�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  P�.   �� ���,�,�h<h.�V.�V.�xf.�Y��� $,4;AHPW^emt{����������������� #*19@HPX_fmu|������������������ #+3;CJRYaiqx�����������������$+3;BJPX_gov~����������������� !)08@GOV]emu|������������������ !(.6>FNU]els{�����������������%,4<DLS[biqy�����������������  '/7?ELS[ciqy�����������������&.3:BJRZbiqy�����������������    & . 3 ; B J Q Y a h o w  � � � � � � � � � � � � � � � �     $ + 3 ; C J R Y a h o v ~ � � � � � � � � � � � � � � � � �    ! ) 1 9 @ G O W ^ e m u } � � � � � � � � � � � � � � � � �    # * 2 : B J O W ^ d l t { � � � � � � � � � � � � � � � � �      % , 3 : B J R Y a i o v } � � � � � � � � � � � � � � � � � $+3:BIPX`gmu}����������������� "*2:BJRYaiow���������������� !(08?FNSZbjqy~�����������������#*19?GNV]emt{�����������������  '.6>DLT[cjrz������������������ #+19AIQY`gov~����������������%-5=DLT[bjrx����������������� "*29AHPW_gov}�����������������$+29@GNU\cjqy~�����������������'/3:AIPW_fnv~����������������� %,4;BJRY`hpw~������������������#+3;BJQY`hov}����������������$,2:AIQY`gnt{����������������� &-5=EMU]dlrz������������������ $,4;CJQYahou|������������������727836268835863037951212988918206356137173111246639146544357402802832236142372686240436828890966358061763181056704814440007133258715196150189876981474971219515277160470461277419517359088125846037557839571298513607040116417678188335571119217225139906743856589591621159314612897922436311407897446150272037901113053499812771441793816961799165275683689676263741648124621542571562537881226356545157433476541143253745864728137568093079068558919810381472581676181723531348867072521994938819169097888167109479497567341836737129952595367988189866241258819412276858106162461918810415983852499738619064217310989913454633169124701527907025807301002050996414121247707013394860124651430606217856753814097715030584188935211578792919219941762306416409782147529275715848903847416497847125557604493613875021316687018783011997222718749955118393414632808140193091784191105642888592641571240017986970618966113635894972268314743373673565089774885112401176621818609520174183019525658749465910126685144106451597185559508255264699578603376687401267610935160991492149886189291348801011172339130664513497032149652575121876110375642819308656505913177188114108321947908159810301503092522470655193231063859862295728168282956026283593683912323121129761448056117414212250865736922158431675355145131919837519948209473245209561047637377133283662097842923964043168581001729641919540779101597029239574182469461643837716066533226326183384711353886845852878938384127593391265652013706223245236213574996835699519341847699751773668115842972844219510489538187860214802206746499535347355308610133657429271303705811874055521598532612981884157258001249483576071361942751013838238493560144028951010454911704355762675102001361838566325392631190592114436176178741717887350190746431752116717271361344246944143241330528218395668293562317613972844113733468711579771816062235596901911925943152028501667828344501071674764606354178971691374714516733719235507157862896305986539833136799699874198166786172895605949641187791971536991734658056551901616292317645500111915561007998961421711287209210119689140440561346837118075140104021941698898712048005277828940581163581101370490911799671158863531263057060963181383011714444008955352715005555792783734272401672495771576801186271211387446108324066572330153689321767658710274745118423861164701721627921784131335754121362538884320227476035555576187106331484253758902159335372189098113169927052393180300741948060360759391363305162986191431843918030492570547910301023141195501572866710327002127710932622899186574361033628852209155690411726797915328230757862411498530139805538470452021327277159318271174974026234408691817539611733181120121136524608148345616962462113234744383908363831062948411899845817659165693867482765113953250173231916240764113007695037058518184711509342158181713870752632180416957004273057810855530185927822484431972230915475302184744582798051677618612109054135301888095036672558611671390157455923083689138274811190364118335131472195411781467479277967884532058351876506317211943180704525553651189826021119858128912274167075178258921411698469287939984730150259001491993812823896104906721304826715156036382045157838651250611214764764118723784679113714738601476938027117654384127112069468474394470210535311681849212346048185761176530284163257828543858574528955732581882809745217896321250164084841461329391709841699325111298772193002399608511826272456981284204051676439944548538902001900673116044405148746138619293161114411504714891560697560551825075921469968212764498265100602864021416556534137242288174306136955285071341753720151417971642750782528641317865862162581504634817682744645520837761684053108956879529963582454347133756752763427176178927867508361594710075476137440423780053452812107176301834239119537172562040616964702146217941823581998255141561655197042755447906496961311613170181181056118842105940751220653844467936015547874147160120191747380710231932787685215846697184990391660253115119997150172211076689520551681798181716121563394543190049821821988213094946192805681820974411023627127631611741170614698148159874601747078515532101863105175820111684991553550771943002018274839993876887771431850586830809351210833539502761721448611252215237797248703571670136222479681746714502444117367493977740134946165104713661223847844910138384110708201255777213233925541370398209326469548149476391060113817908149760561624165112396585131106651297303514827192291746416509532417497472362188694011832413129305196211421437520729609401790480646578921174195916636359141377778027701658220118662948199412022655921273891232069153519385169213681810039612693524106193084079553385388727409547192826162991331787161323337713368256193625861271215754241305882904633760812996969168231154278601852554219182126884923613133410924621517718497108661671690475716817209141140741208873471304055226065493846524928654751611628734592760529627918666434037253952720114102969618390154138822471297648395341729628468361625918297510132560041899561378033516461696178542491216417714118629213069773044791706948563183631844505411623700106622441356129092359811357502111148823700452556717881916209316938514577186052535041752172915606636127559531259879210303507319696814986815629788097949188502383105236461050889611515153893784416971282135064066242968669391018178113152360796858043741003105534011582758189040282846467173570631692176015968359597799191213535621730675382513740528252975343701841037374478409173726801163099761370164539625865668035612719214199745181669974688046109315186163070133859895119194177068041944143010860122278465845678725365442513472814139677172965841488612016455566105881717666227190223921107643317468254105621281942207123811219073213130389613180484159561982662087158431497290489547616947332701637491149654832941543125885492955520255091468470924619960436545622650142318167851215082377113371551472470727875416319364611954917325644243917256097524293451787290868653321366359586557026056218949226113289712911526160011812626138952610615614374146382701603644865126973710554876012808247733815935682781832086790688541393523814381887158686871608586952004071165106465757741393624229196839490428418769325571941755806515426071132216111595016132356081762947838217391755934876734221020626912057737184172021662583698055631269487112147475759190160717921565878434897048996476152182101560934986305848868525828604499147263371369115921409339661226811170235666373587017286979446120063057161990178441145172841936026414461711706126816001552104743519136671651855897111615512181127878871437079215771944817952116186563806436210988588845942312771961476939570312864078215132572001058483057642411647243614237390831931514323110160347339213696110684611195168616152228130472733311016649917113858335162085221189864177102531715293684728845516151271121635800610362972285830812339137120581631860729423942946312154130572137562411689391110699368921911727910172728121474451599059216026516801711818325379178705643303465348782014534074153514375361346155826831046636912163492706533308080634078127823663159625297072289174133771831118313170764111169841346611312305246464518112426456882152156446067641171391685418159657347185891984847892621538402395208001562774131111411493509761414819377129105614161363224257580713193854111748961664239067627194512065137020451585679910347648111374302939936174484557945296221726819476856138283292662464810851224258799166952512293198963757895391275035915556538188512454944823122769433038596456117643939616018437118665774812865173013648385264634851200157563510021273615410887969�S}9T��2�?� �B��B��������������������#`INKQP�U�U�����4���v �=�?H Nq]�b&{E|ŁA���r�� �O�|� �l�\�;������,=CH�p�r�z���/���~�^�˽&�a�h������%3�90A�L�^��e���k�,���F�" � x��d �.Y0�125�I�]�e�k؍6� �j�"���k�j�L��������_���������f�� �P7�"��!o*W7�8�B�E�M�X%�U�p�����9�i�j�������G���I{  S�S�r�3����7�A���[�9���T�%(�)�*�0�KR�b@f����P�Ĝ���������� �������� p �F ]M �Q �W D\ �\ ;] �] d g g{ < Ά "� � � Ŀ ~� W� �� X� � n� ~� �� !�  | G  � � �9 n@ >J �K :N �Q #S �T tX �e ff �g l �z ߁ M� � � �� � � �� (� �� f� �� �� � 2� �� �� l� F p �w y k~ �~ �� � � � � � S� 8� l� �� � Q� �� �� �� � �# ) a) �? FA �B �B &D �j wn �~ � � s� �� j� T� b� � g� � �� � �# U$ �2 �P �X /\ �\ ] c �c ^f -j �l  ^� H� �� M� E� � >� /� [� �� �� G� �� � �� U� �� �� R� ;� �� C� �� $� "� 0W`De�w y~{.�W�n�R��������������m���6�P����� �����x � PK�-�Md"t$M+�,Q0�3�V?Yd����,���������4 !�1�2g45�6N8�@�D�JK"M|W2X�_hv�w�xdy„.�����2��e��K���L����Y�`�N�i�U��,�2i7�9�QWT[@`ݍ��ՐA�I������e&t(�)e+�5�;�=A?AE�L�O9P�P�dSft����<�R�����F�G�������&�#���K,�D!EyV�_B`�c�fh�r2s�t�ć��d�Ω���������1+4]=�Ky]b�b�d4i�i�kasuu��ͦ�� �D�$p�R�ʧ_�������[����<�U��������;������K�ߑ��� �W�Ȣ��������(�R'�Z �:+`-`=�=7FwHJ�g�h�n�o`q xЀ��N�����G� �H������v��w b@�22x>�BmG�K�L�MO�R�e�f,i{����%�v�����������U���#�����"{%�&�1/3�4�:'DwMkP�d�hʅo�&���˹$�����������;���g7* w'�*&+z_;`Y`He/kzlCm&�y��,����I�j%j/�2d?F@BVB9M�U�\6^@bpj�oju��$���L�D�������!�DqMNh�L ,@ �A GH S^ �a �b Gc �s � ݌ p� � � �F!�G!�N!�V!�X!hZ!^!�b!od!��!�!��!G�!j�!_�!#"w("�/":4"=5"�?">B"C"�C"d"ff"gm"d�"-�"ܺ"E�"��"��"J�"��"��"/�"�"��"��"��"l�"_�"h#z'#�(#�6#=:#A?#�A#�D#�G#zI#�J#P#�U#�V#�Z#�]#�`#�o# t#��#�#'�#�#q�#E�#f�#��#��#��# �#C�#�#��#S�#��#��#�$� $i$O$�$�$Q $\L$hN$�Q$T$�T$�[$(-&L9&�?&�G&=P&�i&j&�j& q& u&z&?�&4�&�&��&��&x�& �&@�&�'7'6'E0'�3'j4':9't?'�A'�S'�c''{'�~'S�'҇'L�'�'W�'!�'b�'-�'ɶ'J�'w3(�@(�B(�`(ec(�o(��(I�(u�(}�(�(1�(�( �(��(��(�(��(��(��(K�(G)�)�)�)%)� )J$)�&)ZL)m�)Ԋ)>�)~�)Ħ)�)ɬ)��)�*�*�*�*0*�7*69*':*o?*�A*BG*�W*8\*�k*Fp*Pu*�*�*i�*��*��*$�*�*�*Ԗ*��*��*��*��*m�+��+��+��+�+N.,g/,9,�R,k],�d,�i,eu,�y,�z,2�,U�,y�,x�,l�,�,l�,ӛ,��,P�,�,?�,��, �,��,�,��,v�,��,-�,��,�,��,��, �,d#-�%-�0->1-CI-9J-�O-�P-�S-�[-�]-�]-�^-(-�-��-�-��-�-�-��-��-��-G�-;�-��-�-�-��-��-0�-9�-��-!�-- .� .h.Infineon/mtb-hal-cat2 /* @ @licstart The following is the entire license notice for the JavaScript code in this file. Copyright (C) 1997-2017 by 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. @licend The above is the entire license notice for the JavaScript code in this file */ var NAVTREE = [ [ "Hardware Abstraction Layer (HAL)", "index.html", [ [ "Hardware Abstraction Layer", "index.html", null ], [ "HAL API Reference", "modules.html", "modules" ] ] ] ]; var NAVTREEINDEX = [ "group__group__hal.html", "group__group__hal__dma.html#gga430c1e3ddedade3b6f7ef1f8532e665ba1226b2af396731bd8b959c14924bb612", "group__group__hal__impl__clock.html#ga8de1c7c9af68d66399b5d10652b54d5f", "group__group__hal__impl__hw__types.html#structcyhal__wdt__t", "group__group__hal__impl__pin__package__ccg7d__68__qfn.html#gga304a565dc0d34e417918b505c5f70cb3a12c69ba58f68ac9252a9e84170e354c7", "group__group__hal__impl__pin__package__pmg1s0__24__qfn__pmg1__s0.html#gaee2c88a47b2513d84e993ca48a2ceb6f", "group__group__hal__impl__pin__package__pmg1s2__42__csp__pmg1__s2.html#ga9d22e10f1e8ba302d4b81a9fe929d9f6", "group__group__hal__impl__pin__package__pmg1s3__97__bga__cypd8225.html#ga54fb88fc8ad6956e7bc00e5718e53e39", "group__group__hal__impl__pin__package__pmg1s3__97__bga__cypm1322.html#gafd51be129e3d547477caa66ba0c6bf66", "group__group__hal__impl__pin__package__psoc4000s__25__wlcsp.html#gaa6612569e815c238b02340222fef2867", "group__group__hal__impl__pin__package__psoc4000s__32__tqfp.html#gabead3206b864cdf64b5b4b34d2b2e581", "group__group__hal__impl__pin__package__psoc4100s__28__ssop__auto.html#ga2b6f3b9a4229f16e16191644d7a021ec", "group__group__hal__impl__pin__package__psoc4100s__35__wlcsp.html#ga9f1267e1d5dcd2bb8ef2cc7fbf4af828", "group__group__hal__impl__pin__package__psoc4100s__40__qfn.html#ga7d27f7a1370334611ac7967afa4d5f15", "group__group__hal__impl__pin__package__psoc4100s__44__tqfp.html#ga447743b6c0ccd0c9d70897c08d714c1a", "group__group__hal__impl__pin__package__psoc4100smax__100__tqfp.html#ga5fa96d027cccf8a49dfed175368f47aa", "group__group__hal__impl__pin__package__psoc4100smax__48__tqfp.html#gga42db97a7fe7bbbb01fe18ce6cdeb2fdca33daef487e90b1d8ee897624249d060e", "group__group__hal__impl__pin__package__psoc4100sp256kb__48__tqfp.html#gae5613df619f121c9177ab692ad7cebf5", "group__group__hal__impl__pin__package__psoc4100sp256kb__64__tqfp.html#gaf7ee1fc593d5955a24696f1565ea82c9", "group__group__hal__impl__pin__package__psoc4100sp__40__qfn__2.html#gaa4a0b9678341c62534d22b954a825e8a", "group__group__hal__impl__pin__package__psoc4100sp__48__tqfp.html#gaa7e9e2f14a0eea38e8c933aefb2f9693", "group__group__hal__impl__pin__package__psoc4100sp__64__tqfp.html#ga54e48d58c2a0ca7b205fa0868a41844c", "group__group__hal__impl__triggers__pmg1s3.html#ga90d2899b76493f2bdf36f1b42c134e84", "group__group__hal__impl__triggers__pmg1s3.html#gga9f1b9789bf38e1c6a4cd386ed5c0bc38af1fa56f55f11a72ef120a97e7405f5d7", "group__group__hal__impl__triggers__psoc4100smax.html#ggaac7073cbe7e284fc3fd3a6bc685ea41ea15da1319b00ebc1fa67de1585ad8242c", "group__group__hal__impl__triggers__psoc4100sp.html#ggad5f72222aa7cadda0ebc5497b5df8faca505a97cc32aa50bb9ca0471b34cd19e5", "group__group__hal__impl__triggers__psoc4100sp256kb.html#gga2ad0b16d940b552b7539b3046a699437ad647ae44355800cdc56ac46254747328", "group__group__hal__results__gpio.html#ga19912c1eeef06c15655d0d234ec9bd2c", "group__group__hal__syspm.html#ga299e36096b0ad36b29afe3c5bb02a6d7", "group__group__hal__uart.html#a70b51afc79e56af7360a9b35de3fdb0e" ]; var SYNCONMSG = 'click to disable panel synchronisation'; var SYNCOFFMSG = 'click to enable panel synchronisation';// Copyright (C) 2017 . All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-function-definitions-runtime-semantics-iteratorbindinginitialization description: A new declarative environment is created, from the originalEnv, for each parameter. info: | Runtime Semantics: IteratorBindingInitialization FormalParameter : BindingElement ... 6. Let paramVarEnv be NewDeclarativeEnvironment(originalEnv). ... features: [arrow-function, default-parameters] ---*/ var y; function f(a = eval("var x = 1; y = 42; x"), b = x) {} assert.throws(ReferenceError, () => { f(); }); assert.sameValue(y, 42); import React from "react"; import Alert from "./alert"; export default class FormContact extends React.Component { constructor(props) { super(props); this.submitForm = this.submitForm.bind(this); this.state = { status: "" }; } render() { const { status } = this.state; return (
); } } import util from 'util'; import clearModule from 'clear-module'; import FixtureStdout from 'fixture-stdout'; import stripAnsi from 'strip-ansi'; import test from 'ava'; const stderr = new FixtureStdout({ stream: process.stderr }); let updateNotifier = require('..'); test.before(() => { ['.', 'is-npm'].forEach(clearModule); ['npm_config_username', 'npm_package_name', 'npm_config_heading'].forEach(name => { delete process.env[name]; }); process.stdout.isTTY = true; updateNotifier = require('..'); }); function Control() { this.packageName = 'update-notifier-tester'; this.update = { current: '0.0.2', latest: '1.0.0' }; } util.inherits(Control, updateNotifier.UpdateNotifier); let errorLogs = ''; test.beforeEach(() => { stderr.capture(s => { errorLogs += s; return false; }); }); test.afterEach(() => { stderr.release(); errorLogs = ''; }); test('use pretty boxen message by default', t => { const notifier = new Control(); notifier.notify({defer: false, isGlobal: true}); t.is(stripAnsi(errorLogs), ` ╭───────────────────────────────────────────────────╮ │ │ │ Update available 0.0.2 → 1.0.0 │ │ Run npm i -g update-notifier-tester to update │ │ │ ╰───────────────────────────────────────────────────╯ `); }); test('exclude -g argument when `isGlobal` option is `false`', t => { const notifier = new Control(); notifier.notify({defer: false, isGlobal: false}); t.not(stripAnsi(errorLogs).indexOf('Run npm i update-notifier-tester to update'), -1); }); bsherrill480/portfoliotest/server_unit/db/model/reminder/reminder_util_spec.js const reminderUtil = require('../../../../../server/db/model/reminder/reminder_util'), eventGeneratorConsts = require('../../../../../server/db/model/event_generator/event_generator_consts'), reminderConsts = require('../../../../../server/db/model/reminder/reminder_consts'), models = require('../../../../../server/db/model/models'), eventGeneratorAPI = models.eventGeneratorAPI, reminderAPI = models.reminderAPI, userTestUtil = require('../../../test_util/user_test_util'), moment = require('moment'); function mockEventGenerator(now) { return { question: 'foo', date: now.toDate(), intervalYear: 0, intervalMonth: 0, intervalDay: 1, isReoccurring: true, generatorType: eventGeneratorConsts.HOMEOWNER }; } // getting a hundreth second difference, probably from conversions and subtractions function expectDatesTheSameWithinEpsilon(date1, date2, epsilon) { const expectedReminderPlusEpsilon = moment(date2).add(epsilon, 'second'), expectedReminderMinusEpsilon = moment(date2).subtract(epsilon, 'second'); expect( moment(date1).isBetween( expectedReminderMinusEpsilon, expectedReminderPlusEpsilon ) ).toBeTruthy() } describe('shouldSetNextEventDate', function () { it('should require both interval and isReoccurring', function () { const now = moment(), nextEventDate = moment(now).add(1, 'second'), expectedReminderDate = moment(nextEventDate) .subtract(reminderUtil._SEND_REMINDER_DIFF, 'hour'), epsilon = 1, eventGenerator = { _user: '123', _id: 'abc', nextEventDate: nextEventDate }, reminderDates = reminderUtil._generateReminderDatesFromEventGenerator(eventGenerator), reminderDate = reminderDates[0]; expect(reminderDates.length).toBe(1); expectDatesTheSameWithinEpsilon(reminderDate.date, expectedReminderDate, epsilon); expect(reminderDate.type).toBe(reminderConsts.EMAIL); expect(reminderDate._user).toBe(eventGenerator._user); expect(reminderDate._eventGenerator).toBe(eventGenerator._id); }); // testing generateAndSaveRemindersFromEventGenerator by calling updateEventGenerator // could also be moved to eventGeneratorAPI it('should create a reminder', function (done) { userTestUtil.generateAndSaveTestUser() .then(function (testUser) { const now = moment(); eventGeneratorAPI .createEventGenerator(testUser._id, mockEventGenerator(now)) .then(function (eventGenerator) { reminderAPI.findReminderByEventGenerator(eventGenerator._id) .then(function (reminders) { expect(reminders.length).toBe(1); const reminder = reminders[0], expectedReminderDate = moment(now).subtract( reminderUtil.SEND_REMINDER_DIFF, 'hour' ); expect(reminder._user.toString()).toBe(testUser._id.toString()); expect( reminder._eventGenerator.toString() ).toBe(eventGenerator._id.toString()); expectDatesTheSameWithinEpsilon( reminder.date, expectedReminderDate, 1 ); done() }) .catch(done.fail) }) .catch(done.fail); }) .catch(done.fail); }); // testing generateAndSaveRemindersFromEventGenerator by calling updateEventGenerator // could also be moved to eventGeneratorAPI it('should create a reminder and allow it to be updated', function (done) { userTestUtil.generateAndSaveTestUser() .then(function (testUser) { const now = moment(); eventGeneratorAPI .createEventGenerator(testUser._id, mockEventGenerator(now)) .then(function (eventGenerator) { eventGenerator.date = moment(now).add(1, 'month').toDate(); eventGeneratorAPI.updateEventGenerator(eventGenerator._id, eventGenerator) .then(function () { reminderAPI.findReminderByEventGenerator(eventGenerator._id) .then(function (reminders) { expect(reminders.length).toBe(1); const reminder = reminders[0], expectedReminderDate = moment(now) .subtract( reminderUtil._SEND_REMINDER_DIFF, 'hour' ) .add(1, 'month'); expect( reminder._user.toString() ).toBe(testUser._id.toString()); console.log(moment(reminder.date), expectedReminderDate); expectDatesTheSameWithinEpsilon( reminder.date, expectedReminderDate, 1 ); done(); }) .catch(done.fail); }) .catch(done.fail); }) .catch(done.fail); }) .catch(done.fail); }); }); NoSyntaxError-FE/noSyntaxError-uiconfig/utils.js1-10 import { readdirSync } from 'fs' import { resolve } from 'path' //读取components文件夹下的组件,方便多入口打包 export function getFileName() { const path = resolve('src/components') try { const files = readdirSync(path) return files } catch (error) { console.error(error) return [] } } export default state => state.collectingEventIdentifier //const myApp. = require('../app/library.js'); (function(){ 'use strict'; const myApp = require('../app/library.js'); describe("Determine the sequence of an array of numbers: ", function() { describe("Case for an empty array", function() { it("should return 0 for an empty array", function() { expect(myApp.aritGeo([])).toEqual(0); }); }); describe("Case for an arithmetic sequence", function() { it("should return `Arithmetic` for [2, 4, 6, 8, 10]", function() { expect(myApp.aritGeo([2, 4, 6, 8, 10])).toEqual('Arithmetic'); }); it("should return `Arithmetic` for [5, 11, 17, 23, 29, 35, 41]", function() { expect(myApp.aritGeo([5, 11, 17, 23, 29, 35, 41])).toEqual('Arithmetic'); }); it("should return `Arithmetic` for [15, 10, 5, 0, -5, -10]", function() { expect(myApp.aritGeo([15, 10, 5, 0, -5, -10])).toEqual('Arithmetic'); }); }); describe("Case for a geometric sequence", function() { it("should return `Geometric` for [2, 6, 18, 54, 162]", function() { expect(myApp.aritGeo([2, 6, 18, 54, 162])).toEqual('Geometric'); }); it("should return `Geometric` for [0.5, 3.5, 24.5, 171.5]", function() { expect(myApp.aritGeo([0.5, 3.5, 24.5, 171.5])).toEqual('Geometric'); }); it("should return `Geometric` for [−128, 64, −32, 16, −8]", function() { expect(myApp.aritGeo([-128, 64, -32, 16, -8])).toEqual('Geometric'); }); }); describe("Case for neither arithmetic nor geometric sequence", function() { it("should return -1 for [1, 2, 3, 5, 8]", function() { expect(myApp.aritGeo([1, 2, 3, 5, 8])).toEqual(-1); }); it("should return -1 for [1, 3, 6, 10, 15]", function() { expect(myApp.aritGeo([1, 3, 6, 10, 15])).toEqual(-1); }); it("should return -1 for [1, 8, 27, 64, 125]", function() { expect(myApp.aritGeo([1, 8, 27, 64, 125])).toEqual(-1); }); }); }); describe('Min-Max Numbers in a List: ', function () { describe('Return the min and max number in the list in a new list follows `[min, max]`', function () { it('should return [1,4] for [1, 2, 3 , 4]', function () { expect(myApp.findMinMax([1, 2, 3, 4])).toEqual([1, 4]); }); it('should return [4, 6] for [6, 4]', function () { expect(myApp.findMinMax([6, 4])).toEqual([4, 6]); }); it('should return [2, 78] for [4, 66, 6, 44, 7, 78, 8, 68, 2]', function () { expect(myApp.findMinMax([4, 66, 6, 44, 7, 78, 8, 68, 2])).toEqual([2, 78]); }); }); describe('Return the number in the list in a new list follows `[min]` when the number is the min and max number in that list', function () { it('should return [4] for [4, 4, 4, 4]', function () { expect(myApp.findMinMax([4, 4, 4, 4])).toEqual([4]); }); }); }); })();Harshagracy/sp-dev-fx-webparts100-1000 //# sourceMappingURL=IPropertyPaneHTMLInternalProps.js.mapmodule.exports = { title: 'example', SERVER_ROOT: 'http://localhost:4040', EVENT_EXT: '/api/example/export_events/deeprows', CATEGORY_EXT: '/api/example/export_categories/rows', NARRATIVE_EXT: '/api/example/export_narratives/rows', SOURCES_EXT: '/api/example/export_sources/deepids', TAGS_EXT: '/api/example/export_tags/tree', SITES_EXT: '/api/example/export_sites/rows', SHAPES_EXT: '/api/example/export_shapes/columns', INCOMING_DATETIME_FORMAT: '%m/%d/%YT%H:%M', MAPBOX_TOKEN: 'pk.EXAMPLE_MAPBOX_TOKEN', features: { USE_TAGS: false, USE_SEARCH: false, USE_SITES: true, USE_SOURCES: true, USE_SHAPES: true, CATEGORIES_AS_TAGS: true }, store: { app: { mapAnchor: [31.356397, 34.784818], filters: { // timerange: [ // new Date(2015, 7, 9), // new Date(2015, 10, 6, 23) // ] } }, ui: { style: { categories: {}, shapes: {}, narratives: {} } } } } import React from 'react' import PropTypes from 'prop-types' import { graphql } from 'gatsby' import styled from 'styled-components' import { Layout, ArticleGrid, PortfolioPageListing, SEO } from '../components' const PortfolioGrid = styled.div` grid-area: intro; flex-direction: column; justify-content: space-evenly; grid-gap: 2rem; align-items: center; display: grid; padding: 0.25rem; grid-template-columns: repeat(auto-fill, minmax(45%, 1fr)); grid-auto-rows: 1fr; @media (max-width: 1024px) { grid-template-columns: repeat(auto-fill, minmax(90%, 1fr)); } @media (min-width: 1024px) and (max-width: 1800px) { padding: 1rem; } @media (min-width: 1800px) { grid-gap: 4rem; padding: 2rem; } ` const PortfolioPage = ({ data, location }) => { const items = data.allPrismicProject.edges.map(project => ( )) return ( {items} ) } PortfolioPage.propTypes = { location: PropTypes.object.isRequired, } export default PortfolioPage export const query = graphql` query PortfolioPageQuery { allPrismicProject(sort: { fields: [data___order], order: ASC }) { edges { node { id uid data { title { text } snippet scope { scope_item { text } } main_image { localFile { childImageSharp { fluid(maxWidth: 2500) { ...GatsbyImageSharpFluid_noBase64 } } } } } } } } } ` lyf-coder/bot-sdk-node.jslib/directive/DPL/Commands/SetPageCommand.js /** * @file 页面切换指令 * @author */ /** * Copyright (c) 2017 Baidu, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * @class SetPageCommand 页面切换指令 * @extends {BaseCommand} * @example * let setPageCommand = new SetPageCommand() * setPageCommand.setPosition('relative'); * setPageCommand.setValue(1); * setPageCommand.setComponentId('componentId'); */ const BaseCommand = require('./BaseCommand'); class SetPageCommand extends BaseCommand { /** * SetPageCommand 构造方法. */ constructor() { super('SetPage'); } /** * 设置属性值 * * @param {string} position 相对或者绝对 * @public */ setPosition(position = 'relative') { if (SetPageCommand.positionArr.indexOf(position) !== -1) { this.data.position = position; } } /** * 设置切换步长 * * @param {number} value 步长 * @public */ setValue(value) { if (typeof value === 'number') { this.data.value = value; } } } SetPageCommand.positionArr = [ 'relative', 'absolute' ]; module.exports = SetPageCommand; (function () { 'use strict'; angular .module('everquizApp') .service('quizService', quizService); quizService.$inject = ['$http', 'authFactory', 'profileFactory', 'categoryService']; function quizService($http, authFactory, profileFactory, categoryService) { var self = this; self.lastResult = null; self.quizzes = []; self.activeQuiz = null; self.id = authFactory.currentUserId(); self.display = !!self.id; self.isVisible = isVisible; self.showQuizzes = showQuizzes; self.hideQuizzes = hideQuizzes; self.checkResult = checkResult; self.get = get; self.getQuizzes = getQuizzes; self.getQuizzesByQuery = getQuizzesByQuery; self.getQuestions = getQuestions; self.getAll = getAll; self.create = create; self.unactive = unactive; self.active = active; self.update = update; self.getDifficulties = getDifficulties; self.getComplexity = getComplexity; self.difficulties = [ {_id: 0, title: 'Novice'}, {_id: 1, title: 'Advanced'}, {_id: 2, title: 'Expert'} ]; /** * For user section */ function getQuizzes() { return $http.get('/api/v1/Quizzes?populate=category&status=1', { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }) .then(function (res) { return res.data; }); } function getQuizzesByQuery(query) { return $http.get('/api/v1/Quizzes?populate=category&status=1' + query, { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }) .then(function (res) { return res.data; }); } function getQuestions(id) { return $http.get('/api/v1/Questions?quiz=' + id + '&populate=answers', { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }) .then(function (res) { return res.data; }); } function checkResult(result) { return $http.put('/checkresult', result, { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }) .then(function (res) { self.lastResult = Math.round(res.data.result * 100); profileFactory.updateProfile(); return res.data; }) } /** * For admin section */ function getAll() { $http.get('/api/v1/Quizzes?populate=category&select=category._id,category.title', { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }) .then(function (res) { angular.copy(res.data, self.quizzes); }); return self.quizzes; } function get(id) { return $http.get('/api/v1/Quizzes/' + id + '?populate=questions', { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }) .then(function (res) { return res.data; }); } function create(quiz) { return $http.post('/api/v1/Quizzes', quiz, { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }).success(function (data) { categoryService.get(data.category).then(function (res) { data.category = res; self.quizzes.push(data); }); }); } function unactive(quiz) { quiz.status = 0; return $http.put('/api/v1/Quizzes/' + quiz._id, quiz, { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }); } function active(quiz) { quiz.status = 1; return $http.put('/api/v1/Quizzes/' + quiz._id, quiz, { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }); } function update(quiz) { return $http.put('/api/v1/Quizzes/' + quiz._id, quiz, { headers: {Authorization: 'Bearer ' + authFactory.getToken()} }); } function getDifficulties() { return self.difficulties; } function getComplexity(complexity) { for (var i = self.difficulties.length - 1; i >= 0; i--) { if (self.difficulties[i]._id === complexity) { return self.difficulties[i].title; } } } function isVisible () { return self.display; } function showQuizzes() { self.display = true; } function hideQuizzes() { self.display = false; } } })();ReAleR09/towel-sort0 // You should implement your task here. module.exports = function towelSort (matrix) { if (!(matrix instanceof Array) || matrix.length === 0) { return []; } const result = []; for (const row in matrix) { result.push( ...((row % 2 === 0) ? matrix[row] : matrix[row].reverse()) ); } return result; } import cn from 'classnames'; export function Header({ children, className, }) { return (
{ children }
); } export function Body({ children }) { return (
{ children }
); } export const deleteKartuSehat = (documentID) => { return (dispatch, getState, { getFirebase, getFirestore }) => { const fs = getFirestore(); const fb = getFirebase(); var storageRef = fb.storage().ref(); storageRef.child("kartusehat/" + documentID).delete(); fs.collection("kartusehat").doc(documentID).delete(); }; }; export const tambahKartuSehat = (data) => { return (dispatch, getState, { getFirebase, getFirestore }) => { const fs = getFirestore(); const fb = getFirebase(); var storageRef = fb.storage().ref(); let file = data.image; delete data.image; let metaData = { contentType: "image/jpeg", }; fs.collection("kartusehat") .add({ ...data, created_at: new Date().toISOString(), }) .then((docRef) => { var uploadTask = storageRef .child("kartusehat/" + docRef.id) .put(file, metaData); uploadTask.on( fb.storage.TaskEvent.STATE_CHANGED, function (s) { let progress = (s.bytesTransferred / s.totalBytes) * 100; dispatch({ type: "PROGRESS_LOAD", progressVal: Math.round(progress), }); }, function (err) {}, function () { uploadTask.snapshot.ref .getDownloadURL() .then((url) => { fs.collection("kartusehat").doc(docRef.id).update({ image: url, }); }) .then(() => { dispatch({ type: "UPLOAD_FINISH", }); }); } ); }); }; }; export { default as Img } from './Img' export { default as SplashScreen } from './SplashScreen' export * from './Toast' import { StyleSheet } from 'react-native' export const isStyleRow = style => { const flatStyle = StyleSheet.flatten(style || {}) return flatStyle.flexDirection !== 'column' } const getDashStyleId = ( { dashGap, dashLength, dashThickness, dashColor }, isRow, ) => `${dashGap}-${dashLength}-${dashThickness}-${dashColor}-${ isRow ? 'row' : 'column' }` const createDashStyleSheet = ( { dashGap, dashLength, dashThickness, dashColor }, isRow, ) => { const idStyle = StyleSheet.create({ style: { width: isRow ? dashLength : dashThickness, height: isRow ? dashThickness : dashLength, marginRight: isRow ? dashGap : 0, marginBottom: isRow ? 0 : dashGap, backgroundColor: dashColor, }, }) return idStyle.style } let stylesStore = {} export const getDashStyle = props => { const isRow = isStyleRow(props.style) const id = getDashStyleId(props, isRow) if (!stylesStore[id]) { stylesStore = { ...stylesStore, [id]: createDashStyleSheet(props, isRow), } } return stylesStore[id] } tools/watch.js1-10 const runWatch = require('./run-watch') const watchConfig = require('../build.config').watch runWatch(watchConfig) 0x13-javascript_objects_scopes_closures/9-logme.js #!/usr/bin/node /* 9-logme.js */ exports.logMe = function (item) { if (this.count === undefined) { this.count = 0; } console.log(this.count + ':', item); this.count++; }; bruslim/torrentmeta /*jshint node: true */ 'use strict'; var test = require('tape'); var MetaInfo = require('../index.js'); var fs = require('fs'); var path = require('path'); var bigint = require('bigint'); test("Single File MetaInfo",function(t){ var raw = fs.readFileSync(path.join(__dirname,'test.torrent')); var info = MetaInfo.parse(raw); var torrent = info.asTorrent(); t.test('should have values', function(t) { t.assert(torrent.info, 'has an info dictionary'); t.assert(bigint(524288).eq(torrent.info["piece length"]), "info has a piece length"); t.deepEqual(new Buffer('ubuntu-12.04-server-amd64.iso'), torrent.info.name, 'info has a name'); t.assert(bigint(27380).eq(torrent.info.pieces.length), 'info has pieces'); t.assert(bigint(717533184).eq(torrent.info.length), 'info has a length'); t.deepEqual(new Buffer('http://torrent.ubuntu.com:6969/announce'), torrent.announce, 'has an announce'); var announceList = [ [new Buffer('http://torrent.ubuntu.com:6969/announce') ], [new Buffer('http://ipv6.torrent.ubuntu.com:6969/announce') ] ]; t.deepEquals(announceList, torrent['announce-list'], 'has an announce-list'); t.equal(1335433839,torrent['creation date'],'has a creation date'); t.deepEqual(new Buffer('Ubuntu CD releases.ubuntu.com'), torrent.comment, "has a comment"); t.end(); }); t.test('should produce the same bencoded value for test.torrent', function(t) { t.plan(1); t.deepEqual(raw, torrent.bencoded); }); t.test('should produce the sha1 hash for test.torrent', function(t) { t.plan(1); t.deepEqual(new Buffer('1uzfWLWnV8Z2Xok4Eyw1TY0pb5Y=','base64'),torrent.sha1sum); }); t.test('should produce the info hash for test.torrent', function(t) { t.plan(1); t.deepEqual(new Buffer('S19qPlBJSa/hB1gKZ4RDftCb5So=','base64'),torrent.infoHash); }); }); test("Multi File MetaInfo",function(t){ var raw = fs.readFileSync(path.join(__dirname,'multifile.torrent')); var info = MetaInfo.parse(raw); var torrent = info.asTorrent(); t.test('should produce the same bencoded value for multifile.torrent', function(t) { t.plan(1); t.deepEqual(raw, torrent.bencoded); }); t.test('should produce the sha1 hash for multifile.torrent', function(t) { t.plan(1); t.deepEqual(new Buffer('Zmlm9Z8RcPL2nWUqCIix2niugtM=','base64'),torrent.sha1sum); }); });import React, { Component, PropTypes } from 'react'; import { reduxForm } from 'redux-form'; import classNames from 'classnames'; import { confirmDocumentDelete, update as documentUpdate, updatePayload, create as documentCreate } from '../../action/document'; import { push } from 'react-router-redux'; import { Document } from '../../../validation/schema'; import validate from '../../../validation/validate'; import Section from '../../component/ui/section'; import Field from '../../component/ui/field'; import Button from '../../component/ui/button'; import ErrorInput from '../../component/ui/errorInput'; import DropDown from '../../component/ui/dropDown'; import SelectInput from '../../component/ui/selectInput'; import DeviceList from '../deviceList'; import DocumentErrorList from '../documentErrorList'; import __ from '../../lang'; class DocumentEntryForm extends Component { handleDelete(e) { e.preventDefault(); this.props.confirmDocumentDelete(this.props.document); } handleSubmit(values) { if (this.props.creating) { return this.props.documentCreate(values) .then(action => { if (action.error) return; console.log(action); this.props.push(`/documents/${action.payload.result}`); }); } return this.props.documentUpdate(this.props.document.id, values); } handleReset(e) { e.preventDefault(); this.props.resetForm(); } handleUpload() { let fileList = this.fileInput.files; if (fileList.length === 0) return; let file = fileList[0]; let reader = new FileReader(); reader.onload = () => { if (!reader.result) return; this.props.updatePayload(this.props.document.id, reader.result); }; reader.readAsText(file); } render() { const { fields: { name, state, devices }, handleSubmit, invalid, submitting, className, dirty, document, creating } = this.props; const onSubmit = handleSubmit(this.handleSubmit.bind(this)); if (document == null && !creating) return false; return (
{/*Field label={__('DocumentVisibility')}> */} {!creating && (
{document.state !== 'start' ? ( __('DocumentRunningStopped') ) : ( document.running ? ( __('DocumentRunningStarted') ) : ( __('DocumentRunningWait') ) )}
)} {!creating && (
{new Date(document.createdAt).toLocaleString()}
)} {!creating && (
)}
{!creating && ( )} {!creating && (

{__('DocumentSourceSectionHelp')}

)}
{dirty && !creating && ( )}
); } } DocumentEntryForm.propTypes = { handleSubmit: PropTypes.func, fields: PropTypes.object, invalid: PropTypes.bool, submitting: PropTypes.bool, dirty: PropTypes.bool, document: PropTypes.object, className: PropTypes.string, confirmDocumentDelete: PropTypes.func, documentUpdate: PropTypes.func, documentCreate: PropTypes.func, updatePayload: PropTypes.func, resetForm: PropTypes.func, push: PropTypes.func, creating: PropTypes.bool }; export default reduxForm({ form: 'documentEntry', fields: ['name', 'devices', 'visibility', 'state'], initialValues: { visibility: 'private', state: 'stop', devices: [], name: '' }, validate: (values) => { return validate(values, Document, true); } }, null, { confirmDocumentDelete, documentUpdate, updatePayload, documentCreate, push } )(DocumentEntryForm); public/assets/vendors/input-mask/phone-codes/phone-uk.js [ { "mask": "+44(113)-###-####", "cc": "UK", "cd": "United Kingdom", "city": "Leeds" }, { "mask": "+44(114)-###-####", "cc": "UK", "cd": "United Kingdom", "city": "Sheffield" }, { "mask": "+44(115)-###-####", "cc": "UK", "cd": "United Kingdom", "city": "Nottingham" }, { "mask": "+44(116)-###-####", "cc": "UK", "cd": "United Kingdom", "city": "Leicester" }, { "mask": "+44(117)-###-####", "cc": "UK", "cd": "United Kingdom", "city": "Bristol" }, { "mask": "+44(118)-###-####", "cc": "UK", "cd": "United Kingdom", "city": "Reading" }, { "mask": "+44(1200)-######", "cc": "UK", "cd": "United Kingdom", "city": "Clitheroe" }, { "mask": "+44(1202)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bournemouth" }, { "mask": "+44(1204)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bolton" }, { "mask": "+44(1205)-######", "cc": "UK", "cd": "United Kingdom", "city": "Boston" }, { "mask": "+44(1206)-######", "cc": "UK", "cd": "United Kingdom", "city": "Colchester" }, { "mask": "+44(1207)-######", "cc": "UK", "cd": "United Kingdom", "city": "Consett" }, { "mask": "+44(1208)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bodmin" }, { "mask": "+44(1209)-######", "cc": "UK", "cd": "United Kingdom", "city": "Redruth" }, { "mask": "+44(121)-###-####", "cc": "UK", "cd": "United Kingdom", "city": "Birmingham" }, { "mask": "+44(1223)-######", "cc": "UK", "cd": "United Kingdom", "city": "Cambridge" }, { "mask": "+44(1224)-######", "cc": "UK", "cd": "United Kingdom", "city": "Aberdeen" }, { "mask": "+44(1225)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bath" }, { "mask": "+44(1226)-######", "cc": "UK", "cd": "United Kingdom", "city": "Barnsley" }, { "mask": "+44(1227)-######", "cc": "UK", "cd": "United Kingdom", "city": "Canterbury" }, { "mask": "+44(1228)-######", "cc": "UK", "cd": "United Kingdom", "city": "Carlisle" }, { "mask": "+44(1229)-######", "cc": "UK", "cd": "United Kingdom", "city": "Barrow-in-Furness(2,4,5,6,8), Millom(3,7,9)" }, { "mask": "+44(1233)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ashford (Kent)" }, { "mask": "+44(1234)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bedford" }, { "mask": "+44(1235)-######", "cc": "UK", "cd": "United Kingdom", "city": "Abingdon" }, { "mask": "+44(1236)-######", "cc": "UK", "cd": "United Kingdom", "city": "Coatbridge" }, { "mask": "+44(1237)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bideford" }, { "mask": "+44(1239)-######", "cc": "UK", "cd": "United Kingdom", "city": "Cardigan" }, { "mask": "+44(1241)-######", "cc": "UK", "cd": "United Kingdom", "city": "Arbroath" }, { "mask": "+44(1242)-######", "cc": "UK", "cd": "United Kingdom", "city": "Cheltenham" }, { "mask": "+44(1243)-######", "cc": "UK", "cd": "United Kingdom", "city": "Chichester" }, { "mask": "+44(1244)-######", "cc": "UK", "cd": "United Kingdom", "city": "Chester" }, { "mask": "+44(1245)-######", "cc": "UK", "cd": "United Kingdom", "city": "Chelmsford" }, { "mask": "+44(1246)-######", "cc": "UK", "cd": "United Kingdom", "city": "Chesterfield" }, { "mask": "+44(1248)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bangor (Gwynedd)" }, { "mask": "+44(1249)-######", "cc": "UK", "cd": "United Kingdom", "city": "Chippenham" }, { "mask": "+44(1250)-######", "cc": "UK", "cd": "United Kingdom", "city": "Blairgowrie" }, { "mask": "+44(1252)-######", "cc": "UK", "cd": "United Kingdom", "city": "Aldershot" }, { "mask": "+44(1253)-######", "cc": "UK", "cd": "United Kingdom", "city": "Blackpool" }, { "mask": "+44(1254)-######", "cc": "UK", "cd": "United Kingdom", "city": "Blackburn" }, { "mask": "+44(1255)-######", "cc": "UK", "cd": "United Kingdom", "city": "Clacton-on-Sea" }, { "mask": "+44(1256)-######", "cc": "UK", "cd": "United Kingdom", "city": "Basingstoke" }, { "mask": "+44(1257)-######", "cc": "UK", "cd": "United Kingdom", "city": "Coppull" }, { "mask": "+44(1258)-######", "cc": "UK", "cd": "United Kingdom", "city": "Blandford" }, { "mask": "+44(1259)-######", "cc": "UK", "cd": "United Kingdom", "city": "Alloa" }, { "mask": "+44(1260)-######", "cc": "UK", "cd": "United Kingdom", "city": "Congleton" }, { "mask": "+44(1261)-######", "cc": "UK", "cd": "United Kingdom", "city": "Banff" }, { "mask": "+44(1262)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bridlington" }, { "mask": "+44(1263)-######", "cc": "UK", "cd": "United Kingdom", "city": "Cromer" }, { "mask": "+44(1264)-######", "cc": "UK", "cd": "United Kingdom", "city": "Andover" }, { "mask": "+44(1267)-######", "cc": "UK", "cd": "United Kingdom", "city": "Carmarthen" }, { "mask": "+44(1268)-######", "cc": "UK", "cd": "United Kingdom", "city": "Basildon" }, { "mask": "+44(1269)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ammanford" }, { "mask": "+44(1270)-######", "cc": "UK", "cd": "United Kingdom", "city": "Crewe" }, { "mask": "+44(1271)-######", "cc": "UK", "cd": "United Kingdom", "city": "Barnstaple" }, { "mask": "+44(1273)-######", "cc": "UK", "cd": "United Kingdom", "city": "Brighton" }, { "mask": "+44(1274)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bradford" }, { "mask": "+44(1275)-######", "cc": "UK", "cd": "United Kingdom", "city": "Clevedon" }, { "mask": "+44(1276)-######", "cc": "UK", "cd": "United Kingdom", "city": "Camberley" }, { "mask": "+44(1277)-######", "cc": "UK", "cd": "United Kingdom", "city": "Brentwood" }, { "mask": "+44(1278)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bridgwater" }, { "mask": "+44(1279)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bishops Stortford" }, { "mask": "+44(1280)-######", "cc": "UK", "cd": "United Kingdom", "city": "Buckingham" }, { "mask": "+44(1282)-######", "cc": "UK", "cd": "United Kingdom", "city": "Burnley" }, { "mask": "+44(1283)-######", "cc": "UK", "cd": "United Kingdom", "city": "Burton-on-Trent" }, { "mask": "+44(1284)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bury St Edmunds" }, { "mask": "+44(1285)-######", "cc": "UK", "cd": "United Kingdom", "city": "Cirencester" }, { "mask": "+44(1286)-######", "cc": "UK", "cd": "United Kingdom", "city": "Caernarfon" }, { "mask": "+44(1287)-######", "cc": "UK", "cd": "United Kingdom", "city": "Guisborough" }, { "mask": "+44(1288)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bude" }, { "mask": "+44(1289)-######", "cc": "UK", "cd": "United Kingdom", "city": "Berwick-upon-Tweed" }, { "mask": "+44(1290)-######", "cc": "UK", "cd": "United Kingdom", "city": "Cumnock" }, { "mask": "+44(1291)-######", "cc": "UK", "cd": "United Kingdom", "city": "Chepstow" }, { "mask": "+44(1292)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ayr" }, { "mask": "+44(1293)-######", "cc": "UK", "cd": "United Kingdom", "city": "Crawley" }, { "mask": "+44(1294)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ardrossan" }, { "mask": "+44(1295)-######", "cc": "UK", "cd": "United Kingdom", "city": "Banbury" }, { "mask": "+44(1296)-######", "cc": "UK", "cd": "United Kingdom", "city": "Aylesbury" }, { "mask": "+44(1297)-######", "cc": "UK", "cd": "United Kingdom", "city": "Axminster" }, { "mask": "+44(1298)-######", "cc": "UK", "cd": "United Kingdom", "city": "Buxton" }, { "mask": "+44(1299)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bewdley" }, { "mask": "+44(1300)-######", "cc": "UK", "cd": "United Kingdom", "city": "Cerne Abbas" }, { "mask": "+44(1301)-######", "cc": "UK", "cd": "United Kingdom", "city": "Arrochar" }, { "mask": "+44(1302)-######", "cc": "UK", "cd": "United Kingdom", "city": "Doncaster" }, { "mask": "+44(1303)-######", "cc": "UK", "cd": "United Kingdom", "city": "Folkestone" }, { "mask": "+44(1304)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dover" }, { "mask": "+44(1305)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dorchester" }, { "mask": "+44(1306)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dorking" }, { "mask": "+44(1307)-######", "cc": "UK", "cd": "United Kingdom", "city": "Forfar" }, { "mask": "+44(1308)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bridport" }, { "mask": "+44(1309)-######", "cc": "UK", "cd": "United Kingdom", "city": "Forres" }, { "mask": "+44(131)-###-###", "cc": "UK", "cd": "United Kingdom", "city": "Edinburgh" }, { "mask": "+44(1320)-######", "cc": "UK", "cd": "United Kingdom", "city": "Fort Augustus" }, { "mask": "+44(1322)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dartford" }, { "mask": "+44(1323)-######", "cc": "UK", "cd": "United Kingdom", "city": "Eastbourne" }, { "mask": "+44(1324)-######", "cc": "UK", "cd": "United Kingdom", "city": "Falkirk" }, { "mask": "+44(1325)-######", "cc": "UK", "cd": "United Kingdom", "city": "Darlington" }, { "mask": "+44(1326)-######", "cc": "UK", "cd": "United Kingdom", "city": "Falmouth" }, { "mask": "+44(1327)-######", "cc": "UK", "cd": "United Kingdom", "city": "Daventry" }, { "mask": "+44(1328)-######", "cc": "UK", "cd": "United Kingdom", "city": "Fakenham" }, { "mask": "+44(1329)-######", "cc": "UK", "cd": "United Kingdom", "city": "Fareham" }, { "mask": "+44(1330)-######", "cc": "UK", "cd": "United Kingdom", "city": "Banchory" }, { "mask": "+44(1332)-######", "cc": "UK", "cd": "United Kingdom", "city": "Derby" }, { "mask": "+44(1333)-######", "cc": "UK", "cd": "United Kingdom", "city": "Peat Inn" }, { "mask": "+44(1334)-######", "cc": "UK", "cd": "United Kingdom", "city": "St Andrews" }, { "mask": "+44(1335)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ashbourne" }, { "mask": "+44(1337)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ladybank" }, { "mask": "+44(1339)-######", "cc": "UK", "cd": "United Kingdom", "city": "Aboyne(2,3,5,8), Ballater(4,6,7,9)" }, { "mask": "+44(1340)-######", "cc": "UK", "cd": "United Kingdom", "city": "Craigellachie" }, { "mask": "+44(1341)-######", "cc": "UK", "cd": "United Kingdom", "city": "Barmouth" }, { "mask": "+44(1342)-######", "cc": "UK", "cd": "United Kingdom", "city": "East Grinstead" }, { "mask": "+44(1343)-######", "cc": "UK", "cd": "United Kingdom", "city": "Elgin" }, { "mask": "+44(1344)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bracknell" }, { "mask": "+44(1346)-######", "cc": "UK", "cd": "United Kingdom", "city": "Fraserburgh" }, { "mask": "+44(1347)-######", "cc": "UK", "cd": "United Kingdom", "city": "Easingwold" }, { "mask": "+44(1348)-######", "cc": "UK", "cd": "United Kingdom", "city": "Fishguard" }, { "mask": "+44(1349)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dingwall" }, { "mask": "+44(1350)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dunkeld" }, { "mask": "+44(1352)-######", "cc": "UK", "cd": "United Kingdom", "city": "Mold" }, { "mask": "+44(1353)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ely" }, { "mask": "+44(1354)-######", "cc": "UK", "cd": "United Kingdom", "city": "Chatteris" }, { "mask": "+44(1355)-######", "cc": "UK", "cd": "United Kingdom", "city": "East Kilbride" }, { "mask": "+44(1356)-######", "cc": "UK", "cd": "United Kingdom", "city": "Brechin" }, { "mask": "+44(1357)-######", "cc": "UK", "cd": "United Kingdom", "city": "Strathaven" }, { "mask": "+44(1358)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ellon" }, { "mask": "+44(1359)-######", "cc": "UK", "cd": "United Kingdom", "city": "Pakenham" }, { "mask": "+44(1360)-######", "cc": "UK", "cd": "United Kingdom", "city": "Killearn" }, { "mask": "+44(1361)-######", "cc": "UK", "cd": "United Kingdom", "city": "Duns" }, { "mask": "+44(1362)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dereham" }, { "mask": "+44(1363)-######", "cc": "UK", "cd": "United Kingdom", "city": "Crediton" }, { "mask": "+44(1364)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ashburton" }, { "mask": "+44(1366)-######", "cc": "UK", "cd": "United Kingdom", "city": "Downham Market" }, { "mask": "+44(1367)-######", "cc": "UK", "cd": "United Kingdom", "city": "Faringdon" }, { "mask": "+44(1368)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dunbar" }, { "mask": "+44(1369)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dunoon" }, { "mask": "+44(1371)-######", "cc": "UK", "cd": "United Kingdom", "city": "Great Dunmow" }, { "mask": "+44(1372)-######", "cc": "UK", "cd": "United Kingdom", "city": "Esher" }, { "mask": "+44(1373)-######", "cc": "UK", "cd": "United Kingdom", "city": "Frome" }, { "mask": "+44(1375)-######", "cc": "UK", "cd": "United Kingdom", "city": "Grays Thurrock" }, { "mask": "+44(1376)-######", "cc": "UK", "cd": "United Kingdom", "city": "Braintree" }, { "mask": "+44(1377)-######", "cc": "UK", "cd": "United Kingdom", "city": "Driffield" }, { "mask": "+44(1379)-######", "cc": "UK", "cd": "United Kingdom", "city": "Diss" }, { "mask": "+44(1380)-######", "cc": "UK", "cd": "United Kingdom", "city": "Devizes" }, { "mask": "+44(1381)-######", "cc": "UK", "cd": "United Kingdom", "city": "Fortrose" }, { "mask": "+44(1382)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dundee" }, { "mask": "+44(1383)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dunfermline" }, { "mask": "+44(1384)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dudley" }, { "mask": "+44(1386)-######", "cc": "UK", "cd": "United Kingdom", "city": "Evesham" }, { "mask": "+44(1387)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dumfries" }, { "mask": "+44(13873)-####[#]", "cc": "UK", "cd": "United Kingdom", "city": "Langholm" }, { "mask": "+44(1388)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bishop Auckland(3,4,6,7,8,9), Stanhope(2,5)" }, { "mask": "+44(1389)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dumbarton" }, { "mask": "+44(1392)-######", "cc": "UK", "cd": "United Kingdom", "city": "Exeter" }, { "mask": "+44(1394)-######", "cc": "UK", "cd": "United Kingdom", "city": "Felixstowe" }, { "mask": "+44(1395)-######", "cc": "UK", "cd": "United Kingdom", "city": "Budleigh Salterton" }, { "mask": "+44(1397)-######", "cc": "UK", "cd": "United Kingdom", "city": "Fort William" }, { "mask": "+44(1398)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dulverton" }, { "mask": "+44(1400)-######", "cc": "UK", "cd": "United Kingdom", "city": "Honington" }, { "mask": "+44(1403)-######", "cc": "UK", "cd": "United Kingdom", "city": "Horsham" }, { "mask": "+44(1404)-######", "cc": "UK", "cd": "United Kingdom", "city": "Honiton" }, { "mask": "+44(1405)-######", "cc": "UK", "cd": "United Kingdom", "city": "Goole" }, { "mask": "+44(1406)-######", "cc": "UK", "cd": "United Kingdom", "city": "Holbeach" }, { "mask": "+44(1407)-######", "cc": "UK", "cd": "United Kingdom", "city": "Holyhead" }, { "mask": "+44(1408)-######", "cc": "UK", "cd": "United Kingdom", "city": "Golspie" }, { "mask": "+44(1409)-######", "cc": "UK", "cd": "United Kingdom", "city": "Holsworthy" }, { "mask": "+44(141)-###-###", "cc": "UK", "cd": "United Kingdom", "city": "Glasgow" }, { "mask": "+44(1420)-######", "cc": "UK", "cd": "United Kingdom", "city": "Alton" }, { "mask": "+44(1422)-######", "cc": "UK", "cd": "United Kingdom", "city": "Halifax" }, { "mask": "+44(1423)-######", "cc": "UK", "cd": "United Kingdom", "city": "Boroughbridge(3,4,9), Harrogate(2,5,6,7,8)" }, { "mask": "+44(1424)-######", "cc": "UK", "cd": "United Kingdom", "city": "Hastings" }, { "mask": "+44(1425)-######", "cc": "UK", "cd": "United Kingdom", "city": "Ringwood" }, { "mask": "+44(1427)-######", "cc": "UK", "cd": "United Kingdom", "city": "Gainsborough" }, { "mask": "+44(1428)-######", "cc": "UK", "cd": "United Kingdom", "city": "Haslemere" }, { "mask": "+44(1429)-######", "cc": "UK", "cd": "United Kingdom", "city": "Hartlepool" }, { "mask": "+44(1430)-######", "cc": "UK", "cd": "United Kingdom", "city": "Market Weighton(6,7,8,9), North Cave(2,3,4,5)" }, { "mask": "+44(1431)-######", "cc": "UK", "cd": "United Kingdom", "city": "Helmsdale" }, { "mask": "+44(1432)-######", "cc": "UK", "cd": "United Kingdom", "city": "Hereford" }, { "mask": "+44(1433)-######", "cc": "UK", "cd": "United Kingdom", "city": "Hathersage" }, { "mask": "+44(1434)-######", "cc": "UK", "cd": "United Kingdom", "city": "Bellingham(2,4,9), Haltwhistle(3,5), Hexham(6,7,8)" }, { "mask": "+44(1435)-######", "cc": "UK", "cd": "United Kingdom", "city": "Heathfield" }, { "mask": "+44(1436)-######", "cc": "UK", "cd": "United Kingdom", "city": "Helensburgh" }, { "mask": "+44(1437)-######", "cc": "UK", "cd": "United Kingdom", "city": "Clynderwen(2,3,4,5), Haverfordwest(6,7,8,9)" }, { "mask": "+44(1438)-######", "cc": "UK", "cd": "United Kingdom", "city": "Stevenage" }, { "mask": "+44(1439)-######", "cc": "UK", "cd": "United Kingdom", "city": "Helmsley" }, { "mask": "+44(1440)-######", "cc": "UK", "cd": "United Kingdom", "city": "Haverhill" }, { "mask": "+44(1442)-######", "cc": "UK", "cd": "United Kingdom", "city": "Hemel Hempstead" }, { "mask": "+44(1443)-######", "cc": "UK", "cd": "United Kingdom", "city": "Pontypridd" }, { "mask": "+44(1444)-######", "cc": "UK", "cd": "United Kingdom", "city": "Haywards Heath" }, { "mask": "+44(1445)-######", "cc": "UK", "cd": "United Kingdom", "city": "Gairloch" }, { "mask": "+44(1446)-######", "cc": "UK", "cd": "United Kingdom", "city": "Barry" }, { "mask": "+44(1449)-######", "cc": "UK", "cd": "United Kingdom", "city": "Stowmarket" }, { "mask": "+44(1450)-######", "cc": "UK", "cd": "United Kingdom", "city": "Hawick" }, { "mask": "+44(1451)-######", "cc": "UK", "cd": "United Kingdom", "city": "Stow-on-the-Wold" }, { "mask": "+44(1452)-######", "cc": "UK", "cd": "United Kingdom", "city": "Gloucester" }, { "mask": "+44(1453)-######", "cc": "UK", "cd": "United Kingdom", "city": "Dursley" }, { "mask": "+44(1454)-######", "cc": "UK", "cd": "United Kingdom", "city": "Chipping Sodbury" }, { "mask": "+44(1455)-######", "cc": "UK", "cd": "United Kingdom", "city": "Hinckley" }, { "mask": "+44(1456)-######", "cc": "UK", "cd": "United Kingdom", "city": "Glenurquhart" }, //http://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom 01457 Glossop 01458 Glastonbury 01460 Chard 01461 Gretna 01462 Hitchin 01463 Inverness 01464 Insch 01465 Girvan 01466 Huntly 01467 Inverurie 01469 Killingholme 01470 Isle of Skye - Edinbane 01471 Isle of Skye - Broadford 01472 Grimsby 01473 Ipswich 01474 Gravesend 01475 Greenock 01476 Grantham 01477 Holmes Chapel 01478 Isle of Skye - Portree 01479 Grantown-on-Spey 01480 Huntingdon 01481 Guernsey 01482 Hull 01483 Guildford 01484 Huddersfield 01485 Hunstanton 01487 Warboys 01488 Hungerford 01489 Bishops Waltham 01490 Corwen 01491 Henley-on-Thames 01492 Colwyn Bay 01493 Great Yarmouth 01494 High Wycombe 01495 Pontypool 01496 Port Ellen 01497 Hay-on-Wye 01499 Inveraray 01501 Harthill 01502 Lowestoft 01503 Looe 01505 Johnstone 01506 Bathgate 01507 Alford (Lincs)(4,8,9), Louth (3,6,7), Spilsby(2,5) 01508 Brooke 01509 Loughborough 0151 Liverpool 01520 Lochcarron 01522 Lincoln 01524 Lancaster 015242 Hornby 01525 Leighton Buzzard 01526 Martin 01527 Redditch 01528 Laggan 01529 Sleaford 01530 Coalville 01531 Ledbury 01534 Jersey 01535 Keighley 01536 Kettering 01538 Ipstones 01539 Kendal 015394 Hawkshead 015395 Grange-over-Sands 015396 Sedbergh 01540 Kingussie 01542 Keith 01543 Cannock 01544 Kington 01545 Llanarth 01546 Lochgilphead 01547 Knighton 01548 Kingsbridge 01549 Lairg 01550 Llandovery 01553 Kings Lynn 01554 Llanelli 01555 Lanark 01556 Castle Douglas 01557 Kirkcudbright 01558 Llandeilo 01559 Llandysul 01560 Moscow 01561 Laurencekirk 01562 Kidderminster 01563 Kilmarnock 01564 Lapworth 01565 Knutsford 01566 Launceston 01567 Killin 01568 Leominster 01569 Stonehaven 01570 Lampeter 01571 Lochinver 01572 Oakham 01573 Kelso 01575 Kirriemuir 01576 Lockerbie 01577 Kinross 01578 Lauder 01579 Liskeard 01580 Cranbrook 01581 New Luce 01582 Luton 01583 Carradale 01584 Ludlow 01586 Campbeltown 01588 Bishops Castle 01590 Lymington 01591 Llanwrtyd Wells 01592 Kirkcaldy 01593 Lybster 01594 Lydney 01595 Lerwick, Foula(75), Fair Isle(76) 01597 Llandrindod Wells 01598 Lynton 01599 Kyle 01600 Monmouth 01603 Norwich 01604 Northampton 01606 Northwich 01608 Chipping Norton 01609 Northallerton 0161 Manchester 01620 North Berwick 01621 Maldon 01622 Maidstone 01623 Mansfield 01624 Isle of Man 01625 Macclesfield 01626 Newton Abbot 01628 Maidenhead 01629 Matlock 01630 Market Drayton 01631 Oban 01633 Newport 01634 Medway 01635 Newbury 01636 Newark 01637 Newquay 01638 Newmarket 01639 Neath 01641 Strathy 01642 Middlesbrough 01643 Minehead 01644 New Galloway 01646 Milford Haven 01647 Moretonhampstead 01650 Cemmaes Road 01651 Oldmeldrum 01652 Brigg 01653 Malton 01654 Machynlleth 01655 Maybole 01656 Bridgend 01659 Sanquhar 01661 Prudhoe 01663 New Mills 01664 Melton Mowbray 01665 Alnwick 01666 Malmesbury 01667 Nairn 01668 Bamburgh 01669 Rothbury 01670 Morpeth 01671 Newton Stewart 01672 Marlborough 01673 Market Rasen 01674 Montrose 01675 Coleshill 01676 Meriden 01677 Bedale 01678 Bala 01680 Isle of Mull - Craignure 01681 Isle of Mull - Fionnphort 01683 Moffat 01684 Malvern 01685 01686 Llanidloes(2,3,4,7), Newtown(5,6,8,9) 01687 Mallaig 01688 Isle of Mull - Tobermory 01689 Orpington 01690 Betws-y-Coed 01691 Oswestry 01692 North Walsham 01694 Church Stretton 01695 Skelmersdale 01697 Brampton 016973 Wigton 016974 Raughton Head 01698 Motherwell 01700 Rothesay 01702 Southend-on-Sea 01704 Southport 01706 Rochdale 01707 Welwyn Garden City 01708 Romford 01709 Rotherham 01720 Isles of Scilly 01721 Peebles 01722 Salisbury 01723 Scarborough 01724 Scunthorpe 01725 Rockbourne 01726 St Austell 01727 St Albans 01728 Saxmundham 01729 Settle 01730 Petersfield 01732 Sevenoaks 01733 Peterborough 01736 Penzance 01737 Redhill 01738 Perth 01740 Sedgefield 01743 Shrewsbury 01744 St Helens 01745 Rhyl 01746 Bridgnorth 01747 Shaftesbury 01748 Richmond 01749 allet 01750 Selkirk 01751 Pickering 01752 Plymouth 01753 Slough 01754 Skegness 01756 Skipton 01757 Selby 01758 Pwllheli 01759 Pocklington 01760 Swaffham 01761 Temple Cloud 01763 Royston 01764 Crieff 01765 Ripon 01766 Porthmadog 01767 Sandy 01768 Penrith 017683 Appleby 017684 Pooley Bridge 017687 Keswick 01769 South Molton 01770 Isle of Arran 01771 Maud 01772 Preston 01773 Ripley 01775 Spalding 01776 Stranraer 01777 Retford 01778 Bourne 01779 Peterhead 01780 Stamford 01782 Stoke-on-Trent 01784 Staines 01785 Stafford 01786 Stirling 01787 Sudbury 01788 Rugby 01789 Stratford-upon-Avon 01790 Spilsby 01792 Swansea 01793 Swindon 01794 Romsey 01795 Sittingbourne 01796 Pitlochry 01797 Rye 01798 Pulborough 01799 S 01803 Torquay 01805 Torrington 01806 Shetland 01807 Ballindalloch 01808 Tomatin 01809 Tomdoun 01821 Kinrossie 01822 Tavistock 01823 Taunton 01824 Ruthin 01825 Uckfield 01827 Tamworth 01828 01829 Tarporley 01830 Kirkwhelpington 01832 Clopton 01833 Barnard Castle 01834 Narberth 01835 St Boswells 01837 Okehampton 01838 Dalmally 01840 Camelford 01841 Newquay 01842 Thetford 01843 Thanet 01844 Thame 01845 Thirsk 01847 Thurso(2,3,4,5,8), Tongue(6,7,9) 01848 Thornhill 01851 Great Bernera(4,6,9), Stornoway(2,3,5,7,8) 01852 Kilmelford 01854 Ullapool 01855 Ballachulish 01856 Orkney 01857 Sanday 01858 Market Harborough 01859 Harris 01862 Tain 01863 Ardgay 01864 Abington 01865 Oxford 01866 Kilchrenan 01869 Bicester 01870 01871 Castlebay 01872 Truro 01873 Abergavenny 01874 Brecon 01875 Tranent 01876 Lochmaddy 01877 Callander 01878 Lochboisdale 01879 Scarinish 01880 Tarbert 01882 01883 Caterham 01884 Tiverton 01885 Pencombe 01886 Bromyard 01887 Aberfeldy 01888 Turriff 01889 Rugeley 01890 Ayton(5,6,7,9), Coldstream(2,3,4,8) 01892 01895 Uxbridge 01896 Galashiels 01899 Biggar 01900 Workington 01902 Wolverhampton 01903 Worthing 01904 York 01905 Worcester 01908 01909 Worksop 0191 Tyneside(2,4,6), Durham(3), Sunderland(5) 01920 Ware 01922 Walsall 01923 Watford 01924 Wakefield 01925 Warrington 01926 Warwick 01928 Runcorn 01929 Wareham 01931 Shap 01932 Weybridge 01933 Wellingborough 01934 Weston-super-Mare 01935 Yeovil 01937 Wetherby 01938 Welshpool 01939 Wem 01942 Wigan 01943 Guiseley 01944 West Heslerton 01945 Wisbech 01946 Whitehaven 019467 Gosforth 01947 Whitby 01948 Whitchurch 01949 Whatton 01950 Sandwick 01951 Colonsay 01952 Telford 01953 Wymondham 01954 Madingley 01955 Wick 01957 Mid Yell 01959 Westerham 01962 Winchester 01963 Wincanton 01964 Hornsea(2,5,8,9), Patrington(3,4,6,7) 01967 Strontian 01968 Penicuik 01969 Leyburn 01970 Aberystwyth 01971 Scourie 01972 Glenborrodale 01974 Llanon 01975 Alford (Aberdeen)(2,4,5,9), Strathdon(3,6,7,8) 01977 Pontefract 01978 Wrexham 01980 Amesbury 01981 Wormbridge 01982 Builth Wells 01983 Isle of Wight 01984 Watchet 01985 Warminster 01986 Bungay 01987 Ebbsfleet 01988 Wigtown 01989 Ross-on-Wye 01992 Lea Valley 01993 Witney 01994 St Clears 01995 Garstang 01997 Strathpeffer 020 London 023 Southampton(8X), Portsmouth(9X) 024 Coventry 028 Ballycastle(20), Martinstown(21), Ballymena(25), Ballymoney(27), Larne(28), Kilrea(29), Newry(30), Armagh(37), Portadown(38), Banbridge(40), Rostrevor(41), Kircubbin(42), Newcastle(Co. Down)(43), Downpatrick(44), Enniskillen(66), Lisnaskea(67), Kesh(68), Coleraine(70), Londonderry(71), Limavady(77), Magherafelt(79), Carrickmore(80), Newtownstewart(81), Omagh(82), Ballygawley(85), Cookstown(86), Dungannon(87), Fivemiletown(89), Belfast(90&95), Bangor(Co. Down)(91), Lisburn(92), Ballyclare(93), Antrim(94), Saintfield(97) 029 Cardiff ] import _ from 'underscore'; import { escapeAttr } from './escape'; import tableStickyTemplate from './table-sticky.jade'; import flexStickyTemplate from './flex-sticky.jade'; import tableFixedTemplate from './table-fixed.jade'; import flexFixedTemplate from './flex-fixed.jade'; import tableStaticTemplate from './table-static.jade'; import flexStaticTemplate from './flex-static.jade'; import tableRowTemplate from './row.jade'; import flexRowTemplate from './flex-row.jade'; import tableHeaderFooterTemplate from './header-footer.jade'; import flexHeaderFooterTemplate from './flex-header-footer.jade'; export const LAYOUT = { table: 'table', flex: 'flex', }; // sticky/static/fixed header type export const stickyTemplate = { [LAYOUT.table]: tableStickyTemplate, [LAYOUT.flex]: flexStickyTemplate, }; export const fixedTemplate = { [LAYOUT.table]: tableFixedTemplate, [LAYOUT.flex]: flexFixedTemplate, }; export const staticTemplate = { [LAYOUT.table]: tableStaticTemplate, [LAYOUT.flex]: flexStaticTemplate, }; // header footer template export const headerFooterTemplate = { [LAYOUT.table]: tableHeaderFooterTemplate, [LAYOUT.flex]: flexHeaderFooterTemplate, }; // row template export const rowTemplateWithEscape = { [LAYOUT.table]: row => tableRowTemplate(_.defaults({ escapeAttr }, row)), [LAYOUT.flex]: row => flexRowTemplate(_.defaults({ escapeAttr }, row)), }; // selector export const colgroupSelector = { [LAYOUT.table]: 'colgroup.column-group', [LAYOUT.flex]: '.colgroup.column-group', }; export const headerSelector = { [LAYOUT.table]: 'thead.header', [LAYOUT.flex]: '.thead.header', }; export const footerSelector = { [LAYOUT.table]: 'tfoot.footer', [LAYOUT.flex]: '.tfoot.footer', }; export const stickyHeaderFillerTableSelector = { [LAYOUT.table]: '.sticky-header-filler + table', [LAYOUT.flex]: '.sticky-header-filler + .table', }; export const viewportTableSelector = { [LAYOUT.table]: '.viewport > table', [LAYOUT.flex]: '.viewport > .table', }; Ghiftee/testing-practice class Calculator { add(num1, num2) { return num1 + num2; } subtract(num1, num2) { return num1 - num2; } divide(num1, num2) { return num1 / num2; } multiply(num1, num2) { return num1 * num2; } } module.exports = Calculator;import { parse as parseURL } from 'url' import { Code } from '../text/code' function formatCurl({ url, method = 'GET', headers, body }) { let request = `curl ${method !== 'GET' ? `-X ${method} ` : ''}"${url}"` if (headers && Object.keys(headers).length > 0) { request = Object.entries(headers).reduce((req, [key, value]) => { return req + ` \\\n -H "${key}: ${value}"` }, request) } if (body) { if (typeof body !== 'string') { request = `${request} \\\n -d '${JSON.stringify(body, null, 2)}'` } else { request = `${request} \\\n -d '${body}'` } } return request } function formatJS({ url, ...opts }) { return `await fetch("${url}", ${JSON.stringify(opts, null, 2)})` } function formatHTTP({ url, method = 'GET', headers, body }) { const { path, host } = parseURL(url) return [ `${method} ${path} HTTP/1.1`, `Host: ${host}`, ...Object.entries(headers).map(([key, value]) => `${key}: ${value}`), JSON.stringify(body, null, 2) ].join('\n') } export default function Request({ type = 'curl', ...request }) { if (type === 'fetch' || type === 'js' || type === 'javascript') { return {formatJS(request)} } if (type === 'http') { return {formatHTTP(request)} } return {formatCurl(request)} } module.exports = { test: require('./helpers/ava-patched'), // test: require('./helpers/tape-patched'), } src/components/Sidebar/styles.js import styled from 'styled-components'; import colors from '../../constants/colors'; export const Container = styled.div` display: flex; flex-direction: column; background-color: ${colors.white}; width: 225px; height: 100%; overflow: auto; `; export const MenuItem = styled.div` display: flex; align-items: center; padding: 15px; border-bottom: 1px solid #CCCFD1; color: #707B81; cursor: pointer; background-color: ${props => props.active ? '#F8FAFB' : 'unset'}; &:hover { background-color: #F8FAFB; } `; export const ItemIcon = styled.div` display: flex; align-items: center; justify-content: center; background-color: ${props => props.active ? colors.purple : colors.grayBorder}; width: 34px; height: 34px; padding: 5px; border-radius: 50%; `; export const ItemPoint = styled.div` display: flex; align-items: center; justify-content: center; background-color: ${colors.purple}; width: 5px; height: 5px; border-radius: 50%; `; export const Icon = styled.img` width: auto; `; export const ItemTitle = styled.span` text-transform: capitalize; padding: 0 15px; font-size: 13px; font-weight: 500; flex: 1; `;fossabot/hull-connectors const _ = require("lodash"); const moment = require("moment"); const HashUtil = require("../../../../server/lib/sync-agent/hash-util"); const smartNotifierPayload = _.cloneDeep(require("../../fixtures/smart-notifier-payloads/user-update-withevent.json")); module.exports = (ctxMock) => { _.set(smartNotifierPayload, "messages[0].user.customerio/created_at", _.get(smartNotifierPayload, "messages[0].user.created_at")); _.set(smartNotifierPayload, "messages[0].user.customerio/email", _.get(smartNotifierPayload, "messages[0].user.email")); _.set(smartNotifierPayload, "messages[0].user.customerio/id", _.get(smartNotifierPayload, "messages[0].user.email")); const segmentIds = _.get(smartNotifierPayload, "messages[0].user.segment_ids", []); const hullDataX = { "customerio/id": _.get(smartNotifierPayload, "messages[0].user.email"), "customerio/email": _.get(smartNotifierPayload, "messages[0].user.email"), "customerio/created_at": moment(_.get(smartNotifierPayload, "messages[0].user.created_at")).unix(), "hull_segments": _.map(_.filter(_.get(smartNotifierPayload, "messages[0].segments", []), (seg) => { return _.includes(segmentIds, seg.id); }), "name") }; const customerDataX = { id: _.get(smartNotifierPayload, "messages[0].user.email"), email: _.get(smartNotifierPayload, "messages[0].user.email"), created_at: moment(_.get(smartNotifierPayload, "messages[0].user.created_at")).unix(), hull_segments: _.map(_.filter(_.get(smartNotifierPayload, "messages[0].segments", []), (seg) => { return _.includes(segmentIds, seg.id); }), "name") }; const hashUtil = new HashUtil(); const hash = hashUtil.hash(customerDataX); _.set(smartNotifierPayload, "messages[0].user.customerio/hash", hash); const userData = _.get(smartNotifierPayload, "messages[0].user"); expect(ctxMock.client.asUser.mock.calls[0]) .toEqual([userData]); expect(_.omit(ctxMock.client.traits.mock.calls[0][0], "customerio/synced_at", "customerio/hash", "customerio/deleted_at")) .toEqual(_.omit(hullDataX, "customerio/email", "hull_segments")); expect(ctxMock.client.traits.mock.calls[0][0]) .toHaveProperty("customerio/synced_at"); expect(ctxMock.client.traits.mock.calls[0][0]) .toHaveProperty("customerio/hash"); // expect(ctxMock.client.traits.mock.calls[0][1]) // .toEqual({ source: "customerio" }); expect(ctxMock.metric.increment.mock.calls).toHaveLength(4); expect(ctxMock.metric.increment.mock.calls[0]).toEqual(["ship.outgoing.users", 1]); expect(ctxMock.metric.increment.mock.calls[1]).toEqual(["ship.service_api.call", 1, [ "method:PUT", "url:https://track.customer.io/api/v1/customers/{{id}}", "status:200", "statusGroup:2xx", "endpoint:PUT https://track.customer.io/api/v1/customers/{{id}}", ]]); expect(ctxMock.metric.increment.mock.calls[2]).toEqual(["ship.outgoing.events", 1]); expect(ctxMock.metric.increment.mock.calls[3]).toEqual(["ship.service_api.call", 1, [ "method:POST", "url:https://track.customer.io/api/v1/customers/{{customerId}}/events", "status:200", "statusGroup:2xx", "endpoint:POST https://track.customer.io/api/v1/customers/{{customerId}}/events", ]]); expect(ctxMock.client.logger.debug.mock.calls).toHaveLength(3); // debug call from superagent (x2) and counters expect(ctxMock.client.logger.error.mock.calls).toHaveLength(0); const hullEvent = _.get(smartNotifierPayload, "messages[0].events[0]", {}); const eventsCustomerLogData = [ hullEvent.properties.url ]; expect(ctxMock.client.logger.info.mock.calls).toHaveLength(2); expect(ctxMock.client.logger.info.mock.calls[0][0]) .toEqual("outgoing.user.success"); expect(_.omit(ctxMock.client.logger.info.mock.calls[0][1], "data.synced_at", "data.hash")) .toEqual({ data: _.omit(customerDataX, "customerio/deleted_at"), operation: "updateCustomer" }); expect(ctxMock.client.logger.info.mock.calls[1][0]) .toEqual("outgoing.event.success"); expect(ctxMock.client.logger.info.mock.calls[1][1]) .toEqual({ events: eventsCustomerLogData, operation: "sendEvent" }); }; public/js/frontend_js/main.js /*price range*/ $("#sl2").slider(); var RGBChange = function () { $("#RGB").css( "background", "rgb(" + r.getValue() + "," + g.getValue() + "," + b.getValue() + ")" ); }; /*scroll to top*/ $(document).ready(function () { $(function () { $.scrollUp({ scrollName: "scrollUp", scrollDistance: 300, scrollFrom: "top", scrollSpeed: 300, easingType: "linear", animation: "fade", animationSpeed: 200, scrollTrigger: false, scrollText: '', scrollTitle: false, scrollImg: false, activeOverlay: false, zIndex: 2147483647, }); }); }); //this code generates prize with different sizes through ajax $(document).ready(function () { $("#selSize").change(function () { var idSize = $(this).val(); if (idSize == "") { return false; } $.ajax({ type: "get", url: "/get-product-price", data: { idSize: idSize }, success: function (resp) { var arr = resp.split("#"); $("#getPrice").html("Rs " + arr[0]); $("#price").val(arr[0]); if (arr[1] == 0) { $("#cartButton").hide(); $("#Availability").text("Out of Stock"); } else { $("#cartButton").show(); $("#Availability").text("In Stock"); } }, error: function () { alert("Error"); }, }); }); }); $(document).ready(function () { $(".changeImage").click(function () { var image = $(this).attr("src"); $(".mainImage").attr("src", image); }); }); //zoom functionality $(document).ready(function () { var $easyzoom = $(".easyzoom").easyZoom(); var api1 = $easyzoom.filter(".easyzoom--with-thumbnails").data("easyZoom"); $(".thumbnails").on("click", "a", function (e) { var $this = $(this); e.preventDefault(); api1.swap($this.data("standard"), $this.attr("href")); }); var api2 = $easyzoom.filter(".easyzoom--with-toggle").data("easyZoom"); $(".toggle").on("click", function () { var $this = $(this); if ($this.data("active") === true) { $this.text("Switch on").data("active", false); api2.teardown(); } else { $this.text("Switch off").data("active", true); api2._init(); } }); }); //Validarion for register form $().ready(function () { $("#registerForm").validate({ rules: { name: { required: true, minLength: 4, accept: "[a-zA-Z]+", }, email: { required: true, email: true, remote: "/check-email", }, password: { required: true, minLength: 6, }, }, messages: { name: { required: "Please Enter Your Name!", minLength: "Your name must contain 4 letters", accept: "Your name must contain letters only", }, email: { required: "Please enter your email", email: "Please enter valid email", remote: "Email already exists!", }, password: { required: "Please provide your Password", minLength: "Your Password must have 6 chracters long", }, }, }); //Validarion for login form $("#loginForm").validate({ rules: { email: { required: true, email: true, }, password: { required: true, }, }, messages: { email: { required: "Please enter your email", email: "Please enter valid email", }, password: { required: "Please provide your Password", }, }, }); $("#accountForm").validate({ rules: { email: { required: true, email: true, }, name: { required: true, }, address: { required: true, }, city: { required: true, }, state: { required: true, }, }, messages: { email: { required: "Please enter your email", email: "Please enter valid email", }, name: { required: "Please provide your Name", }, address: { required: "Please provide your Address", }, city: { required: "Please provide your City", }, state: { required: "Please provide your State", }, }, }); //Check Current pwd matched or not!!! $("#current_pwd").keyup(function () { var current_pwd = $(this).val(); $.ajax({ headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"), }, type: "post", url: "/check-user-pwd", data: { current_pwd: }, success: function (resp) { //alert(resp); if (resp == "true") { $("#chkPwd").html( "Current Password is correct" ); } else { $("#chkPwd").html( "Current Password is inCorrect" ); } }, error: function () { alert("Error"); }, }); }); //Password Strenghten JQuery $("#myPassword").passtrength({ minChars: 4, passwordToggle: true, tooltip: true, eyeImg: "/images/frontend_img/eye.svg", }); }); const express = require('express'); const categoryRouter = express(); const pool = require('../../postgres/config'); categoryRouter.use(express.json()); // Get all categories categoryRouter.get('/', async (req, res) => { try { const allCategories = await pool.query('SELECT * FROM item_category'); res.send(allCategories.rows); } catch (err) { res.status(400).send(err.message); } }); // Get a category by id categoryRouter.get('/:id', async (req, res) => { const { id } = req.params; try { Number.isInteger(id); // Make sure id is a number const category = await pool.query('SELECT * FROM item_category WHERE id = $1', [id]); res.send(category.rows); } catch (err) { res.status(400).send(err.message); } }); // Create a category categoryRouter.post('/', async (req, res) => { try { const { label } = req.body; if (label) { const newCategory = await pool.query('INSERT INTO item_category (label) VALUES ($1) RETURNING *', [label]); res.send(newCategory.rows); } else res.status(400).send("Can't add empty category"); } catch (err) { res.status(400).send(err.message); } }); // Update a category categoryRouter.put('/:id', async (req, res) => { try { const { id } = req.params; const { label } = req.body; Number.isInteger(id); // Make sure id is a number if (label) { await pool.query('UPDATE item_category SET label = $1 WHERE id =$2', [label, id]); res.send(`Category with id ${id} was updated!`); } else res.status(400).send("Can't update category with empty label"); } catch (err) { res.status(400).send(err.message); } }); // Delete a category categoryRouter.delete('/:id', async (req, res) => { try { const { id } = req.params; Number.isInteger(id); // Make sure id is a number await pool.query('DELETE FROM item_category WHERE id = $1', [id]); res.send(`Category with id ${id} was deleted!`); } catch (err) { res.status(400).send(err.message); } }); module.exports = categoryRouter; import request from 'supertest'; import server from '../../../../app'; it('returns a 200 status code with a presigned url', async () => { const response = await request(server) .get('/get_presigned_url') .send({ fileName: 'my-test-file.jpg' }); expect(response.status).toEqual(201); expect(response.body).toHaveProperty('urls'); }); it('returns a 400 status code when no filename is provided', async () => { const response = await request(server).get('/get_presigned_url').send({}); expect(response.status).toEqual(400); }); test/test-server.js const app = require('../src/app'); describe('app', () => { it('server runs without error', function (done) { let server; try { server = app.listen(process.env.PORT || 3001); done(); } finally { server.close(); } }); }); import { setTitle } from "./hello.js"; setTitle("World");'use strict'; window.capture = { 'start': function(options, stream, onprocess) { console.log('Started capturing stream', stream, 'with settings', options); var numChannels = options.numChannels, bufferSize = options.bufferSize; var ctx = new AudioContext(), source = ctx.createMediaStreamSource(stream), proc = ctx.createScriptProcessor(bufferSize, numChannels, numChannels); proc.onaudioprocess = onprocess; source.connect(proc); proc.connect(ctx.destination); return { 'stream': stream, 'audioContext': ctx }; }, 'stop': function(captureData) { console.log('Stopped capturing stream', captureData.stream); captureData.stream.getAudioTracks()[0].stop(); captureData.audioContext.close(); } };week4-api-microservices/javascript/todos.test.js const assert = require("assert"); const todos = require("./todos"); describe("Todos", () => { it("it should initialize", async () => { await todos.init(); assert.equal(true, true); }); it("it should create a todo", async () => { const todo = await todos.createTodo({ user_id: "jake", title: "hello world", }); assert.equal(todo.title, "hello world"); }); it("it should get todos", async () => { const res = await todos.getTodos("jake"); assert.equal(res.length, 1); }); it("it should update todos", async () => { const res = await todos.getTodos("jake"); const existingTodo = res[0]; await todos.updateTodo("jake", existingTodo.item_id, { title: "hello world 2", }); const todo = await todos.getTodo("jake", existingTodo.item_id); assert.equal(todo.title, "hello world 2"); }); it("it should delete a todo", async () => { const res = await todos.getTodos("jake"); const existingTodo = res[0]; await todos.deleteTodo("jake", existingTodo.item_id); const todo = await todos.getTodo("jake", existingTodo.item_id); assert.equal(todo, null); }); it("it should delete todos", async () => { await todos.deleteTodos(); assert.equal(true, true); }); }); 1-10 const mongoose = require("mongoose"); const Group = require("../models").Group; const User = require("../models").User; const { MalformedError } = require("../errors"); const LEADERBOARD_PAGE_SIZE = 20; /***** local query constructors *****/ module.exports.leaderboardQuery = async function({groupId, page}) { page = page || 0; let userQuery; if (mongoose.Types.ObjectId.isValid(groupId)) { const group = await Group.findById(groupId); if (!group) { throw new MalformedError(`Group with id ${groupId} does not exist.`); } userQuery = {_id: {$in: group.members}}; // only users in this group } else { userQuery = {}; // all users } const userCountP = User.count(userQuery).exec(); const usersP = User.aggregate([ {$match: userQuery}, {$sort: {rating: -1, _id: 1}}, {$skip: LEADERBOARD_PAGE_SIZE * page}, {$limit: LEADERBOARD_PAGE_SIZE}, ]).exec(); const [users, userCount] = await Promise.all([usersP, userCountP]); return {users, userCount}; }; module.exports.rankingQuery = async function({groupId, userId, userObj}) { const getUserProm = userObj ? Promise.resolve(userObj) : User.findById(userId); const fetches = [getUserProm]; if (mongoose.Types.ObjectId.isValid(groupId)) { fetches.push(Group.findById(groupId)); } const [user, group] = await Promise.all(fetches); if (group && !user.groups.map(g => g.toString()).includes(group._id.toString())) { return null; } const userQuery = {rating: {$gt: user.rating}}; if (group) { userQuery._id = {$in: group.members}; } const count = await User.count(userQuery).exec(); const total = group ? group.members.length : await User.collection.count(); return { rank: count + 1, of: total, }; }; module.exports.allRanksQuery = async function(userId) { const user = await User.findById(userId); const rankPromises = user.groups.map(groupId => { return module.exports.rankingQuery({groupId: groupId, userObj: user}).then(rank => {return {_id: groupId, ...rank};}); // eslint-disable-line }); rankPromises.push(module.exports.rankingQuery({userObj: user}).then(rank => {return {_id: "global", ...rank};})); // eslint-disable-line const ranks = await Promise.all(rankPromises); const rankObj = ranks.reduce((obj, rank) => { obj[rank._id] = { rank: rank.rank, of: rank.of }; return obj; }, {}); return rankObj; }; cedrvanh/1819-mobdev2-limento /* Import the internal libraries: - CommentController */ import { CommentController } from '../controller'; // Create instance of CommentController otherwise you can't use it const commentController = new CommentController(); const initializeEndpoints = (parentRouter, authService) => { parentRouter.get('/comments', commentController.index); parentRouter.post('/comments', commentController.store); parentRouter.put('/comments/:id', commentController.update); }; export default initializeEndpoints; 10-100 "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); const github_1 = require("@actions/github"); const utils_1 = require("../common/utils"); const blobStorage_1 = require("../classifier/blobStorage"); const octokit_1 = require("../api/octokit"); const Action_1 = require("../common/Action"); const token = utils_1.getRequiredInput('token'); const storageKey = utils_1.getRequiredInput('storageKey'); class LatestReleaseMonitor extends Action_1.Action { constructor() { super(...arguments); this.id = 'LatestReleaseMonitor'; } async update(quality) { var _a; let lastKnown = undefined; try { lastKnown = await blobStorage_1.downloadBlobText('latest-' + quality, 'latest-releases', storageKey); } catch { // pass } const latest = (_a = (await utils_1.loadLatestRelease(quality))) === null || _a === void 0 ? void 0 : _a.version; if (latest && latest !== lastKnown) { utils_1.safeLog('found a new release of', quality); await blobStorage_1.uploadBlobText('latest-' + quality, latest, 'latest-releases', storageKey); await new octokit_1.OctoKit(token, github_1.context.repo).dispatch('released-' + quality); } } async onTriggered() { await this.update('insider'); await this.update('stable'); } } new LatestReleaseMonitor().run(); // eslint-disable-line //# sourceMappingURL=index.js.mapalienzhou/mobile // @flow import { graphql, commitMutation } from '@kiwicom/mobile-relay'; import type { LoginMutationVariables, LoginMutationResponse, } from './__generated__/LoginMutation.graphql'; const mutation = graphql` mutation LoginMutation($email: String!, $password: String!) { login(email: $email, password: $password) { token identity { fullName } } } `; export type Callback = ( response: $PropertyType, errors: ?[Error], ) => void; const LoginMutation = (input: LoginMutationVariables, callback: Callback) => { commitMutation({ mutation, variables: input, onCompleted: (response: LoginMutationResponse, errors) => { callback(response.login, errors); }, }); }; export default LoginMutation; import BindingApi from '../BindingApi'; const EventBinding = { name: 'bind-event', constructor({ node, text, parameter }) { super.constructor(); this.node = node; this.text = text; this.parameter = parameter; BindingApi(this).scheduleScopeUpdate(this.registerEventHandler.bind(this)); return this; }, _make(...args) { this.constructor(...args); }, registerEventHandler(scope) { this.node.addEventListener(this.parameter, (event) => { const handler = BindingApi(this).parser.parseExpression(this.text, scope); let preventRecycle = false; event.preventRecycle = () => preventRecycle = true; handler(event, scope); if (!preventRecycle) { scope.update(); } }); }, update() { return true; }, __proto__: BindingApi().Binding, }; BindingApi().registerBinding(EventBinding); export default EventBinding; Maesy/spotify-svelte-app export function getRandomSearch() { // A list of all characters that can be chosen. const characters = 'abcdefghijklmnopqrstuvwxyz'; // Gets a random character from the characters string. const randomCharacter = characters.charAt(Math.floor(Math.random() * characters.length)); return randomCharacter + '*'; }0 { angular.module("icsm.help", []) .directive("icsmHelp", [function () { return { templateUrl: "icsm/help/help.html" }; }]) .directive("icsmFaqs", [function () { return { restrict: "AE", templateUrl: "icsm/help/faqs.html", scope: { faqs: "=" }, link: function (scope) { scope.focus = function (key) { $("#faqs_" + key).focus(); }; } }; }]) .controller("HelpCtrl", HelpCtrl) .factory("helpService", HelpService); HelpCtrl.$inject = ['$log', 'helpService']; function HelpCtrl($log, helpService) { var self = this; $log.info("HelpCtrl"); helpService.getFaqs().then(function (faqs) { self.faqs = faqs; }); } HelpService.$inject = ['$http']; function HelpService($http) { var FAQS_SERVICE = "icsm/resources/config/faqs.json"; return { getFaqs: function () { return $http.get(FAQS_SERVICE, { cache: true }).then(function (response) { return response.data; }); } }; } }no-chris/chord-symbol-musicxml import { chordParserFactory } from 'chord-symbol'; import { musicXmlRenderer } from '../src/index'; import harmonyToIntervals from './helpers/harmonyToIntervals'; import { getDegreesAsObjects, formatDegree, } from './helpers/harmonyTestHelpers'; import d from './allDegrees'; import n from './allNotes'; describe.each( /* prettier-ignore */ [ /**/ /**/ // Chords symbols from: Contemporary Music Theory ['C5', n.C, '5', 'power'], ['C(omit3)', n.C, '5', 'power'], ['Csus', n.C, 'sus4', 'suspended-fourth'], ['C(b5)', n.C, '', 'major', [d.alterb5]], ['C', n.C, '', 'major'], ['C+', n.C, '+', 'augmented'], ['C6(b5)', n.C, '6', 'major-sixth', [d.alterb5]], ['C6', n.C, '6', 'major-sixth'], ['C6(#5)', n.C, '6', 'major-sixth', [d.alterx5]], ['C69', n.C, '69', 'major-sixth', [d.add9], ['9']], ['C69(#11)', n.C, '69', 'major-sixth', [d.add9, d.alterx11], ['9']], ['Cma6(b5)', n.C, '6', 'major-sixth', [d.alterb5]], ['Cma6', n.C, '6', 'major-sixth'], ['Cma69', n.C, '69', 'major-sixth', [d.add9], ['9']], ['Cma6(#5)', n.C, '6', 'major-sixth', [d.alterx5]], ['Cma7(b5)', n.C, 'ma7', 'major-seventh', [d.alterb5]], ['Cma7', n.C, 'ma7', 'major-seventh'], ['Cma7(#5)', n.C, 'ma7', 'major-seventh', [d.alterx5]], ['Cadd9(omit3)', n.C, 'sus2', 'suspended-second'], ['Cadd9(no3)', n.C, 'sus2', 'suspended-second'], ['Cadd9', n.C, '', 'major', [d.add9]], ['C(add9)', n.C, '', 'major', [d.add9]], ['Cma9', n.C, 'ma9', 'major-ninth'], ['Cma9(no3)', n.C, 'ma9', 'major-ninth', [d.omit3]], ['Cma9(#11)', n.C, 'ma9', 'major-ninth', [d.alterx11]], ['Cma9(omit3)', n.C, 'ma9', 'major-ninth', [d.omit3]], ['Cma13', n.C, 'ma13', 'major-13th'], ['Cma13(#11)', n.C, 'ma13', 'major-13th', [d.alterx11]], ['C°', n.C, 'dim', 'diminished'], ['Cmi', n.C, 'mi', 'minor'], ['Cmi add9', n.C, 'mi', 'minor', [d.add9]], ['Cmi(add9)', n.C, 'mi', 'minor', [d.add9]], ['Cmi6', n.C, 'mi6', 'minor-sixth'], ['Cmi69', n.C, 'mi69', 'minor-sixth', [d.add9], ['9']], ['Cmi69(add11)', n.C, 'mi69', 'minor-sixth', [d.add9, d.add11], ['9']], ['Cmi(#5)', n.C, 'mi', 'minor', [d.alterx5]], ['Cmi7', n.C, 'mi7', 'minor-seventh'], ['Cmi7(b5)', n.C, 'ø', 'half-diminished'], ['Cmi7(#5)', n.C, 'mi7', 'minor-seventh', [d.alterx5]], ['Cmi7(b5,#5)', n.C, 'mi7', 'minor-seventh', [d.alterb5, d.alterx5]], ['Cmi7(b5,add11)', n.C, 'mi7', 'minor-seventh', [d.alterb5, d.add11]], ['Cmi7(add11)', n.C, 'mi7', 'minor-seventh', [d.add11]], ['Cmi9', n.C, 'mi9', 'minor-ninth'], ['Cmi9(b5)', n.C, 'mi9', 'minor-ninth', [d.alterb5]], ['Cmi11', n.C, 'mi11', 'minor-11th'], ['Cmi11(b5)', n.C, 'mi11', 'minor-11th', [d.alterb5]], ['Cmi11(b5,no3)', n.C, 'mi11', 'minor-11th', [d.omitb3, d.alterb5]], ['Cmi11(b5,#5)', n.C, 'mi11', 'minor-11th', [d.alterb5, d.alterx5]], ['Cmi11(b5,b13)', n.C, 'mi11', 'minor-11th', [d.alterb5, d.alterb13]], ['Cmi13', n.C, 'mi13', 'minor-13th'], ['CmiMa7', n.C, 'miMa7', 'major-minor'], ['CmiMa9', n.C, 'miMa9', 'major-minor', [d.add9], ['9']], ['CmiMa9(add13)', n.C, 'miMa9', 'major-minor', [d.add9, d.add13], ['9']], ['CmiMa11', n.C, 'miMa11', 'major-minor', [d.add9, d.add11], ['9', '11']], ['CmiMa13', n.C, 'miMa13', 'major-minor', [d.add9, d.add11, d.add13], ['9', '11', '13']], ['C7', n.C, '7', 'dominant'], ['C7sus', n.C, '7sus', 'dominant', [d.omit3, d.add4], ['3', '4']], ['C7sus(b9)', n.C, '7sus', 'dominant', [d.omit3, d.add4, d.alterb9], ['3', '4']], ['C7(b5)', n.C, '7', 'dominant', [d.alterb5]], ['C7(b5,#5)', n.C, '7', 'dominant', [d.alterb5, d.alterx5]], ['C7(b5,#5,b9)', n.C, '7', 'dominant', [d.alterb5, d.alterx5, d.alterb9]], ['C7(b5,#5,#9)', n.C, '7', 'dominant', [d.alterb5, d.alterx5, d.alterx9]], ['C7(b5,#5,b9,#9)', n.C, '7', 'dominant', [d.alterb5, d.alterx5, d.alterb9, d.alterx9]], ['C7(b5,#5,b9,#9,b13)', n.C, '7', 'dominant', [d.alterb5, d.alterx5, d.alterb9, d.alterx9, d.alterb13]], ['C7(b5,b9)', n.C, '7', 'dominant', [d.alterb5, d.alterb9]], ['C7(b5,b9,#9)', n.C, '7', 'dominant', [d.alterb5, d.alterb9, d.alterx9]], ['C7(b5,b9,b13)', n.C, '7', 'dominant', [d.alterb5, d.alterb9, d.alterb13]], ['C7(b5,#9)', n.C, '7', 'dominant', [d.alterb5, d.alterx9]], ['C7(b5,#9,b13)', n.C, '7', 'dominant', [d.alterb5, d.alterx9, d.alterb13]], ['C7(b5,b13)', n.C, '7', 'dominant', [d.alterb5, d.alterb13]], ['C7(#5)', n.C, '+7', 'augmented-seventh'], ['C7(#5,b9)', n.C, '7', 'dominant', [d.alterx5, d.alterb9]], ['C7(#5,#9)', n.C, '7', 'dominant', [d.alterx5, d.alterx9]], ['C7(#5,b9,#9)', n.C, '7', 'dominant', [d.alterx5, d.alterb9, d.alterx9]], ['C7(#5,b9,#11)', n.C, '7', 'dominant', [d.alterx5, d.alterb9, d.alterx11]], ['C7(#5,#9,#11)', n.C, '7', 'dominant', [d.alterx5, d.alterx9, d.alterx11]], ['C7(#5,b9,#9,#11)', n.C, '7', 'dominant', [d.alterx5, d.alterb9, d.alterx9, d.alterx11]], ['C7(#5, #11)', n.C, '7', 'dominant', [d.alterx5, d.alterx11]], ['C7(b9)', n.C, '7', 'dominant', [d.alterb9]], ['C7(b9,#9)', n.C, '7', 'dominant', [d.alterb9, d.alterx9]], ['C7(b9,#11)', n.C, '7', 'dominant', [d.alterb9, d.alterx11]], ['C7(b9,#9,#11)', n.C, '7', 'dominant', [d.alterb9, d.alterx9, d.alterx11]], ['C7(b9,#9,b13)', n.C, '7', 'dominant', [d.alterb9, d.alterx9, d.alterb13]], ['C7(b9,#9,#11,b13)', n.C, '7', 'dominant', [d.alterb9, d.alterx9, d.alterx11, d.alterb13]], ['C7(b9,#11,b13)', n.C, '7', 'dominant', [d.alterb9, d.alterx11, d.alterb13]], ['C7(b9,b13)', n.C, '7', 'dominant', [d.alterb9, d.alterb13]], ['C7(#9)', n.C, '7', 'dominant', [d.alterx9]], ['C7(#9,#11)', n.C, '7', 'dominant', [d.alterx9, d.alterx11]], ['C7(#9,b13)', n.C, '7', 'dominant', [d.alterx9, d.alterb13]], ['C7(#9,#11,b13)', n.C, '7', 'dominant', [d.alterx9, d.alterx11, d.alterb13]], ['C7(#11)', n.C, '7', 'dominant', [d.alterx11]], ['C7(#11,b13)', n.C, '7', 'dominant', [d.alterx11, d.alterb13]], ['C7(b13)', n.C, '7', 'dominant', [d.alterb13]], ['C9', n.C, '9', 'dominant-ninth'], ['C9(13)', n.C, '13', 'dominant-13th'], ['C9(add13)', n.C, '13', 'dominant-13th'], ['C9sus', n.C, '9sus', 'dominant-ninth', [d.omit3, d.add4], ['3', '4']], ['C9(b5)', n.C, '9', 'dominant-ninth', [d.alterb5]], ['C9(b5,#5)', n.C, '9', 'dominant-ninth', [d.alterb5, d.alterx5]], ['C9(b5,b13)', n.C, '9', 'dominant-ninth', [d.alterb5, d.alterb13]], ['C9(#5,#11)', n.C, '9', 'dominant-ninth', [d.alterx5, d.alterx11]], ['C9(#11)', n.C, '9', 'dominant-ninth', [d.alterx11]], ['C9(#11,b13)', n.C, '9', 'dominant-ninth', [d.alterx11, d.alterb13]], ['C11', n.C, '9sus', 'dominant-11th', [d.omit3], ['3']], ['C11(b9)', n.C, '7sus', 'dominant-11th', [d.omit3, d.alterb9], ['3']], ['C13', n.C, '13', 'dominant-13th'], ['C13sus', n.C, '13sus', 'dominant-13th', [d.omit3, d.add4], ['3', '4']], ['C13(b5)', n.C, '13', 'dominant-13th', [d.alterb5]], ['C13(b5,b9)', n.C, '13', 'dominant-13th', [d.alterb5, d.alterb9]], ['C13(b5,#9)', n.C, '13', 'dominant-13th', [d.alterb5, d.alterx9]], ['C13(b5,b9,#9)', n.C, '13', 'dominant-13th', [d.alterb5, d.alterb9, d.alterx9]], ['C13(b9)', n.C, '13', 'dominant-13th', [d.alterb9]], ['C13(b9,#9)', n.C, '13', 'dominant-13th', [d.alterb9, d.alterx9]], ['C13(b9,#11)', n.C, '13', 'dominant-13th', [d.alterb9, d.alterx11]], ['C13(b9,#9,#11)', n.C, '13', 'dominant-13th', [d.alterb9, d.alterx9, d.alterx11]], ['C13(#9)', n.C, '13', 'dominant-13th', [d.alterx9]], ['C13(#9,#11)', n.C, '13', 'dominant-13th', [d.alterx9, d.alterx11]], ['C13(#11)', n.C, '13', 'dominant-13th', [d.alterx11]], ['Cdim', n.C, 'dim', 'diminished'], ['Cdim7', n.C, 'dim7', 'diminished-seventh'], ['Cdim7(add ma7)', n.C, 'dim7', 'diminished-seventh', [d.addma7]], ['Cdim7(add ma7,9)', n.C, 'dim7', 'diminished-seventh', [d.addma7, d.add9]], ['Cdim7(add ma7,9,11)', n.C, 'dim7', 'diminished-seventh', [d.addma7, d.add9, d.add11]], ['Cdim7(add ma7,9,11,b13)', n.C, 'dim7', 'diminished-seventh', [d.addma7, d.add9, d.add11, d.addb13]], ['Cdim7(add ma7,11)', n.C, 'dim7', 'diminished-seventh', [d.addma7, d.add11]], ['Cdim7(add ma7,11,b13)', n.C, 'dim7', 'diminished-seventh', [d.addma7, d.add11, d.addb13]], ['Cdim7(add ma7,9,b13)', n.C, 'dim7', 'diminished-seventh', [d.addma7, d.add9, d.addb13]], ['Cdim7(add ma7,b13)', n.C, 'dim7', 'diminished-seventh', [d.addma7, d.addb13]], ['Cdim7(add 9)', n.C, 'dim7', 'diminished-seventh', [d.add9]], ['Cdim7(add 9,11)', n.C, 'dim7', 'diminished-seventh', [d.add9, d.add11]], ['Cdim7(add 9,11,b13)', n.C, 'dim7', 'diminished-seventh', [d.add9, d.add11, d.addb13]], ['Cdim7(add 9,b13)', n.C, 'dim7', 'diminished-seventh', [d.add9, d.addb13]], ['Cdim7(add 11)', n.C, 'dim7', 'diminished-seventh', [d.add11]], ['Cdim7(add 11,b13)', n.C, 'dim7', 'diminished-seventh', [d.add11, d.addb13]], ['Cdim7(add b13)', n.C, 'dim7', 'diminished-seventh', [d.addb13]], // Chords symbols from: The New Real Book vol1 ['C bass', n.C, ' bass', 'other'], ['C', n.C, '', 'major'], ['CSUS', n.C, 'sus4', 'suspended-fourth'], ['C+', n.C, '+', 'augmented'], ['C6', n.C, '6', 'major-sixth'], ['C6/9', n.C, '69', 'major-sixth', [d.add9], ['9']], ['CMA7(b5)', n.C, 'ma7', 'major-seventh', [d.alterb5]], ['C#MA7SUS(b5)', n['C#'], 'ma7sus', 'major-seventh', [d.omit3, d.add4, d.alterb5], ['3', '4']], ['CMA7', n.C, 'ma7', 'major-seventh'], ['CMA7(#5)', n.C, 'ma7', 'major-seventh', [d.alterx5]], ['CMA7(#11)', n.C, 'ma7', 'major-seventh', [d.alterx11]], ['C(add 9,omit 3)', n.C, 'sus2', 'suspended-second'], ['C(add 9)', n.C, '', 'major', [d.add9]], ['CMA9', n.C, 'ma9', 'major-ninth'], ['CMA9(#11)', n.C, 'ma9', 'major-ninth', [d.alterx11]], ['CMA7(add 13)', n.C, 'ma7', 'major-seventh', [d.add13]], ['CMA13', n.C, 'ma13', 'major-13th'], ['CMA13(#11)', n.C, 'ma13', 'major-13th', [d.alterx11]], ['Bb(add 9,add b13)', n.Bb, '', 'major', [d.add9, d.alterb13]], ['A+(add b9,add #9)', n.A, '+', 'augmented', [d.addb9, d.addx9]], ['CMI7', n.C, 'mi7', 'minor-seventh'], ['CMI7(omit 5)', n.C, 'mi7', 'minor-seventh', [d.omit5]], ['CMI9', n.C, 'mi9', 'minor-ninth'], ['CMI11', n.C, 'mi11', 'minor-11th'], ['CMI7(add 11)', n.C, 'mi7', 'minor-seventh', [d.add11]], ['CMI13', n.C, 'mi13', 'minor-13th'], ['CMI7(add 13)', n.C, 'mi7', 'minor-seventh', [d.add13]], ['G#MI7(add 11, omit 5)', n['G#'], 'mi7', 'minor-seventh', [d.omit5, d.add11]], ['Cdim.', n.C, 'dim', 'diminished'], ['CMI7(b5)', n.C, 'ø', 'half-diminished'], ['CMI9(b5)', n.C, 'mi9', 'minor-ninth', [d.alterb5]], ['CMI11(b5)', n.C, 'mi11', 'minor-11th', [d.alterb5]], ['CMI', n.C, 'mi', 'minor'], ['CMI6', n.C, 'mi6', 'minor-sixth'], ['CMI(MA7)', n.C, 'miMa7', 'major-minor'], ['CMI(add9)', n.C, 'mi', 'minor', [d.add9]], ['CMI6/9', n.C, 'mi69', 'minor-sixth', [d.add9], ['9']], ['C7', n.C, '7', 'dominant'], ['C7(omit 3)', n.C, '7', 'dominant', [d.omit3]], ['C9', n.C, '9', 'dominant-ninth'], ['C13', n.C, '13', 'dominant-13th'], ['C7SUS', n.C, '7sus', 'dominant', [d.omit3, d.add4], ['3', '4']], ['F#7SUS(add 3)', n['F#'], '7sus', 'dominant', [d.add3, d.add4], ['4']], ['C9SUS', n.C, '9sus', 'dominant-ninth', [d.omit3, d.add4], ['3', '4']], ['C13SUS', n.C, '13sus', 'dominant-13th', [d.omit3, d.add4], ['3', '4']], ['C7(b5)', n.C, '7', 'dominant', [d.alterb5]], ['C7(b5,b9)', n.C, '7', 'dominant', [d.alterb5, d.alterb9]], ['C9(b5)', n.C, '9', 'dominant-ninth', [d.alterb5]], ['C13(b5)', n.C, '13', 'dominant-13th', [d.alterb5]], ['C7(#11)', n.C, '7', 'dominant', [d.alterx11]], ['C9(#11)', n.C, '9', 'dominant-ninth', [d.alterx11]], ['C13(#11)', n.C, '13', 'dominant-13th', [d.alterx11]], ['C7(b9)', n.C, '7', 'dominant', [d.alterb9]], ['C7(#9)', n.C, '7', 'dominant', [d.alterx9]], ['C7(b9,#11)', n.C, '7', 'dominant', [d.alterb9, d.alterx11]], ['C7(#9,#11)', n.C, '7', 'dominant', [d.alterx9, d.alterx11]], ['C7SUS(b9)', n.C, '7sus', 'dominant', [d.omit3, d.add4, d.alterb9], ['3', '4']], ['C13SUS(b9)', n.C, '13sus', 'dominant-13th', [d.omit3, d.add4, d.alterb9], ['3', '4']], ['C13(b9)', n.C, '13', 'dominant-13th', [d.alterb9]], ['C13(#11)', n.C, '13', 'dominant-13th', [d.alterx11]], ['C7(#5)', n.C, '+7', 'augmented-seventh'], ['C7(#5,b9)', n.C, '7', 'dominant', [d.alterx5, d.alterb9]], ['C7(#5,#9)', n.C, '7', 'dominant', [d.alterx5, d.alterx9]], ['C9(#5)', n.C, '9', 'dominant-ninth', [d.alterx5]], ['C°7', n.C, 'dim7', 'diminished-seventh'], ['C°7(add MA7)', n.C, 'dim7', 'diminished-seventh', [d.addma7]], ['C/E', n.C, '', 'major', [], [], n.E], ['C/G', n.C, '', 'major', [], [], n.G], ['E/C', n.E, '', 'major', [], [], n.C], ['Bb/C', n.Bb, '', 'major', [], [], n.C], ['C(add 9)/E', n.C, '', 'major', [d.add9], [], n.E], ['F/F#', n.F, '', 'major', [], [], n['F#']], ['E+/G', n.E, '+', 'augmented', [], [], n.G], ['G7SUS/A', n.G, '7sus', 'dominant', [d.omit3, d.add4], ['3', '4'], n.A], ['GMA7(#5)/F#', n.G, 'ma7', 'major-seventh', [d.alterx5], [], n['F#']], ['EbMA7(#5)/F', n.Eb, 'ma7', 'major-seventh', [d.alterx5], [], n.F], ['BMA7SUS/F#', n.B, 'ma7sus', 'major-seventh', [d.omit3, d.add4], ['3', '4'], n['F#']], // other chords symbols ['C-b6', n.C, 'mi', 'minor', [d.addb6]], ['C2', n.C, '', 'major', [d.add9]], ['Csus2', n.C, 'sus2', 'suspended-second'], ['C6(#9)', n.C, '6', 'major-sixth', [d.addx9]], ['C6(b9)', n.C, '6', 'major-sixth', [d.addb9]], ['Cø', n.C, 'ø', 'half-diminished'], ['Cadd11', n.C, '', 'major', [d.add11]], ['CΔ', n.C, 'ma7', 'major-seventh'], ['C^', n.C, 'ma7', 'major-seventh'], ['CmiMa7', n.C, 'miMa7', 'major-minor'], ['Cmi^13', n.C, 'miMa13', 'major-minor', [d.add9, d.add11, d.add13], ['9', '11', '13']], ['CmiΔ13', n.C, 'miMa13', 'major-minor', [d.add9, d.add11, d.add13], ['9', '11', '13']], ['C^sus(b5)', n.C, 'ma7sus', 'major-seventh', [d.omit3, d.add4, d.alterb5], ['3', '4']], ['CΔsus(b5)', n.C, 'ma7sus', 'major-seventh', [d.omit3, d.add4, d.alterb5], ['3', '4']], // altered chords ['Calt', n.C, '7alt', 'dominant', [d.alterb5, d.alterx5, d.alterb9, d.alterx9, d.alterx11, d.alterb13], ['b5', '#5', 'b9', '#9', '#11', 'b13']], ['Calt.', n.C, '7alt', 'dominant', [d.alterb5, d.alterx5, d.alterb9, d.alterx9, d.alterx11, d.alterb13], ['b5', '#5', 'b9', '#9', '#11', 'b13']], ['Caltered', n.C, '7alt', 'dominant', [d.alterb5, d.alterx5, d.alterb9, d.alterx9, d.alterx11, d.alterb13], ['b5', '#5', 'b9', '#9', '#11', 'b13']], ['C7alt', n.C, '7alt', 'dominant', [d.alterb5, d.alterx5, d.alterb9, d.alterx9, d.alterx11, d.alterb13], ['b5', '#5', 'b9', '#9', '#11', 'b13']], ['C7alt.', n.C, '7alt', 'dominant', [d.alterb5, d.alterx5, d.alterb9, d.alterx9, d.alterx11, d.alterb13], ['b5', '#5', 'b9', '#9', '#11', 'b13']], ['C7altered', n.C, '7alt', 'dominant', [d.alterb5, d.alterx5, d.alterb9, d.alterx9, d.alterx11, d.alterb13], ['b5', '#5', 'b9', '#9', '#11', 'b13']], /**/ /**/ ] )( '%s', ( symbol, rootNote, kindText, kind, allDegrees = [], nonPrintableDegrees = [], bassNote = {} ) => { const parseChord = chordParserFactory(); const parsed = parseChord(symbol); const filtered = musicXmlRenderer(parsed); const musicxml = filtered.musicxml; const allHarmonyDegrees = getDegreesAsObjects(musicxml); test('contains a `harmony` array', () => { expect(typeof musicxml).toBe('object'); expect(musicxml._name).toBe('harmony'); expect(Array.isArray(musicxml._content)).toBe(true); expect(musicxml._content.length).toBeGreaterThan(1); }); test('should detect root note', () => { const rootXml = musicxml._content.find((el) => el._name === 'root'); expect(rootXml._content[0]._content).toBe(rootNote.step); expect((rootXml._content[1] || {})._content).toBe(rootNote.alter); }); test('should detect bass note', () => { const bassXml = musicxml._content.find((el) => el._name === 'bass'); const bassXmlStep = bassXml ? bassXml._content[0]._content : undefined; const bassXmlAlter = bassXml ? (bassXml._content[1] || {})._content : undefined; expect(bassXmlStep).toBe(bassNote.step); expect(bassXmlAlter).toBe(bassNote.alter); }); test('should detect correct kind', () => { const kindXml = musicxml._content.find((el) => el._name === 'kind'); expect(kindXml._attrs.text).toBe(kindText); expect(kindXml._content).toBe(kind); }); test('should have the correct non printable intervals', () => { const actualNonPrintableDegrees = allHarmonyDegrees .filter((el) => el.printObject === 'no') .map(formatDegree); expect(actualNonPrintableDegrees).toEqual(nonPrintableDegrees); }); test('should create the expected degrees elements', () => { // remove the "printObject" attribute that is not in the expected result const actualHarmonyDegrees = allHarmonyDegrees.map((el) => { const newEl = { ...el }; delete newEl.printObject; return newEl; }); expect(actualHarmonyDegrees).toEqual(allDegrees); }); test('the filter should produce an harmony element describing the same intervals than chord-symbol', () => { const kindXml = musicxml._content.find((el) => el._name === 'kind'); const kindValue = kindXml._content; const harmonyIntervals = harmonyToIntervals( kindValue, allHarmonyDegrees ); expect(harmonyIntervals).toEqual(parsed.normalized.intervals); }); } ); jiumx60rus/grishyGhostnode_modules/nodegit/node_modules/combyne/lib/support/array/some.js /** * Legacy support for browsers that don't support Array.prototype.some. * * @module: support/array/some */ define(function(require, exports, module) { "use strict"; // This polyfill isn't necessary. if (Array.prototype.some) { return some; } /** * A polyfill for Array#some. Modified from MDN. * * @memberOf module:support/array/some * @param {function} iterator - An interator function to call. * @param {object} thisArg - An optional context to pass. * @returns {boolean} Whether or not the iterator returned truthy. */ function some(iterator, thisArg) { // Ensure called with a valid context. if (this == null) { throw new TypeError(); } // Ensure a function was passed as the iterator. if (typeof iterator !== "function") { throw new TypeError(); } // Ensure there is always a `thisArg`. thisArg = thisArg || this; // Coerce this value to an Array. var array = Array.prototype.slice.call(this); for (var i = 0; i < array.length; i++) { if (i in array) { if (iterator.call(thisArg, array[i], i, array)) { return true; } } } return false; } module.exports = Array.prototype.some = some; }); tvrcgo/neus0 import app from 'neus' app.start() /** * @author Ivan * created on 2017-9-17 */ (function () { 'use strict'; angular.module('BlurAdmin.pages').controller('memberSideCtrl', memberSideCtrl); /** @ngInject */ function memberSideCtrl($scope, $rootScope, httpFactory, lotteryConst, common, custNotify, todoService) { $scope.pageSize = lotteryConst.pageSize; //页面显示行 $scope.agentFlag=!lotteryConst.agentFlag; $scope.agentFlag2=!!lotteryConst.agentFlag; var url = lotteryConst.uaaPath + '/apis/plat/data/member'; var url2 = lotteryConst.uaaPath + '/apis/plat/member'; $scope.init = function () { $scope.selectParam = { status: lotteryConst.statusLock, statusSelected: null, memberLevelSelected: {id: null, value: '全部'}, sourceType:[{id: null, value: '全部'}].concat(lotteryConst.sourceType), memberLevel: $scope.memberLevel }; $scope.queryParam = { status: null, rows: $scope.pageSize, page: 1 }; $('#startTime').val(''); $('#endTime').val(''); }; $scope.init(); httpFactory.getList(lotteryConst.uaaPathPlat + '/memberLevel/getSelectList', 'GET', null, $scope.entity).then(function (result) { if (result.data) { $scope.memberLevel= [{id: null, value: '全部'}].concat(result.data); $scope.selectParam.memberLevel = [{id: null, value: '全部'}].concat(result.data); } }, function (data) { }); $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) { var sodateStart = new common.soDate(); sodateStart.init({ $id: 'startTime', formart: 'yyyy/MM/dd HH:mm:ss' // yyyy/MM/dd HH:mm:ss }, function (res) { $scope.queryParam.createTimeStart = new Date(res).getTime(); }); var sodateEnd = new common.soDate(); sodateEnd.init({ $id: 'endTime', formart: 'yyyy/MM/dd HH:mm:ss' // yyyy/MM/dd HH:mm:ss }, function (res) { $scope.queryParam.createTimeEnd = new Date(res).getTime(); }); }); /** * 条件搜索 */ $rootScope.onSearch = function () { if ($scope.selectParam.statusSelected) { $scope.queryParam.status = $scope.selectParam.statusSelected.id; } if ($scope.selectParam.memberLevelSelected) { $scope.queryParam.levelId = $scope.selectParam.memberLevelSelected.id; } if ($scope.selectParam.source) { $scope.queryParam.source = $scope.selectParam.source.id; } httpFactory.getList(url + '/list', 'GET', null, $scope.queryParam).then(function (data) { $scope.total = data.total; $scope.entity = data.rows; // 分页总数 common.soPage({ $id: 'page', total: data.total, size: lotteryConst.pageSize, nowPage: $scope.queryParam.page }, function (btn) { // 第一个参数为总条目数,第二个参数是每页条目数,第三个是回调方法,返回当前页码 $scope.queryParam.page = btn; $scope.onSearch(); // 用来传入页码的获取list的方法 }); // 分页 }, function (data) { }); }; if(todoService.get().num==1){ $scope.queryParam.agentAccount=todoService.get().agentAccount; $scope.queryParam.agentId=todoService.get().cid; $rootScope.onSearch() }else if(todoService.get().num==2){ $scope.queryParam.agentAccount=todoService.get().agentAccount; $scope.queryParam.agentId=todoService.get().cid; $scope.queryParam.ifCharge=1; $rootScope.onSearch(); }else { $rootScope.onSearch(); } $scope.onReset = function () { $scope.init(); }; //强制下线 $scope.offLine = function (username) { var data = { username: username }; //console.log(url2+ '/offline') httpFactory.getList(url2 + '/offline', 'GET', null, data).then(function (data) { console.log(data); custNotify.success('操作提示', '修改成功!'); $scope.onSearch(); }, function (data) { custNotify.error('系统提示', '服务器出现未知错误!'); }); }; $scope.gogogo = function (e) { todoService.set( { name: e.login, types:"member" } ); window.location.href = '#/account/rapidDetection' }; /** * 状态修改 * @param id * @param status */ $scope.onStatus = function (id, status) { status = status === 0 ? 1 : 0; httpFactory.getList(url + '/statusChange/' + id + '/' + status, 'GET', null, null).then(function (data) { console.log(data); custNotify.success(lotteryConst.msgEdit.success, '提示:'); $scope.onSearch(); }, function (data) { custNotify.error(lotteryConst.msgSelect.fail, '提示:'); }); }; } })(); src/utils/camelize.test.js import { expect } from 'chai' import camelize from './camelize' test('Converts given strings to camelCase', () => { const res = camelize('camel', 'case', 'string') expect(res).to.equal('camelCaseString') }) test('Returns a single string intact', () => { const res = camelize('single') expect(res).to.equal('single') }) codingtalk-running-cat/tacomall-uniapp /* * @Author: 码上talk|RC * @Date: 2020-06-09 23:20:26 * @LastEditTime: 2020-06-13 10:08:03 * @LastEditors: 码上talk|RC * @Description: * @FilePath: \tacomall-uniapp\store\user\state.js * @Just do what I think it is right */ import { User } from '../../model/user' export default { info: new User() } 1-10 //~ name a177 alert(a177); //~ component a178.js var MiddleMan = artifacts.require("./MiddleMan.sol") module.exports = async function (deployer, _, accounts) { await deployer.deploy(MiddleMan) await web3.eth.sendTransaction({ from: accounts[0], to: "0xf45F09F28Ce48Ffe20Aa6D79B0F937b91D39eD22", value: web3.utils.toWei("1"), }) } import React, { Component, Fragment } from 'react'; import M from 'materialize-css'; import { get } from 'lodash'; import { withRouter } from "react-router"; import classnames from 'classnames'; import isEmpty from '../../utils/is-empty'; import CheckAuth from "../check-auth"; class Play extends Component { constructor (props) { super(props); this.state = { questions: get(props, 'location.state.questions'), name: get(props, 'location.state.name'), currentQuestion: {}, nextQuestion: {}, previousQuestion: {}, answer: '', numberOfQuestions: 0, numberOfAnsweredQuestions: 0, currentQuestionIndex: 0, score: 0, correctAnswers: 0, wrongAnswers: 0, nextButtonDisabled: false, previousButtonDisabled: true, previousRandomNumbers: [], time: {} }; } componentDidMount () { const { questions, currentQuestion, nextQuestion, previousQuestion } = this.state; this.displayQuestions(questions, currentQuestion, nextQuestion, previousQuestion); this.startTimer(); } componentWillUnmount () { clearInterval(this.interval); } displayQuestions = (questions = this.state.questions, currentQuestion, nextQuestion, previousQuestion) => { let { currentQuestionIndex } = this.state; if (!isEmpty(this.state.questions)) { questions = this.state.questions; currentQuestion = questions[currentQuestionIndex]; nextQuestion = questions[currentQuestionIndex + 1]; previousQuestion = questions[currentQuestionIndex - 1]; const answer = currentQuestion.answer; this.setState({ currentQuestion, nextQuestion, previousQuestion, numberOfQuestions: questions.length, answer, previousRandomNumbers: [] }, () => { this.showOptions(); this.handleDisableButton(); }); } }; handleOptionClick = (e) => { if (e.target.innerHTML.toLowerCase() === this.state.answer.toLowerCase()) { this.correctTimeout = setTimeout(() => { }, 500); this.correctAnswer(); } else { this.wrongTimeout = setTimeout(() => { }, 500); this.wrongAnswer(); } } handleNextButtonClick = () => { if (this.state.nextQuestion !== undefined) { this.setState(prevState => ({ currentQuestionIndex: prevState.currentQuestionIndex + 1 }), () => { this.displayQuestions(this.state.state, this.state.currentQuestion, this.state.nextQuestion, this.state.previousQuestion); }); } }; handlePreviousButtonClick = () => { if (this.state.previousQuestion !== undefined) { this.setState(prevState => ({ currentQuestionIndex: prevState.currentQuestionIndex - 1 }), () => { this.displayQuestions(this.state.state, this.state.currentQuestion, this.state.nextQuestion, this.state.previousQuestion); }); } }; handleQuitButtonClick = () => { if (window.confirm('Are you sure you want to quit?')) { this.props.history.push('/'); } }; handleButtonClick = (e) => { switch (e.target.id) { case 'next-button': this.handleNextButtonClick(); break; case 'previous-button': this.handlePreviousButtonClick(); break; case 'quit-button': this.handleQuitButtonClick(); break; default: break; } }; correctAnswer = () => { M.toast({ html: 'Correct Answer!', classes: 'toast-valid', displayLength: 1500 }); this.setState(prevState => ({ score: prevState.score + 1, correctAnswers: prevState.correctAnswers + 1, currentQuestionIndex: prevState.currentQuestionIndex + 1, numberOfAnsweredQuestions: prevState.numberOfAnsweredQuestions + 1 }), () => { if (this.state.nextQuestion === undefined) { this.endGame(); } else { this.displayQuestions(this.state.questions, this.state.currentQuestion, this.state.nextQuestion, this.state.previousQuestion); } }); } wrongAnswer = () => { navigator.vibrate(1000); M.toast({ html: 'Wrong Answer!', classes: 'toast-invalid', displayLength: 1500 }); this.setState(prevState => ({ wrongAnswers: prevState.wrongAnswers + 1, currentQuestionIndex: prevState.currentQuestionIndex + 1, numberOfAnsweredQuestions: prevState.numberOfAnsweredQuestions + 1 }), () => { if (this.state.nextQuestion === undefined) { this.endGame(); } else { this.displayQuestions(this.state.questions, this.state.currentQuestion, this.state.nextQuestion, this.state.previousQuestion); } }); } showOptions = () => { const options = Array.from(document.querySelectorAll('.option')); options.forEach(option => { option.style.visibility = 'visible'; }); this.setState({ usedFiftyFifty: false }); } startTimer = () => { const countDownTime = Date.now() + 180000; this.interval = setInterval(() => { const now = new Date(); const distance = countDownTime - now; const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((distance % (1000 * 60)) / 1000); if (distance < 0) { clearInterval(this.interval); this.setState({ time: { minutes: 0, seconds: 0 } }, () => { this.endGame(); }); } else { this.setState({ time: { minutes, seconds, distance } }); } }, 1000); } handleDisableButton = () => { if (this.state.previousQuestion === undefined || this.state.currentQuestionIndex === 0) { this.setState({ previousButtonDisabled: true }); } else { this.setState({ previousButtonDisabled: false }); } if (this.state.nextQuestion === undefined || this.state.currentQuestionIndex + 1 === this.state.numberOfQuestions) { this.setState({ nextButtonDisabled: true }); } else { this.setState({ nextButtonDisabled: false }); } } // save summary datastate to database endGame = () => { alert('Quiz has eneded!'); const { state } = this; const playerStats = { score: state.score, numberOfQuestions: state.numberOfQuestions, numberOfAnsweredQuestions: state.correctAnswers + state.wrongAnswers, correctAnswers: state.correctAnswers, wrongAnswers: state.wrongAnswers, fiftyFiftyUsed: 2 - state.fiftyFifty, hintsUsed: 5 - state.hints }; setTimeout(() => { this.props.history.push('/play/quizSummary', playerStats); }, 1000); } render () { const { currentQuestion, name, } = this.state; return ( Quiz Page

{name} Quiz

{currentQuestion.question}

{currentQuestion.optionA}

{currentQuestion.optionB}

{currentQuestion.optionC}

{currentQuestion.optionD}

); } } export default withRouter(Play); 0 /*global describe, expect*/ const { parseEvent } = require('../../src/index'); const s3Event = require('../test-events/s3-event.json'); const { S3 } = require('../../src/constants/event'); describe('parse S3 event', () => { 'use strict'; test('should properly parse a well structured S3 event', () => { const parsedEvent = parseEvent(s3Event); expect(parsedEvent.sourceType).toEqual(S3); expect(parsedEvent.sourceEvent).toEqual(s3Event); expect(parsedEvent.records).toBeInstanceOf(Array); }); test('should return an array of extracted records', () => { const event = Object.assign({}, s3Event); event.Records[0].s3.object = 'apple'; event.Records[1].s3.object = 'pear'; event.Records[2].s3.object = 'orange'; const parsedEvent = parseEvent(event); expect(parsedEvent.sourceType).toEqual(S3); expect(parsedEvent.sourceEvent).toEqual(event); expect(parsedEvent.records).toEqual(['apple', 'pear', 'orange']); }); }); import { Story, Meta, html } from '@open-wc/demoing-storybook'; import { define } from '@webtides/accordion-group'; define(); export default { title: 'Elements/AccordionGroup', component: 'accordion-group', }; export const singleElement = () => html`
Accordion Header
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus accusantium, aliquid autem dicta eos, fuga fugiat incidunt itaque libero maxime non nostrum odio, perferendis placeat quia repellendus soluta sunt voluptatem! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta, minima numquam. Asperiores commodi consequuntur delectus dolor eos fuga natus nemo repellendus repudiandae sunt? Amet beatae dicta impedit, praesentium quis vel.
Accordion Header
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus accusantium, aliquid autem dicta eos, fuga fugiat incidunt itaque libero maxime non nostrum odio, perferendis placeat quia repellendus soluta sunt voluptatem!
Accordion Header
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus accusantium, aliquid autem dicta eos, fuga fugiat incidunt itaque libero maxime non nostrum odio, perferendis placeat quia repellendus soluta sunt voluptatem! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab aut cum dignissimos dolor dolorem excepturi expedita explicabo facilis id in incidunt, neque, nobis odio officia quia, quisquam quos suscipit veniam! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci alias amet autem cupiditate ea earum est explicabo illo inventore laboriosam neque nisi perferendis, quia quisquam quo sapiente voluptas voluptate voluptates?
`; export const multipleElement = () => html`
Accordion Header
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus accusantium, aliquid autem dicta eos, fuga fugiat incidunt itaque libero maxime non nostrum odio, perferendis placeat quia repellendus soluta sunt voluptatem! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta, minima numquam. Asperiores commodi consequuntur delectus dolor eos fuga natus nemo repellendus repudiandae sunt? Amet beatae dicta impedit, praesentium quis vel.
Accordion Header
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus accusantium, aliquid autem dicta eos, fuga fugiat incidunt itaque libero maxime non nostrum odio, perferendis placeat quia repellendus soluta sunt voluptatem!
Accordion Header
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus accusantium, aliquid autem dicta eos, fuga fugiat incidunt itaque libero maxime non nostrum odio, perferendis placeat quia repellendus soluta sunt voluptatem! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab aut cum dignissimos dolor dolorem excepturi expedita explicabo facilis id in incidunt, neque, nobis odio officia quia, quisquam quos suscipit veniam! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci alias amet autem cupiditate ea earum est explicabo illo inventore laboriosam neque nisi perferendis, quia quisquam quo sapiente voluptas voluptate voluptates?
`; jshazia/FashionZen import React from "react"; import { Link } from "react-router-dom"; const LogOutBtn = () => ( ); export default LogOutBtn;controllers/eventsController.js const Event = require('../models/event.js'); class EventsService { static create(obj) { const event = new Event(obj); return event.save(); } static public() { return Event.find({eventType:"Public"}) .then((event) => { // found return event; }); } static eventNum(id) { return Event.findOne({eventNum:id}) .then((event) => { // found return event; }); } static updateSeats(id, seats, vegans) { return Event.findById(id) .then((event) => { event.set({seatsOccupied:seats, seatsVegatarian:vegans}); event.save(); return event; }); } static update(id, data) { return Event.findById(id) .then((event) => { event.set(data); event.save(); return event; }); } static read(id) { return Event.findById(id) .then((event) => { // found return event; }); } static list() { return Event.find({}) .then((event) => { // found return event; }); } static delete(id) { return Event.deleteOne({ _id: id }) .then((obj) => { //removed return obj; }) } } module.exports.EventsService = EventsService; import React from 'react'; import ReactDOM from 'react-dom'; import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js'; class App extends React.Component { render() { let source = { datatype: 'json', datafields: [ { name: 'firstname' }, { name: 'lastname' }, { name: 'productname' }, { name: 'quantity', type: 'int' }, { name: 'price', type: 'float' }, { name: 'total', type: 'float' } ], id: 'id', url: '../sampledata/data.php', root: 'data' }; let dataAdapter = new $.jqx.dataAdapter(source); let columns = [ { text: 'First Name', dataField: 'firstname', width: 200 }, { text: 'Last Name', dataField: 'lastname', width: 200 }, { text: 'Product', dataField: 'productname', width: 180 }, { text: 'Quantity', dataField: 'quantity', width: 80, cellsalign: 'right' }, { text: 'Unit Price', dataField: 'price', width: 90, cellsalign: 'right', cellsformat: 'c2' }, { text: 'Total', dataField: 'total', cellsalign: 'right', minwidth: 100, cellsformat: 'c2' } ]; return (
) } } ReactDOM.render(, document.getElementById('app')); // data.php // const express = require('express') const server = express() const routes = require('./routes') const path = require('path') // instalar o ejs 'npm i ejs' server.set('view engine', 'ejs')// parte da biblioteca que me permite usar a engine para ler arquivos ejs server.set('views', path.join(__dirname, 'views')) // habilitar arquivos statics(imagens, obs a pasta public) server.use(express.static('public')) server.use(express.urlencoded({ extended: true })) //routes server.use(routes) server.listen(4000, () => console.log('rodando...'))LSystem.screen(LStage.FULL_SCREEN); init(50,"mylegend",480,288,main); LGlobal.setDebug(true); LRPG.setShortcuts(true); var backLayer,loadingLayer; var loadData = [ {path:"./js/script.js",type:"js"}, {name:"map",path:"./images/map01.jpg"}, {name:"player",path:"./images/p0.png"}, {name:"npc",path:"./images/p1.png"}, {name:"m",path:"./images/m.jpg"}, {name:"n",path:"./images/n.jpg"}, {name:"talk",path:"./images/back.png"}, {name:"e1",path:"./images/e1.png"}, {name:"e2",path:"./images/e2.png"} ]; var datalist = []; var map,mapData; var charaList; var talkContent; var jumpTo; var stage; var isJumpMap = false; var stageObj; var dir = ""; function main(){ loadingLayer = new LoadingSample3(); addChild(loadingLayer); LLoadManage.load( loadData, function(progress){ loadingLayer.setProgress(progress); }, gameInit ); } function gameInit(result){ removeChild(loadingLayer); datalist = result; initLayer(); initScriptData(); stage = script.stage01; initScript(); addCtrl(); } function initLayer(){ backLayer = new LSprite(); addChild(backLayer); ctrlLayer = new LSprite(); addChild(ctrlLayer); } function addScene(){ var mapObj = new LTileMap(map,datalist["map"],32,32,mapData); var stageData = new LSceneData(mapObj,charaList,talkContent); stageObj = new LScene(stageData); backLayer.addChild(stageObj); var talkBoardData = new LBitmapData(datalist["talk"]); var talkBoard = new LBitmap(talkBoardData); talkBoard.scaleX = 28; talkBoard.scaleY = 6.2; talkBoard.x = 100; talkBoard.y = 70; talkBoard.alpha = 0.7; stageObj.talk.x = 120; stageObj.talk.y = 30; stageObj.setTalkStyle({x:-80,y:20},{x:20,y:55,size:12,color:"lightgray"},{x:20,y:85,size:10,color:"lightgray"},talkBoard,200); stageObj.addMoveEventListener(LEvent.COMPLETE,function(){ for(var i=0;i= ctrlLayer.x + 40 && event.offsetX <= ctrlLayer.x+80){ if(event.offsetY >= ctrlLayer.y && event.offsetY <= ctrlLayer.y+40){ dir = "UP"; }else if(event.offsetY >= ctrlLayer.y+80 && event.offsetY <= ctrlLayer.y+120){ dir = "DOWN"; } }else if(event.offsetX >= ctrlLayer.x && event.offsetX <= ctrlLayer.x+40){ dir = "LEFT"; }else if(event.offsetX >= ctrlLayer.x+80 && event.offsetX <= ctrlLayer.x+120){ dir = "RIGHT"; } } function onup(event){ dir = ""; if(event.offsetX >= ctrlLayer.x + 280 && event.offsetX <= ctrlLayer.x+330){ if(event.offsetY >= ctrlLayer.y+40 && event.offsetY <= ctrlLayer.y+100){ stageObj.startTalk(); } } } function onframe(){ switch(dir){ case "UP": stageObj.movePlayer(LPlayerMove.UP); break; case "DOWN": stageObj.movePlayer(LPlayerMove.DOWN); break; case "LEFT": stageObj.movePlayer(LPlayerMove.LEFT); break; case "RIGHT": stageObj.movePlayer(LPlayerMove.RIGHT); break; } }client/tests/unit/components/Spinner.test.js1-10 import React from 'react'; import { shallow } from 'enzyme'; import Spinner from '../../../src/components/Spinner.jsx'; describe('Spinner component', () => { const comp = shallow(); it('should contain .spinner-overlay', () => { expect(comp.hasClass('spinner-overlay')).toBeTruthy(); }); it('should contain .spinner-container', () => { expect(comp.exists('spinner-container')).toBeTruthy(); }); it('should render spinner correctly', () => { expect(comp.html()) .toEqual('
'); }); }); import React from 'react'; import PropTypes from 'prop-types'; import { View, Modal, StyleSheet } from 'react-native'; import LottieView from 'lottie-react-native'; const styles = StyleSheet.create({ container: { flex: 1 }, centered: { justifyContent: 'center', alignItems: 'center' }, opacity: { backgroundColor: '#00000050' }, animation: { width: 100, height: 100 } }); const Loading = ({ visible }) => ( ); Loading.propTypes = { visible: PropTypes.bool }; export default Loading; let observer = new IntersectionObserver(entries => { entries.forEach((entry)=>{ let event = new CustomEvent('inview',{detail:{intersectionRatio:entry.intersectionRatio}}); entry.target.dispatchEvent(event); }); }); export function initialize( application ) { application.register('service:intersection', observer, { instantiate: false }); } export default { name: 'intersection', initialize };; (function (window, document, $, Q, FileReader, XLSX, Papa, undefined) { 'use strict'; // Custom File Types // ======================================================================== var customFiles = { extend: extendFile }; function extendFile(file) { var defer = Q.defer(); var type = String.prototype.trim.call(file.type) !== "" ? file.type : askAboutType(file); // csv -> "type/csv" // ods -> "application/vnd.oasis.opendocument.spreadsheet" // xlsx -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" // zip -> "application/zip" // pdf -> "application/pdf" // docx -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document" // if (file.type.indexOf('image/') === 0) { // return new ImageFile(file); // } // // if (file.type === 'type/csv') { // return new CSVFile(file); // } Q.when(type, createFile); function createFile(type) { switch (type) { // == images == case "image": case "image/png": case "image/gif": case "image/pjpg": case "image/jpg": case "image/pjpeg": case "image/jpeg": case "image/png": defer.resolve(new ImageFile(file)); break; // == excel == case "ods": case "application/vnd.oasis.opendocument.spreadsheet": // .ods case "xlsx": case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": // .xlsx defer.resolve(new XLSXFile(file)); break; case "csv": case "text/csv": defer.resolve(new CSVFile(file)); break; default: defer.resolve(new BasicFile(file)); break; } } return defer.promise; } function askAboutType(file) { var defer = Q.defer(); var modal = [ '' ].join(''); var select = [ '' ].join(''); var btn = [ '' ].join(''); var $modal = $(modal); var $select = $(select); var $btn = $(btn); var listener = function (evt) { evt.preventDefault(); var value = $select.val(); $btn.off('click', listener); $modal.remove(); defer.resolve(value); }; $btn.on('click', listener); $modal.find('.modal-ibge-body').append($select); $modal.find('.modal-ibge-footer').append($btn); $modal.appendTo('body'); return defer.promise; } window.customFiles = customFiles; /* * Basic/TXT Files * ------------------------------------------------------------------------ */ function BasicFile(file) { var self = this; Object.keys(file).forEach(function (key) { self[key] = file[key]; }); self.value = file; this.customType = 'text'; self.Text = ""; return self; } BasicFile.prototype = Object.create(window.File.prototype); Object.defineProperties(BasicFile.prototype, { readFile: { value: readAsText }, hasText: { value: hasText }, 'upload': { value: upload }, appendTo: { value: appendTo } }); function readAsText() { var self = this; var file = this.value; if (self.hasText()) { return self.Text; } var defer = Q.defer(); var reader = new FileReader(); reader.onload = function (event) { var contents = event.target.result; // console.log("File contents: " + contents); self.Text = contents; defer.resolve(contents); }; reader.onerror = function (event) { console.error("File could not be read! Code " + event.target.error.code); defer.reject(event.target.error); }; reader.readAsText(file); return defer.promise; } function hasText() { return this.Text && this.Text.trim() !== ""; } function upload(url, cb) { cb = cb || defaultCallback; var file = this.value; return Q($.post(url, file)).then(cb); function defaultCallback(responseText) { if (responseText.status === 'error') { return responseText.message; } return responseText; } } function appendTo(element, tag, cssClass) { tag = tag || '

'; cssClass = cssClass || ''; var defer = Q.defer(); var self = this; Q.when(self.readFile(), function (txt) { var $el = $(tag, { 'class': cssClass, 'text': txt }); defer.resolve($el.appendTo(element)); }); return defer.promise; } /* * CSV Files * ------------------------------------------------------------------------ */ function CSVFile(file) { BasicFile.call(this, file); this.Table = null; return this; } CSVFile.prototype = Object.create(BasicFile.prototype); Object.defineProperties(CSVFile.prototype, { toTable: { value: toTable } // toEditableTable: { // value: toEditableTable // } }); function toTable(headerRows, cssTableClass) { var self = this; if (self.Table) { return self.Table; } var defer = Q.defer(); Q.when(self.readFile(), function (str) { var $table = $('', { 'class': cssTableClass }); var fastMode = (str.slice(0) === "'" && str.slice(-1) === "'") || (str.slice(0) === '"' && str.slice(-1) === '"'); var parse = Papa.parse(str, { delimiter: "", // auto-detect newline: "", // auto-detect header: false, dynamicTyping: true, preview: 0, encoding: "", worker: false, comments: false, //step: undefined, //complete: undefined, //error: undefined, download: false, skipEmptyLines: true, //chunk: undefined, fastMode: fastMode }); var columns = []; if (Array.isArray(headerRows)) { columns = _buildColumns(headerRows); } else { if (isNaN(parseInt(headerRows, 10)) || headerRows < 1) { headerRows = 1; } var $thead = $(''); for (var i = 0; i < headerRows; i++) { var row = parse.data.shift(); var $row = $(''); row.forEach(function (val) { $row.append($(''); } var config = {}; config.data = parse.data; if (columns.length) { config.columns = columns; } $table.dataTable(config); self.Table = $table; defer.resolve($table); }); return defer.promise; } function _buildColumns(array) { return array.map(function (str) { return { title: str }; }); } function appendTo(element, cssClass) { cssClass = cssClass || ''; var defer = Q.defer(); var self = this; Q.when(self.toTable(), function ($table) { if (cssClass) { $table.addClass(cssClass); } defer.resolve($table.appendTo(element)); }); return defer.promise; } /* * XSLX/ODS Files * ------------------------------------------------------------------------ */ function XLSXFile(file) { CSVFile.call(this, file); this.XLSX = null; this.customType = 'excel'; return this; } XLSXFile.prototype = Object.create(CSVFile.prototype); Object.defineProperties(XLSXFile.prototype, { readFile: { value: toCSV }, openFile: { value: readXLSXFile } }); function readXLSXFile() { var reader = new FileReader(); var self = this; var file = self.value; if (this.XLSX) { return this.XLSX; } var defer = Q.defer(); var reader = new FileReader(); reader.onload = function (event) { var data = event.target.result; //var wb = XLSX.read(data, {type: 'binary'}); var arr = String.fromCharCode.apply(null, new Uint8Array(data)); var wb = XLSX.read(btoa(arr), { type: 'base64' }); self.XLSX = wb; defer.resolve(wb); }; reader.onerror = function (event) { console.error("File could not be read! Code " + event.target.error.code); defer.reject(event.target.error); }; //reader.readAsBinaryString(f); reader.readAsArrayBuffer(file); return defer.promise; } function toCSV(options) { var defer = Q.defer(); var self = this; if (self.hasText()) { return self.Text; } Q.when(self.openFile(), function (file) { var result = []; file.SheetNames.forEach(function (sheetName) { var csv = XLSX.utils.sheet_to_csv(file.Sheets[sheetName]); if (csv.length > 0) { // result.push(""); result.push(csv); } }); self.Text = result.join("\n"); defer.resolve(result.join("\n")); }); return defer.promise; } /* * Image Files * ------------------------------------------------------------------------ */ function ImageFile(file) { BasicFile.call(this, file); this.customType = 'image'; this.Img = null; return this; } ImageFile.prototype = Object.create(BasicFile.prototype); Object.defineProperties(ImageFile.prototype, { 'readFile': { value: buildImg }, 'appendTo': { value: appendImgTo } }); function buildImg() { if (this.Img) { return this.Img; } var defer = Q.defer(); var self = this; var reader = new FileReader(); reader.onload = function (event) { var dataUri = event.target.result, img = document.createElement("img"); img.src = dataUri; // document.body.appendChild(img); self.Img = img; defer.resolve(img); }; reader.onerror = function (event) { console.error("File could not be read! Code " + event.target.error.code); defer.reject(event.target.error); }; reader.readAsDataURL(self.value); return defer.promise; } function appendImgTo(element) { var defer = Q.defer(); var self = this; Q.when(self.readFile(), function (img) { defer.resolve($(img).appendTo(element)); }); return defer.promise; } })(this, this.document, jQuery, Q, FileReader, XLSX, Papa);'use strict' import { getPosts as getPostsService, getPost as getPostService, createPost as createPostService, updatePost as updatePostService, deletePost as deletePostService } from '../services/postService'; const response = (res, status, data) => { res.status(status || 500).send(data) } export async function getPosts(req, res) { const posts = await getPostsService() response(res, posts.status, posts.data || posts.message) } export async function getPost(req, res) { const id = req.params.id const post = await getPostService(id) response(res, post.status, post.data || post.message) } export async function createPost(req, res) { const postBody = req.body const post = await createPostService(postBody) response(res, post.status, post.data || post.message) } export async function updatePost(req, res) { const id = req.params.id; const postBody = req.body; const post = await updatePostService(id, postBody) response(res, post.status, post.data || post.message) } export async function deletePost(req, res) { const id = req.params.id; const post = await deletePostService(id) response(res, post.status, post.data || post.message) } Pat-On/repairs_for_you import { createHmac, randomBytes, createHash } from "crypto"; const bcrypt = require("bcryptjs"); import { pool } from "../db"; exports.signUpUser = async (userObj) => { try { // 1) TO CHECK IF INPUT HAS WHAT WE NEED plus SANITIZATION const { name, email, password, passwordConfirm, role } = userObj; if (role === "admin") throw new Error("Creating admins in this way is forbidden"); if ((role !== "buyer" && role !== "handyperson") || role === "") throw new Error("You can only create buyer or handyperson account"); if (!name) throw new Error("You need to provide name"); if (!email) throw new Error("You need to provide email address"); //!TODO: backend validation if (!(password === passwordConfirm)) throw new Error("Password and password confirmation must be equal"); // 2) run pool.query() - may give the error if mail is in use - return msg to front const encryptedPassword = await bcrypt.hash(password, 12); //.hash() is async const dataOfCreation = new Date(); // 3) // !TODO: returning * is not best solution in my opinion / temporary - kick out password from input later const newUser = await pool.query( `INSERT INTO users (first_name, email, user_password, password_changed_at, user_role) VALUES ($1, $2, $3, $4, $5) RETURNING * `, [name, email, encryptedPassword, dataOfCreation, role] ); // 3) if success inform user return newUser; // !TODO: is it all? } catch (error) { throw error; } }; exports.logInUser = async (userCredential) => { try { const { email, password } = userCredential; const newUserArray = await pool.query( `SELECT * FROM users WHERE email = $1`, [email] ); if (newUserArray.rowCount === 0) throw new Error("Incorrect email or password"); const newUser = newUserArray.rows[0]; //return true if both password are the same const testBoolean = await bcrypt.compare(password, new); if (!testBoolean) throw new Error("Incorrect email or password"); // 3) if success inform user return newUser; } catch (error) { throw error; } }; exports.findUserByTokenDecoded = async (decoded) => { try { const newUserArray = await pool.query( `SELECT * FROM users WHERE user_id = $1`, [decoded.id] ); if (newUserArray.rowCount === 0) throw new Error("The user related to this token does no longer exist."); const newUser = newUserArray.rows[0]; const changedTimestamp = parseInt( newUser.password_changed_at.getTime() / 1000, 10 ); if (decoded.iat < changedTimestamp) throw new Error("Not valid token"); return newUser; } catch (error) { throw error; } }; exports.findOneUser = async (userCredential) => { try { const { email } = userCredential; const newUserArray = await pool.query( `SELECT * FROM users WHERE email = $1`, [email] ); if (newUserArray.rowCount === 0) throw new Error("User with that email no exist"); const newUser = newUserArray.rows[0]; return newUser; } catch (error) {} }; exports.createPasswordResetToken = async (userObject) => { try { const resetToken = randomBytes(32).toString("hex"); const passwordResetTokenToDB = createHash("sha256") .update(resetToken) .digest("hex"); const expirationTime = new Date(); expirationTime.setMinutes(expirationTime.getMinutes() + 10); const newUserArray = await pool.query( `UPDATE users SET password_reset_token = $1, password_reset_expires = $2 WHERE email = $3`, [passwordResetTokenToDB, expirationTime, userObject.email] ); return resetToken; } catch (error) { throw error; } }; exports.findUserBaseOnResetToken = async (token) => { try { const userToResetPassword = await pool.query( `SELECT * FROM users WHERE password_reset_token=$1;`, [token] ); if (userToResetPassword.rowCount === 0) throw new Error("There is no user related to that token"); const user = userToResetPassword.rows[0]; // check if the token did not expires. const date = new Date(user.password_reset_expires); const milliseconds = date.getTime(); if (milliseconds < Date.now()) throw new Error("Token already expired"); return user; } catch (error) { throw error; } }; exports.updatePasswordAfterRecovery = async ( user, password, passwordConfirm ) => { try { //!TODO: is it logical tu put it earlier? I think so - do in refactor if (!password || !passwordConfirm) throw new Error("You need to provide password and password confirmation"); if (password !== passwordConfirm) throw new Error("Password and password confirmation must be equal"); const encryptedPassword = await bcrypt.hash(password, 12); //.hash() is async // minus 1000 millisecond from data Of creation -> because saving to DB is taking time const dataOfCreation = new Date(); //!TODO: what about cleaning the fields in DB? null? empty string? const _ = await pool.query( `UPDATE users SET user_password = $1, password_changed_at = $2, password_reset_token=$3, password_reset_expires=$4 WHERE email = $5`, [ encryptedPassword, dataOfCreation, "", "1970-06-21 15:46:38.799+01", user.email, ] ); //!TODO: dummy return return ""; } catch (error) { throw error; } }; exports.findUserById = async (userId, passwordCurrent) => { try { const userToChangePassword = await pool.query( `SELECT * FROM users WHERE user_id=$1;`, [userId] ); const userObject = userToChangePassword.rows[0]; //!TODO: take out this part of the code and create helper function to check passwords //return true if both password are the same const testBoolean = await bcrypt.compare( passwordCurrent, userObject.user_password ); if (!testBoolean) throw new Error("Incorrect password"); return userObject; } catch (error) { throw error; } }; exports.updateUserPassword = async ( userId, passwordCandidate, passwordCandidateConfirm ) => { try { if (passwordCandidate !== passwordCandidateConfirm) throw new Error("Password candidates are not equal"); const encryptedPassword = await bcrypt.hash(passwordCandidate, 12); //.hash() is async // minus 1000 millisecond from data Of creation -> because saving to DB is taking time const dataOfCreation = new Date(); const _ = await pool.query( `UPDATE users SET user_password = $1, password_changed_at = $2 WHERE user_id = $3`, [encryptedPassword, dataOfCreation, userId] ); //!TODO: dummy return return ""; } catch (error) { throw error; } }; issaTan/weapp-demogulpfile.js const gulp = require('gulp'); const gulpSequence = require('gulp-sequence'); const newer = require('gulp-newer'); const filter = require('gulp-filter'); const gulpif = require('gulp-if'); const watch = require('gulp-watch'); const plumber = require('gulp-plumber'); const gutil = require('gulp-util'); const del = require('del'); const less = require('gulp-less'); const replace = require('gulp-replace'); const base64 = require('gulp-base64'); const cleanCss = require('gulp-clean-css'); const sourcemaps = require('gulp-sourcemaps'); const rename = require('gulp-rename'); const eslint = require('gulp-eslint'); const friendlyFormatter = require('eslint-friendly-formatter'); const babel = require('gulp-babel'); const uglify = require('gulp-uglify'); const imagemin = require('gulp-imagemin'); const notify = require('gulp-notify'); const through = require('through2'); const path = require('path'); const config = require('./.gulprc.js'); const prod = process.env.NODE_ENV === 'production'; gulp.task('clean', () => del([`${config.dest}/**`])); function prefixStream(prefixText) { const stream = through(); stream.write(prefixText); return stream; } function gulpAddRequireRuntime() { // 创建一个让每个文件通过的 stream 通道 return through.obj((file, enc, cb) => { let prefixText = ''; let rel = path.relative(path.dirname(file.path), path.join(file.base, 'libs/regenerator/runtime.js')); rel = rel.replace(/\\/g, '/'); if (rel === 'runtime.js') { prefixText = new Buffer(prefixText); // 预先分配 } else { prefixText = `var regeneratorRuntime = require("${rel}");`; prefixText = new Buffer(prefixText); // 预先分配 } if (file.isNull()) { // 返回空文件 cb(null, file); } if (file.isBuffer()) { file.contents = Buffer.concat([prefixText, file.contents]); } if (file.isStream()) { file.contents = file.contents.pipe(prefixStream(prefixText)); } cb(null, file); }); } // 处理js 文件,包括eslint/babel/压缩 let buildJsSrc = config.source.js; gulp.task('buildJs', () => gulp.src(buildJsSrc, { base: config.base }) .pipe(newer(config.dest)) .pipe(plumber({ errorHandler: (err) => { gutil.log(err.stack); }, })) .pipe(gulpif(prod, sourcemaps.init())) .pipe(eslint('.eslintrc.js')) .pipe(eslint.format(friendlyFormatter)) .pipe(babel()) .pipe(gulpAddRequireRuntime()) .pipe(gulpif(prod, uglify())) .pipe(gulpif(prod, sourcemaps.write())) .pipe(gulp.dest(config.dest))); // 处理less文件 const sourceLessSrc = config.source.less; const buildLessSrc = config.src.less; gulp.task('buildLess', () => gulp.src(buildLessSrc, { base: config.base }) .pipe(filter(sourceLessSrc)) .pipe(gulpif(prod, sourcemaps.init())) .pipe(plumber({ errorHandler: notify.onError('Error:<%= error.message %>') })) .pipe(less({ relativeUrls: true })) .pipe(replace(/px/g, 'rpx')) .pipe(base64({ extensions: ['png', 'jpg', 'jpeg', 'gif', 'svg'], maxImageSize: 10000, debug: false })) .pipe(gulpif(prod, cleanCss())) .pipe(gulpif(prod, sourcemaps.write())) .pipe(rename((parsedPath) => { parsedPath.extname = '.wxss'; })) .pipe(gulp.dest(config.dest))); // 处理wxss 文件 let buildWxssSrc = config.source.wxss; gulp.task('buildWxss', () => gulp.src(buildWxssSrc, { base: config.base }) .pipe(newer(config.dest)) .pipe(gulp.dest(config.dest))); // 处理图片 let buildImageSrc = config.source.img; gulp.task('buildImage', () => gulp.src(buildImageSrc, { base: config.base }) .pipe(newer(config.dest)) .pipe(plumber({ errorHandler: (err) => { gutil.log(err.stack); }, })) .pipe(imagemin()) .pipe(gulp.dest(`${config.dest}`))); // 处理wxml let buildWxmlSrc = config.source.wxml; gulp.task('buildWxml', () => gulp.src(buildWxmlSrc, { base: config.base }) .pipe(newer(config.dest)) .pipe(plumber({ errorHandler: (err) => { gutil.log(err.stack); }, })) .pipe(gulp.dest(config.dest))); // 处理json let buildJsonSrc = config.source.json; gulp.task('buildJson', () => gulp.src(buildJsonSrc, { base: config.base }) .pipe(newer(config.dest)) .pipe(gulp.dest(config.dest))); gulp.task('buildContent', (cb) => { gulpSequence('buildImage', 'buildLess', 'buildJs', 'buildWxml', 'buildJson')(cb); }); gulp.task('build', (cb) => { gulpSequence('clean', 'buildContent')(cb); }); gulp.task('watch', gulpSequence('buildContent', () => { watch(config.source.js, { debounceDelay: 200 }, (res) => { buildJsSrc = [`${config.base}/${res.relative}`]; gulp.start('buildJs'); gutil.log(`File ${res.history} was ${res.event}, tasks running ...`); }); watch(config.src.less, { debounceDelay: 200 }, (res) => { gulp.start('buildLess'); gutil.log(`File ${res.history} was ${res.event}, tasks running ...`); }); watch(config.source.wxss, { debounceDelay: 200 }, (res) => { buildWxssSrc = [`${config.base}/${res.relative}`]; gulp.start('buildWxss'); gutil.log(`File ${res.history} was ${res.event}, tasks running ...`); }); watch(config.source.img, { debounceDelay: 200 }, (res) => { buildImageSrc = [`${config.base}/${res.relative}`]; gulp.start('buildImage'); gutil.log(`File ${res.history} was ${res.event}, tasks running ...`); }); watch(config.source.wxml, { debounceDelay: 200 }, (res) => { buildWxmlSrc = [`${config.base}/${res.relative}`]; gulp.start('buildWxml'); gutil.log(`File ${res.history} was ${res.event}, tasks running ...`); }); watch(config.source.json, { debounceDelay: 200 }, (res) => { buildJsonSrc = [`${config.base}/${res.relative}`]; gulp.start('buildJson'); gutil.log(`File ${res.history} was ${res.event}, tasks running ...`); }); })); gulp.task('default', ['watch']); // UBER API STARTER KIT FOR NODE/EXPRESS // We use passport to handle oauth for uber, passport uses express-session, and we use the passport-uber strategy. Https for sending api requests from our server and bodyparser for post data. var express = require('express'); var session = require('express-session'); var passport = require('passport'); var uberStrategy = require('passport-uber'); var https = require('https'); var bodyParser = require('body-parser'); var app = express(); var config = require('./config.js'); // Get all auth stuff from config file // ClientID & ClientSecret for API requests with OAUTH var clientID = config.ClientID; var clientSecret = config.ClientSecret; // ServerID for API requests without OAUTH var ServerID = config.ServerID; // sessionSecret used by passport var sessionSecret = "UBERAPIROCKS" app.use(session({ secret: sessionSecret, resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); // app.use('/img',express.static(path.join(__dirname, 'public/images'))); // app.use('/js',express.static(path.join(__dirname, 'public/javascripts'))); // app.use('/css',express.static(path.join(__dirname, 'public/stylesheets'))); app.use(express.static(__dirname + 'client')); app.set('views', __dirname + '/../client/views'); app.set('view engine','ejs'); // bodyparser for handling post data app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); // post to show unauthorized request app.post('/cars', function(request, response) { getRequest('/v1/products?latitude='+request.body.start_latitude+'&longitude='+request.body.start_longitude, function(err, res) { response.json(ServerID, res); }) }) // use this for an api get request without oauth function getRequest(endpoint, callback) { var options = { hostname: "sandbox-api.uber.com", path: endpoint, method: "GET", headers: { Authorization: "Token " + ServerID } } var req = https.request(options, function(res) { res.on('data', function(data) { console.log('data!'); console.log(JSON.parse(data)); callback(null, JSON.parse(data)); }) }) req.end(); req.on('error', function(err) { callback(err, null); }); } // _______________ BEGIN PASSPORT STUFF ________________ // Serialize and deserialize users used by passport passport.serializeUser(function (user, done){ done(null, user); }); passport.deserializeUser(function (user, done){ done(null, user); }); // define what strategy passport will use -- this comes from passport-uber passport.use(new uberStrategy({ clientID: clientID, clientSecret: clientSecret, callbackURL: "http://localhost:8000/auth/uber/callback" }, function (accessToken, refreshToken, user, done) { console.log('user:', user.first_name, user.last_name); console.log('access token:', accessToken); console.log('refresh token:', refreshToken); // THIS IS WHERE YOU WOULD PUT SOME DB LOGIC TO SAVE THE USER user.accessToken = accessToken; return done(null, user); } )); // login page app.get('/login', function (request, response) { response.render('login'); }); // get request to start the whole oauth process with passport app.get('/auth/uber', passport.authenticate('uber', { scope: ['profile', 'history', 'history_lite', 'request', 'request_receipt'] } ) ); // authentication callback redirects to /login if authentication failed or home if successful app.get('/auth/uber/callback', passport.authenticate('uber', { failureRedirect: '/login' }), function(req, res) { res.redirect('/'); }); // home after the user is authenticated app.get('/', ensureAuthenticated, function (request, response) { response.render('index'); }); // /profile API endpoint app.get('/profile', ensureAuthenticated, function (request, response) { getAuthorizedRequest('/v1/me', request.user.accessToken, function (error, res) { if (error) { console.log(error); } response.json(res); }); }); // /history API endpoint app.get('/history', ensureAuthenticated, function (request, response) { getAuthorizedRequest('/v1.2/history', request.user.accessToken, function (error, res) { if (error) { console.log("err", error); } console.log(res); response.json(res); }); }); // ride request API endpoint app.post('/request', ensureAuthenticated, function (request, response) { // NOTE! Keep in mind that, although this link is a GET request, the actual ride request must be a POST, as shown below var parameters = { start_latitude : request.body.start_latitude, start_longitude: request.body.start_longitude, end_latitude: request.body.end_latitude, end_longitude: request.body.end_longitude, product_id: "a1111c8c-c720-46c3-8534-2fcdd730040d" }; postAuthorizedRequest('/v1/requests', request.user.accessToken, parameters, function (error, res) { if (error) { console.log(error); } response.json(res); }); }); // logout app.get('/logout', function (request, response) { request.logout(); response.redirect('/login'); }); // route middleware to make sure the request is from an authenticated user function ensureAuthenticated (request, response, next) { console.log('inside ensure Authenticated'); if (request.isAuthenticated()) { return next(); } response.redirect('/login'); } // use this for an api get request function getAuthorizedRequest(endpoint, accessToken, callback) { var options = { hostname: "sandbox-api.uber.com", path: endpoint, method: "GET", headers: { Authorization: "Bearer " + accessToken } } var req = https.request(options, function(res) { res.on('data', function(data) { console.log('data!'); console.log(JSON.parse(data)); callback(null, JSON.parse(data)); }) }) req.end(); req.on('error', function(err) { callback(err, null); }); } // use this for an api post request function postAuthorizedRequest(endpoint, accessToken, parameters, callback) { var options = { hostname: "sandbox-api.uber.com", path: endpoint, method: "POST", headers: { Authorization: "Bearer " + accessToken, 'Content-Type': 'application/json' } } var req = https.request(options, function(res) { res.on('data', function(data) { console.log('data!'); console.log(JSON.parse(data)); callback(null, JSON.parse(data)); }) }) req.write(JSON.stringify(parameters)); req.end(); req.on('error', function(err) { callback(err, null); }); } // start server var server = app.listen(8000, function(){ console.log('listening to port: 8000'); }); dontry/js-basics function plucker(field) { return function(obj) { return obj && obj[field]; }; } module.exports = plucker; import React, {Component} from 'react' import {findDOMNode} from 'react-dom' import Firebase from 'firebase' import Rebase from 're-base' import utils from '../../utils/firebaseUtils' //import {URL} from '../../config/firebase' const URL = "https://brilliant-torch-4963.firebaseio.com/"; let ref = new Firebase(URL); let base = Rebase.createClass(URL); var initialDate = new Date(); import {Button, Dialog, Dropdown} from 'react-toolbox' import MeetingEditor from '../SmallComponents/MeetingEditor' // To be deleted when the group dropdown is no longer in effect. const groups = [ {value: 0, gid: '', label: ''}, {value: 1, gid: 'iungo', label:'IUNGO'}, {value: 2, gid: 'forsam', label: 'ForSam'} ] class NewMeeting extends Component { state = { visible: false, gid: 'iungo', //from props groupName: 'IUNGO', //from props value: 0 }; onClick = () => { this.setState({ visible: true }) }; closeModal = () => { this.setState({ visible: false }) }; handleSubmit = (formData) => { const { title, address, agenda, date, startTime, endTime, notification, value } = formData; var path = 'networkgroups/' + groups[value]['gid'] + '/members'; base.fetch(path, { context: this, then(data){ var part = {}; Object.keys(data).forEach(key => { part[key] = {status: 0} }); console.log(part); this.createNewMeetingToFB({ title, address, endTimestamp: new Date( date.getFullYear(), date.getMonth(), date.getDate(), endTime.getHours(), endTime.getMinutes(), endTime.getSeconds()).getTime()/1000, startTimestamp: new Date( date.getFullYear(), date.getMonth(), date.getDate(), startTime.getHours(), startTime.getMinutes(), startTime.getSeconds()).getTime()/1000, participants: part, text: agenda }, groups[value]['gid'], groups[value]['label'], notification, data); /* TODO: Check if the meeting was successfully created (use rebase in utils and have createNewMeetingToFB return true or false), and send notifications to all users. Use Object.keys(data).forEach(). */ } }) }; createNewMeetingToFB = (meeting, gid, groupName, notification, members) =>{ var meetingRef = ref.child('networkgroups').child(gid).child('meetings').push(meeting, function(error) { if (error) { console.log('The meeting could not be saved'); } else { console.log("The meeting has been saved"); console.log(meetingRef.key()); if(notification){ Object.keys(members).forEach(key => { ref.child('notifications').push({ from: gid, fromName: groupName, read: false, to: key, title: "Nyt møde hos " + groupName, type: 'newMeeting', reference: "/networkgroups/" + gid + "/meetings/" + meetingRef.key(), timestamp: new Date().getTime() }) }) } } }); console.log("Done"); this.closeModal() }; render(){ return (

Create new meeting

) } } export default NewMeeting 1-10 /** * @fileoverview This module provides a constructor for an ftp server * user manager operating on top of an object containing the user accounts. */ addToClasspath("../jars/ftplet-api-1.1.1.jar"); addToClasspath("../jars/ftpserver-core-1.1.1.jar"); const {AuthenticationFailedException} = org.apache.ftpserver.ftplet; const {SaltedPasswordEncryptor} = org.apache.ftpserver.usermanager; const {BaseUser, WritePermission, ConcurrentLoginPermission, TransferRatePermission} = org.apache.ftpserver.usermanager.impl; const {UsernamePasswordAuthentication, AnonymousAuthentication} = org.apache.ftpserver.usermanager; const FtpletUserManager = org.apache.ftpserver.ftplet.UserManager; const {IllegalArgumentException} = java.lang; const {ArrayList} = java.util; const {EventEmitter} = require("ringo/events"); /** * Encrypts the password passed as argument. * @param {String} password The password to encrypt * @returns {String} The encrypted password */ exports.encryptPassword = function(password) { const encryptor = new SaltedPasswordEncryptor(); return encryptor.encrypt(password); }; /** * Returns a new UserManager instance * @class Instances of this class represent a usermanager operating on * a hash of user accounts. * @param {Object} users An object with properties for each user containing * at least the name, password and homeDirectory. * @returns {UserManager} A newly constructed user manager * @constructor */ const UserManager = exports.UserManager = function(users) { let adminName = "admin"; EventEmitter.call(this); Object.defineProperties(this, { /** * An object containing the user accounts * @type Object */ "users": { "get": function() { return users || {}; }, "enumerable": true, "configurable": true }, /** * Returns the name of the admin account (default: `admin`) * @returns {String} The name of the admin account */ "getAdminName": { "value": function() { return adminName; }, "enumerable": true, "configurable": true }, /** * Sets the admin name to the one passed as argument * @param {String} name The name of the admin account */ "setAdminName": { "value": function(name) { adminName = name; }, "enumerable": true, "configurable": true }, /** * Loads the users from the JSON file. This method triggers a "reloaded" * event on this usermanager instance. * @param {Object} obj An object containing the user accounts */ "loadUsers": { "value": sync(function(obj) { if (!obj || typeof(obj) !== "object" || obj.constructor !== Object) { throw new Error("loadUsers expects an object as argument"); } users = obj; this.emit("reloaded"); }, this), "enumerable": true, "writable": true } }); return this; }; /** * Convenience method for creating a UserManager instance suitable for * use with ftpserver module. * @param {Object} obj An object containing the user accounts * @returns {org.apache.ftpserver.ftplet.UserManager} The user manager instance */ UserManager.create = function(obj) { return new FtpletUserManager(new UserManager(obj)); }; Object.defineProperties(UserManager.prototype, { /** * The encryptor used by this user manager * @type org.apache.ftpserver.usermanager.SaltedPasswordEncryptor */ "encryptor": { "value": new SaltedPasswordEncryptor(), "enumerable": true } }); /** * Authenticates against the user accounts of this manager * @param {UsernamePasswordAuthentication|AnonymousAuthentication} authentication The * authentication request to verify. * @returns {BaseUser} If authentication was successful, this method returns the * user object, otherwise it throws an AuthenticationFailedException */ UserManager.prototype.authenticate = function(authentication) { if (authentication instanceof UsernamePasswordAuthentication) { const username = authentication.getUsername(); const password = authentication.getPassword() || ""; if (username == null || !this.doesExist(username)) { throw new AuthenticationFailedException("Authentication failed"); } const user = this.getUserByName(username); if (this.encryptor.matches(password, user.getPassword())) { return user; } else { throw new AuthenticationFailedException("Authentication failed"); } } else if (authentication instanceof AnonymousAuthentication) { if (this.doesExist("anonymous")) { return this.getUserByName("anonymous"); } else { throw new AuthenticationFailedException("Authentication failed"); } } else { throw new IllegalArgumentException("Authentication not supported by this user manager"); } }; /** * Removes the user with the given name from the underlying users object * @param {String} username The name of the user to remove */ UserManager.prototype["delete"] = function(username) { if (this.doesExist(username)) { delete this.users[username]; } }; /** * Returns true if this manager has a user with the given username * @param {String} username The username to check if existing * @returns {Boolean} True if the user exists, false otherwise */ UserManager.prototype.doesExist = function(username) { return this.users.hasOwnProperty(username); }; /** * Returns an array containing all user names known to this manager * @returns {Array} An array containing all user names */ UserManager.prototype.getAllUserNames = function() { return Object.keys(this.users); }; /** * Returns the user with the given name * @param {String} username The user name * @returns {User} The user object, or null if the user doesn't exist */ UserManager.prototype.getUserByName = function(username) { if (!this.doesExist(username)) { return null; } const props = this.users[username]; const user = new BaseUser(); user.setName(props.name); user.setPassword(props.password); user.setHomeDirectory(props.homeDirectory); user.setEnabled(props.isEnabled === true); const authorities = new ArrayList(); if (props.canWrite !== false) { authorities.add(new WritePermission()); } authorities.add(new ConcurrentLoginPermission(props.maxLogin || 0, props.maxLoginPerIp || 0)); authorities.add(new TransferRatePermission(props.downloadRate || 0, props.uploadRate || 0)); user.setAuthorities(authorities); user.setMaxIdleTime(props.maxIdleTime || 0); return user; }; /** * Returns true if the user name passed as argument equals the admin account name. * @param {String} username The user name * @returns {Boolean} True if the user name equals the admin name, false otherwise */ UserManager.prototype.isAdmin = function(username) { return username === this.getAdminName(); }; /** * Adds the user to the list of accounts, possibly replacing an already * existing account with the same name. * @param {Object} user The user account data */ UserManager.prototype.save = function(user) { if (user.name == null || typeof(user.name) !== "string") { throw new Error("User name is null or not a string"); } this.users[user.name] = user; }; define( [ 'qunit', 'tests/mockup/mockup', 'osg/Camera', 'osg/Matrix', 'osg/MatrixTransform', 'osg/TransformEnums' ], function ( QUnit, mockup, Camera, Matrix, MatrixTransform, TransformEnums ) { 'use strict'; return function () { QUnit.module( 'osg' ); QUnit.test( 'Camera', function () { var matrix = Matrix.makeOrtho( -1, 1, -1, 1, -2, 2, Matrix.create() ); var camera = new Camera(); camera.setProjectionMatrixAsOrtho( -1, 1, -1, 1, -2, 2 ); mockup.near( matrix, camera.getProjectionMatrix(), 'check Camera.setProjectionMatrixAsOrtho' ); } ); QUnit.test( 'Camera absolute vs relative', function () { var rotation = Matrix.makeRotate( -Math.PI * 0.5, 1.0, 0.0, 0.0, Matrix.create() ); var translate = Matrix.makeTranslate( 1, 0, 0, Matrix.create() ); var invRotation = Matrix.create(); Matrix.inverse( rotation, invRotation ); var camera = new Camera(); Matrix.copy( rotation, camera.getViewMatrix() ); var test = Matrix.create(); Matrix.copy( translate, test ); camera.computeLocalToWorldMatrix( test ); mockup.near( test, Matrix.mult( translate, rotation, Matrix.create() ), 'Should expect Translation * Rotation' ); Matrix.copy( translate, test ); camera.computeWorldToLocalMatrix( test ); mockup.near( test, Matrix.mult( translate, invRotation, Matrix.create() ), 'Should expect Translation * invRotation' ); camera.setReferenceFrame( TransformEnums.ABSOLUTE_RF ); Matrix.copy( translate, test ); camera.computeLocalToWorldMatrix( test ); mockup.near( test, rotation, 'Should expect Rotation' ); Matrix.copy( translate, test ); camera.computeWorldToLocalMatrix( test ); mockup.near( test, invRotation, 'Should expect invRotation' ); } ); }; } ); 0 const CurveBTCPlus = artifacts.require("CurveBTCPlus"); const ERC20Proxy = artifacts.require("ERC20Proxy"); const CURVE_BTC_PLUS = '0xDe79d36aB6D2489dd36729A657a25f299Cb2Fbca'; module.exports = async function (callback) { try { const accounts = await web3.eth.getAccounts(); console.log('Upgrading curveBTC+...'); const curveBTCPlusImpl = await CurveBTCPlus.new(); const curveBTCPlusProxy = await ERC20Proxy.at(CURVE_BTC_PLUS); await curveBTCPlusProxy.upgradeTo(curveBTCPlusImpl.address, {from: accounts[1]}); console.log(`Proxy admin: ${accounts[1]}`); console.log(`curveBTC+: ${curveBTCPlusProxy.address}`); console.log(`curveBTC+ implementation: ${curveBTCPlusImpl.address}`); callback(); } catch (e) { callback(e); } }/** * @module 1-liners/by * * @description * * Same as `a / b` * * @example * * const by = require('1-liners/by'); * * by(6, 2); // => 3 * */ export default (a, b) => a / b; require('./bootstrap'); require('./css'); prototypes/tablet/routes/story-2-get-story-idea-metrics-single-panel-persona.route.js // dependencies var express = require("express"); var router = express.Router(); // express middleware var pg = require("pg"); // postgres connector var config = require("./config"); var conString = config.connectionString; /*******************************/ /************* GET *************/ /*******************************/ // all story idea metrics for a single story in a single panel for a single persona router.get(config.story.storyIdeaMetricsSinglePanelPersona.route, function(req, res) { var results = []; // get a postgres client from the connection pool pg.connect(conString, function(err, client, done) { var ideaID = req.params.idea; var controlID = req.params.control; var configQuery = config.story.storyIdeaMetricsSinglePanelPersona.query; // SQL query var query = client.query(configQuery[0] + ideaID + configQuery[1] + controlID + configQuery[2]); // stream results back one row at a time query.on("row", function(row) { results.push(row); }); // close connection and return results query.on("end", function() { client.end(); return res.json(results); }); // handle errors if(err) { console.log(err); }; }); }) module.exports = router;10-100 import { theme } from "@chakra-ui/core"; const customTheme = { ...theme, colors: { ...theme.colors, brand: { 400: "#ff8fb4", 500: "#ff6699", 600: "#e65c8a" } } }; export default customTheme; Coffeekraken/coffeekraken import __smoothScrollOnAnchorLinks from './smoothScrollOnAnchorLinks'; import __smoothScrollOnPageLoad from './smoothScrollOnPageLoad'; import __smoothScrollOnHashChange from './smoothScrollOnHashChange'; import __deepMerge from '../../shared/object/deepMerge'; function smoothScroll(settings = {}) { settings = __deepMerge({ scroll: {} }, settings); __smoothScrollOnPageLoad(settings); __smoothScrollOnAnchorLinks(settings); __smoothScrollOnHashChange(settings); } export default smoothScroll; //# sourceMappingURL=data:application/json;base64,import React from 'react'; const Recommendations = ({ data }) => { if (data) { var recommendations = data.recommendations.map(function (recommendations) { return
  • {recommendations.text}

    {recommendations.user}

  • }) } return (

    Recommendations

      {recommendations}
    ); } export default Recommendations; jesus-son-coder/projectSymfony2src/TechCorp/FrontBundle/Resources/public/js/manage-friends.js var manageFriend = function(friendId, route){ var url = Routing.generate(route, { 'friendId': friendId }); return $.post(url); } $('.add-friend').click(function() { var friendId = $(this).data('user-id'); manageFriend(friendId, 'tech_corp_front_user_add_friend'); $(this).addClass('disabled'); }); $('.remove-friend').click(function(){ var friendId = $(this).data('user-id'); manageFriend(friendId, 'tech_corp_front_user_remove_friend'); $(this).addClass('disabled'); });import {render} from './helpers/test-utils' test('it should work as expected', () => { const {queryByTestId} = render(` `) expect(queryByTestId('select')).toHaveDisplayValue('Select a fruit...') expect(queryByTestId('select')).not.toHaveDisplayValue('Banana') expect(() => expect(queryByTestId('select')).not.toHaveDisplayValue('Select a fruit...'), ).toThrow() expect(() => expect(queryByTestId('select')).toHaveDisplayValue('Ananas'), ).toThrow() queryByTestId('select').value = 'banana' expect(queryByTestId('select')).toHaveDisplayValue('Banana') expect(queryByTestId('select')).toHaveDisplayValue(/[bB]ana/) }) describe('with multiple select', () => { function mount() { return render(` `) } it('matches only when all the multiple selected values are equal to all the expected values', () => { const subject = mount() expect(subject.queryByTestId('select')).toHaveDisplayValue([ 'Ananas', 'Avocado', ]) expect(() => expect(subject.queryByTestId('select')).not.toHaveDisplayValue([ 'Ananas', 'Avocado', ]), ).toThrow() expect(subject.queryByTestId('select')).not.toHaveDisplayValue([ 'Ananas', 'Avocado', 'Orange', ]) expect(subject.queryByTestId('select')).not.toHaveDisplayValue('Ananas') expect(() => expect(subject.queryByTestId('select')).toHaveDisplayValue('Ananas'), ).toThrow() Array.from(subject.queryByTestId('select').options).forEach(option => { option.selected = ['ananas', 'banana'].includes(option.value) }) expect(subject.queryByTestId('select')).toHaveDisplayValue([ 'Ananas', 'Banana', ]) }) it('matches even when the expected values are unordered', () => { const subject = mount() expect(subject.queryByTestId('select')).toHaveDisplayValue([ 'Avocado', 'Ananas', ]) }) it('matches with regex expected values', () => { const subject = mount() expect(subject.queryByTestId('select')).toHaveDisplayValue([ /[Aa]nanas/, 'Avocado', ]) }) }) test('it should work with input elements', () => { const {queryByTestId} = render(` `) expect(queryByTestId('input')).toHaveDisplayValue('Luca') expect(queryByTestId('input')).toHaveDisplayValue(/Luc/) queryByTestId('input').value = 'Piero' expect(queryByTestId('input')).toHaveDisplayValue('Piero') }) test('it should work with textarea elements', () => { const {queryByTestId} = render( '', ) expect(queryByTestId('textarea-example')).toHaveDisplayValue( 'An example description here.', ) expect(queryByTestId('textarea-example')).toHaveDisplayValue(/example/) queryByTestId('textarea-example').value = 'Another example' expect(queryByTestId('textarea-example')).toHaveDisplayValue( 'Another example', ) }) test('it should throw if element is not valid', () => { const {queryByTestId} = render(`
    Banana
    `) let errorMessage try { expect(queryByTestId('div')).toHaveDisplayValue('Banana') } catch (err) { errorMessage = err.message } expect(errorMessage).toMatchInlineSnapshot( `".toHaveDisplayValue() currently supports only input, textarea or select elements, try with another matcher instead."`, ) try { expect(queryByTestId('radio')).toHaveDisplayValue('Something') } catch (err) { errorMessage = err.message } expect(errorMessage).toMatchInlineSnapshot( `".toHaveDisplayValue() currently does not support input[type=\\"radio\\"], try with another matcher instead."`, ) try { expect(queryByTestId('checkbox')).toHaveDisplayValue(true) } catch (err) { errorMessage = err.message } expect(errorMessage).toMatchInlineSnapshot( `".toHaveDisplayValue() currently does not support input[type=\\"checkbox\\"], try with another matcher instead."`, ) }) 'use strict'; const axios = require('axios'); function GetData (req,res) { const url = `https://www.thecocktaildb.com/api/json/v1/1/filter.php?a=Non_Alcoholic`; axios.get(url).then((response) => { res.send(response.data.drinks); }).catch((err) => { res.status(500).send(err.message); }) } module.exports = GetData; const { Model, DataTypes } = require('sequelize'); const sequelize = require('../config/connection'); class Pokemon extends Model {} Pokemon.init( { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true, }, name: { type: DataTypes.STRING, allowNull: false, }, move_1: { type: DataTypes.STRING, allowNull: false, }, move_2: { type: DataTypes.STRING, allowNull: false, }, move_1_damage: { type: DataTypes.INTEGER, allowNull: false, }, move_2_damage: { type: DataTypes.INTEGER, allowNull: false, }, front_default: { type: DataTypes.STRING, allowNull: false, }, back_default: { type: DataTypes.STRING, allowNull: false, }, health_points: { type: DataTypes.INTEGER, allowNull: false, }, type: { type: DataTypes.STRING, allowNull: false }, user_id: { type: DataTypes.INTEGER, references: { model: 'user', key: 'id', }, }, }, { sequelize, freezeTableName: true, underscored: true, modelName: 'pokemon', } ); module.exports = Pokemon;const path = require('path'); const paths = require('../../paths'); const paginate = require('simple-pagination'); const {mapTopics, convertTopicsToOrderedArray} = require('../topics'); const RESOURCES_PER_PAGE = 12; module.exports = ({ createPage, sections, resources }) => () => Object.keys(sections).forEach(sectionId => { const section = sections[sectionId]; const numPages = Math.ceil(resources.length / RESOURCES_PER_PAGE); Array.from({ length: numPages }).forEach((_, i) => { // The page 1 will be the site homepage createPage({ path: paths.getLastAddedPagePath({index: i + 1, sectionSlug: section.slug}), component: path.resolve(`src/templates/section/index.js`), context: { sectionSlug: section.slug, sectionName: section.name, limit: RESOURCES_PER_PAGE, skip: i * RESOURCES_PER_PAGE, resourcesCount: section.resourcesCount, topicsList: convertTopicsToOrderedArray(mapTopics(section.topics)), pagination: paginate(resources.length, RESOURCES_PER_PAGE, i + 1), }, }) }); }); /*jslint browser: true */ /*global jQuery */ (function ($) { 'use strict'; $(document).ready(function () { $('.element_toggler').on('click', function(ev) { $(this).classList.toggle('active'); if ($(this).next().is(':visible')) { $(this).next().hide(); } else { $(this).next().show(); } }); }); }(jQuery)); diegoablanco/almacenesclient/actions/messageBar.js export const SHOW_MESSAGE = 'SHOW_MESSAGE' export const HIDE_MESSAGE = 'HIDE_MESSAGE' export const ENTITY_CREATED = 'ENTITY_CREATED' export const ENTITY_UPDATED = 'ENTITY_UPDATED' export const ENTITY_DELETED = 'ENTITY_DELETED' const messageDuration = 4 * 1000 export function showMessage(text, messageType) { return { type: SHOW_MESSAGE, text, messageType } } export function hideMessage() { return { type: HIDE_MESSAGE } } export function showTimedMessage(text, messageType = 'success') { return (dispatch) => { dispatch(showMessage(text, messageType)) setTimeout(() => dispatch(hideMessage()), messageDuration) } } export function showLoadingMessage(text) { return showMessage(text, 'loading') } export function showErrorMessage(text) { return showMessage(text, 'error') } export function showSuccessMessage(text) { return showMessage(text, 'success') } export function entityCreatedMessage() { return showTimedMessage('Se creó correctamente') } export function entityUpdatedMessage() { return showTimedMessage('Se actualizó correctamente') } export function entityDeletedMessage() { return showTimedMessage('Se eliminó correctamente') } import { observable } from 'mobx'; import { faShareSquare, faCopy } from '@fortawesome/free-solid-svg-icons' const ClientStore = observable({ root_drive: [], client_list: [], currentClientIP: '', currentClientPath: '', getParentPath: function () { if (this.isRoot()) { return this.currentClientPath; } else { return this.currentClientPath.substring(0, this.currentClientPath.lastIndexOf("\\")); } }, isRoot: function () { return this.root_drive.includes(this.currentClientPath); }, currentDirectoriesList: [],//data clearClient: function () { this.currentClientIP = ''; this.currentClientPath = ''; this.currentDirectoriesList = []; this.clearSelectedData(); }, selectedIP: '', selectedPath: '', selectedIndex: 0, selectedType: '', selectedAction: '', clearSelectedData: function () { this.selectedIP = ''; this.selectedPath = ''; this.selectedType = ''; this.selectedIndex = 0; this.selectedAction = ''; }, copymoveDataJson: null, copymoveData: { path: '', fileName: '', ip: '', action: [{ label: "복사", icon: faCopy, act: 1, }, { label: "이동", icon: faShareSquare, act: 2, },] }, clearCopyMoveDatay: function () { this.copymoveData.path = '' this.copymoveData.fileName = '' this.copymoveData.ip = '' this.copymoveData.action = [{ label: "복사", icon: faShareSquare, act: 1, }, { label: "이동", icon: faCopy, act: 2, },] }, expanded: [], addExpanded: function (data) { const index = this.expanded.indexOf(data) if (index === 1) { this.expanded.push(data); } }, removeExpanded: function (data) { const index = this.expanded.indexOf(data) if (index !== -1) { this.expanded.splice(index, 1); } }, reset: function (data) { this.root_drive = []; this.client_list = []; this.currentClientIP = ''; this.currentClientPath = ''; this.currentDirectoriesList = [];//data this.selectedIP = ''; this.selectedPath = ''; this.selectedIndex = 0; this.selectedType = ''; this.selectedAction = ''; this.copymoveDataJson = null; this.expanded = []; this.progressVisible = false; }, progressVisible : false, }); // class ClientStore2 { // @observable client_list = []; // } export default ClientStore; 'use strict'; /** * Module dependencies. */ var each = require('@ndhoule/each'); var integration = require('@segment/analytics.js-integration'); var querystring = require('component-querystring'); var useHttps = require('use-https'); var toNoCase = require('to-no-case'); /** * Expose `AppNexus`. */ var AppNexus = module.exports = integration('AppNexus') .tag('http', ' )} ); } export default MetaData; ui/servers.js define([ "dojo/_base/declare", "aps/View", "aps/ResourceStore" ], function ( declare, View, Store ) { return declare(View, { init: function () { /* Define the data store */ var vpsStore = new Store({ apsType: "http://for93t.github.com/aps2-boilerplate/vps/1.0", target: "/aps/2/resources/" }); /* Define a handler for the *New* button click */ var add = function () { /* Start the process of creating a VPS by going to the relevant view */ aps.apsc.gotoView("server-new"); }; /* Define and return widgets */ return ["aps/Grid", { id: this.genId("srv_grid"), store: vpsStore, columns: [{ field: "name", name: "Name" }, { field: "os", name: "Operating System" } ] }, [ ["aps/Toolbar", [ ["aps/ToolbarButton", { id: this.genId("srv_new"), iconClass: "fa-plus", type: "primary", label: "New", onClick: add }] ]] ]]; }, // End of Init onContext: function () { this.byId("srv_grid").refresh(); aps.apsc.hideLoading(); }, onHide: function () { this.byId("srv_new").cancel(); } }); }); routes/index.js const express = require('express') const router = express.Router() const app = express() const pkg = require('../package.json') const CDN = require('./modules/cdn') var ENV = app.get('env') router.get('/', (req, res, next) => { res.render('index', { title: pkg.name, version: pkg.version, ENV, CDN }) }) module.exports = router 移动端商城/wechat-weapp-mall-master/pages/details/index.js var app = getApp() Page({ data: { indicatorDots: true, vertical: false, autoplay: true, interval: 3000, duration: 1200, }, onLoad: function(options) { var that = this // 商品详情 wx.request({ url: 'http://huanqiuxiaozhen.com/wemall/goods/inqgoods?id=' + options.id, method: 'GET', data: {}, header: { 'Accept': 'application/json' }, success: function(res) { //console.log(res.data.data); that.data.shopppingDetails = res.data.data; var goodsPicsInfo = []; var goodsPicsObj = {}; var goodspic = res.data.data.goodspics; var goodspics = goodspic.substring(0, goodspic.length - 1); var goodspicsArr = goodspics.split("#"); for (var i = 0; i < goodspicsArr.length; i++) { goodsPicsInfo.push({ "picurl": goodspicsArr[i] }); } that.setData({ goodsPicsInfo: goodsPicsInfo }) } }) } }) mavarona/chronometer-mavl "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const constants_1 = require("./constants"); /** * Convert the seconds in format HH:MM:SS * @param sc seconds of the moment * @param type 1: counter / 2: discounter * @param limit value to stop the count */ function convertSecondToDiplay(sc, type, limit) { if (type === 1 && limit === sc || type === 2 && sc === 0) { return 'FINISH'; } const hours = Math.floor((sc % constants_1.Chrono.SC_DAY) / constants_1.Chrono.SC_HOUR); const minutes = Math.floor((sc % constants_1.Chrono.SC_HOUR) / constants_1.Chrono.SC_MIN); const seconds = Math.floor(sc % constants_1.Chrono.SC_MIN); return formatToDisplay(hours, minutes, seconds); } exports.convertSecondToDiplay = convertSecondToDiplay; /** * @ignore */ function formatToDisplay(hours, minutes, seconds) { const h = formatInTwoCharacters(hours); const m = formatInTwoCharacters(minutes); const s = formatInTwoCharacters(seconds); return `${h}:${m}:${s}`; } /** * @ignore */ function formatInTwoCharacters(num) { return (num < 10) ? '0'.concat(String(num)) : String(num); } var mod = {}; module.exports = mod; mod.loop = function() { const flags = _.filter(Game.flags, o => FlagUtil.spawning.examine(o)); for(const flag of flags) { const room = flag.room; if(room) { //We do have vision this.queueCreeps(room); } else { //No vision // but this flag should only place in base room! Logger.warning(`Found spawning(base) flag[${flag.name}] in no-vision room[${flag.roomName}]!`); } } }; //Filler mod.queueCreeps = function(room) { //=== Role count === const cnt = room.cachedRoleCount(); if(room.storage) { //We still have energy in storage // Do we have a filler to transfer energy from storage to spawns/extensions? if(cnt.total[C.FILLER]<2) { if(cnt.existed[C.FILLER] > 1 && room.storage.store[RESOURCE_ENERGY] > 5000) { room.queue.normal.unshift(C.FILLER); } else { //So this is kind of emergence room.queue.urgent.unshift(C.FILLER); } cnt.queue[C.FILLER]++; cnt.total[C.FILLER]++; } } else { //No storage, then it is low rcl room, task.mining will take // care of spawning too } }; import React from 'react'; import Title from '../Title'; export default function Contact() { return (
    <form className="mt-5" action="https://formspree.io/jsebastiansalazaro@gmail.com" method="POST"> <div className="form-group"> <input type="text" name="firstName" className="form-control" placeholder="<NAME>" /> </div> <div className="form-group"> <input type="email" name="email" className="form-control" placeholder="Email" /> </div> <div className="form-group"> <input type="text" name="subject" className="form-control" placeholder="Subject" /> </div> <div className="form"> <textarea name="message" className="form-control" rows="10" placeholder="Message here" /> </div> <div className="form-group mt-3"> <input type="submit" className="form-control bg-primary text-white" value="Send" /> </div> </form> </div> </div> </section> ) } 'use strict'; const Command = require('../structures/Command'); //Kills the bot, just in case it's acting up ;) module.exports = function command(requires) { return new Command({ name: 'Kill', inline: true, alias: ['ki'], blurb: 'Kills the bot', longDescription: 'Sometimes you just gotta do it ┐(´д`)┌', usages: ['`%prefixkill`'], permission: 'private', action: function(details) { requires.bObj.kill(); } }, requires); }; var xhr, xmlDocumentConstructor; module("responding", { setup: function(){ xhr = new FakeXMLHttpRequest(); xmlDocumentConstructor = makeXMLDocument().constructor; }, teardown: function(){ xhr = undefined; xmlDocumentConstructor = undefined; } }); // Different browsers report different constructors for XML Documents. // Chrome 45.0.2454 and Firefox 40.0.0 report `XMLDocument`, // PhantomJS 1.9.8 reports `Document`. // Make a dummy xml document to determine what constructor to // compare against in the tests below. // This function is taken from `parseXML` in the src/ function makeXMLDocument() { var xmlDoc, text = "<some>xml</some>"; if (typeof DOMParser != "undefined") { var parser = new DOMParser(); xmlDoc = parser.parseFromString(text, "text/xml"); } else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(text); } return xmlDoc; } test("defaults responseHeaders to {} if not passed", function(){ xhr.respond(200); deepEqual(xhr.responseHeaders, {}); }); test("sets responseHeaders", function(){ xhr.respond(200, {"Content-Type":"application/json"}); deepEqual(xhr.responseHeaders, {"Content-Type":"application/json"}); }); test("sets body", function(){ xhr.respond(200, {"Content-Type":"application/json"}, JSON.stringify({a: 'key'})); equal(xhr.responseText, '{"a":"key"}'); }); test("parses the body if it's XML and no content-type is set", function(){ xhr.respond(200, {}, "<key>value</key>"); equal(xhr.responseXML.constructor, xmlDocumentConstructor); }); test("parses the body if it's XML and xml content type is set", function(){ xhr.respond(200, {'Content-Type':'application/xml'}, "<key>value</key>"); equal(xhr.responseXML.constructor, xmlDocumentConstructor); }); test("does not parse the body if it's XML and another content type is set", function(){ xhr.respond(200, {'Content-Type':'application/json'}, "<key>value</key>"); equal(xhr.responseXML, undefined); }); test("calls the onload callback once", function(){ var wasCalled = 0; xhr.onload = function(ev){ wasCalled += 1; }; xhr.respond(200, {}, ""); strictEqual(wasCalled, 1); }); var dir_5ce4861fcab418defdb36351d556c9c8 = [ [ "FHOAuthIntent.cs", "_f_h_o_auth_intent_8cs.html", [ [ "FHOAuthIntent", "class_f_h_s_d_k_1_1_services_1_1_f_h_o_auth_intent.html", "class_f_h_s_d_k_1_1_services_1_1_f_h_o_auth_intent" ] ] ], [ "FHOAuthWebview.cs", "_f_h_o_auth_webview_8cs.html", [ [ "FHOAuthWebview", "class_f_h_s_d_k_1_1_services_1_1_f_h_o_auth_webview.html", "class_f_h_s_d_k_1_1_services_1_1_f_h_o_auth_webview" ] ] ], [ "OAuthClientHandlerService.cs", "_f_h_xamarin_android_s_d_k_2_services_2_auth_2_o_auth_client_handler_service_8cs.html", [ [ "OAuthClientHandlerService", "class_f_h_s_d_k_1_1_services_1_1_o_auth_client_handler_service.html", "class_f_h_s_d_k_1_1_services_1_1_o_auth_client_handler_service" ] ] ] ];<filename>src/middlewares/schema/user.schema.js const joi = require('joi'); const userIdSchema = joi.string().regex(/^[0-9a-fA]{24}$/); const nameSchema = joi.string().min(3).max(80); const userNameSchema = joi.string().min(3).max(80); const emailSchema = joi.string().email({ minDomainSegments: 2, tlds: { allow: ['com'], }, }); const companySchema = joi .object({ name: joi.string().min(5).max(80), position: joi.string().min(5).max(80), }) .length(2); const createUserSchema = { name: nameSchema.required(), username: userNameSchema.required(), email: emailSchema.required(), company: companySchema.required(), }; const updateUserSchema = { name: nameSchema, username: userNameSchema, email: emailSchema, company: companySchema, }; module.exports = { createUserSchema, userIdSchema, updateUserSchema, }; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Icon } from '@ohif/ui'; import { UIModalService, UINotificationService } from '@ohif/core'; import cornerstone from 'cornerstone-core'; import cornerstoneTools from 'cornerstone-tools'; import './SegmentationList.styl'; import { createSegment, deleteSegment, flattenLabelmaps, getLabelMaps, getSegmentInfo, updateSegment, updateSegmentMeta, } from '../utils/SegmentationUtils'; import SegmentationLabelForm from './SegmentationLabelForm'; import { hexToRgb, randomName, randomRGB, rgbToHex, getLabelColor, } from '../utils/GenericUtils'; import SegmentationReader from '../utils/SegmentationReader'; const ColoredCircle = ({ color }) => { return ( <span className="segColor" style={{ backgroundColor: `rgba(${color.join(',')})` }} /> ); }; ColoredCircle.propTypes = { color: PropTypes.array.isRequired, }; export default class SegmentationList extends Component { static propTypes = { viewConstants: PropTypes.any, onSegmentCreated: PropTypes.func, onSegmentUpdated: PropTypes.func, onSegmentDeleted: PropTypes.func, onSegmentSelected: PropTypes.func, }; constructor(props) { super(props); this.notification = UINotificationService.create({}); this.uiModelService = UIModalService.create({}); const { element } = this.props.viewConstants; const labelmaps = getLabelMaps(element); const segments = flattenLabelmaps(labelmaps); this.state = { element: element, segments: segments, selectedSegmentId: segments && segments.length ? segments[0].id : null, header: null, }; } getSelectedActiveIndex = () => { const id = this.state.selectedSegmentId; if (id) { let index = id.split('+').map(Number); return { id, labelmapIndex: index[0], segmentIndex: index[1] }; } return null; }; onAddSegment = (name, description, color) => { this.uiModelService.hide(); const { element } = this.props.viewConstants; const { id } = createSegment(element, name, description, hexToRgb(color)); this.refreshSegTable(id); if (this.props.onSegmentCreated) { this.props.onSegmentCreated(id); } }; onUpdateSegment = (name, description, color) => { this.uiModelService.hide(); const { element } = this.props.viewConstants; const activeIndex = this.getSelectedActiveIndex(); updateSegmentMeta( element, activeIndex.labelmapIndex, activeIndex.segmentIndex, name, description, hexToRgb(color) ); this.refreshSegTable(activeIndex.id); if (this.props.onSegmentUpdated) { this.props.onSegmentUpdated(activeIndex.id); } }; onSelectSegment = evt => { let id = evt.currentTarget.value; this.setState({ selectedSegmentId: id }); }; onClickAddSegment = () => { this.uiModelService.show({ content: SegmentationLabelForm, title: 'Add New Label', contentProps: { name: randomName(), description: '', color: randomRGB(), onSubmit: this.onAddSegment, }, customClassName: 'segmentationLabelForm', shouldCloseOnEsc: true, }); }; onClickEditSegment = () => { const { element } = this.props.viewConstants; const activeIndex = this.getSelectedActiveIndex(); const { name, description, color } = getSegmentInfo( element, activeIndex.labelmapIndex, activeIndex.segmentIndex ); this.uiModelService.show({ content: SegmentationLabelForm, title: 'Edit Label', contentProps: { name: name, description: description, color: rgbToHex( Math.floor(color[0]), Math.floor(color[1]), Math.floor(color[2]) ), onSubmit: this.onUpdateSegment, }, customClassName: 'segmentationLabelForm', shouldCloseOnEsc: true, }); }; onUpdateLabelOrDesc = (id, evt, label) => { const { element } = this.props.viewConstants; let index = id.split('+').map(Number); const labelmapIndex = index[0]; const segmentIndex = index[1]; updateSegmentMeta( element, labelmapIndex, segmentIndex, label ? evt.currentTarget.textContent : undefined, label ? undefined : evt.currentTarget.textContent ); }; onClickDeleteSegment = () => { const { element } = this.props.viewConstants; const activeIndex = this.getSelectedActiveIndex(); deleteSegment(element, activeIndex.labelmapIndex, activeIndex.segmentIndex); this.refreshSegTable(null); if (this.props.onSegmentDeleted) { this.props.onSegmentDeleted(activeIndex.id); } }; onClickExportSegments = () => { const { getters } = cornerstoneTools.getModule('segmentation'); const { labelmaps3D } = getters.labelmaps3D( this.props.viewConstants.element ); if (!labelmaps3D) { console.info('LabelMap3D is empty.. so zero segments'); return; } this.notification.show({ title: 'MONAI Label', message: 'Preparing the labelmap to download as .nrrd', type: 'info', duration: 5000, }); for (let i = 0; i < labelmaps3D.length; i++) { const labelmap3D = labelmaps3D[i]; if (!labelmap3D) { console.warn('Missing Label; so ignore'); continue; } const metadata = labelmap3D.metadata.data ? labelmap3D.metadata.data : labelmap3D.metadata; if (!metadata || !metadata.length) { console.warn('Missing Meta; so ignore'); continue; } SegmentationReader.serializeNrrdCompressed( this.state.header, labelmap3D.buffer, 'segment-' + i + '.nrrd' ); } }; refreshSegTable = id => { const { element } = this.props.viewConstants; const labelmaps = getLabelMaps(element); const segments = flattenLabelmaps(labelmaps); if (!segments.length) { id = undefined; } else if (!id) { id = segments[segments.length - 1].id; } if (id) { this.setState({ segments: segments, selectedSegmentId: id }); } else { this.setState({ segments: segments }); } }; setActiveSegment = () => { const { element } = this.props.viewConstants; const activeIndex = this.getSelectedActiveIndex(); const { setters } = cornerstoneTools.getModule('segmentation'); const { labelmapIndex, segmentIndex } = activeIndex; setters.activeLabelmapIndex(element, labelmapIndex); setters.activeSegmentIndex(element, segmentIndex); // Refresh cornerstone.updateImage(element); if (this.props.onSegmentSelected) { this.props.onSegmentSelected(activeIndex.id); } }; updateView = async (response, labels, operation, slice, overlap) => { const { element, numberOfFrames } = this.props.viewConstants; let activeIndex = this.getSelectedActiveIndex(); const { header, image } = SegmentationReader.parseNrrdData(response.data); this.setState({ header: header }); if (labels) { for (let i = 0; i < labels.length; i++) { const resp = createSegment( element, labels[i], '', getLabelColor(labels[i]), i === 0 ? !overlap : false ); if (i === 0) { activeIndex = resp; } if (this.state.selectedSegmentId) { this.refreshSegTable(); } else { this.refreshSegTable(activeIndex.id); } } } if (!operation && overlap) { operation = 'overlap'; } updateSegment( element, activeIndex.labelmapIndex, activeIndex.segmentIndex, image, numberOfFrames, operation, slice ); }; componentDidUpdate(prevProps, prevState, snapshot) { if (prevState.selectedSegmentId !== this.state.selectedSegmentId) { if (this.state.selectedSegmentId) { this.setActiveSegment(); } } } render() { return ( <div className="segmentationList"> <table width="100%"> <tbody> <tr> <td> <button className="segButton" onClick={this.onClickAddSegment} title="Add Segment" > <Icon name="plus" width="12px" height="12px" /> </button>   <button className="segButton" onClick={this.onClickEditSegment} title="Edit Selected Segment" disabled={!this.state.selectedSegmentId} > <Icon name="edit" width="12px" height="12px" /> </button>   <button className="segButton" onClick={this.onClickDeleteSegment} title="Delete Selected Segment" disabled={!this.state.selectedSegmentId} > <Icon name="trash" width="12px" height="12px" /> </button> </td> <td align="right"> <button className="segButton" onClick={this.onClickExportSegments} title={'Download Segments'} disabled={!this.state.header} > <Icon name="save" width="12px" height="12px" /> </button> </td> </tr> </tbody> </table> <div className="segSection"> <table className="segTable"> <thead> <tr> <th width="2%">#</th> <th width="8%">Color</th> <th width="60%">Name</th> <th width="30%">Desc</th> </tr> </thead> <tbody> {this.state.segments.map(seg => ( <tr key={seg.id}> <td> <input type="radio" name="segitem" value={seg.id} checked={seg.id === this.state.selectedSegmentId} onChange={this.onSelectSegment} /> </td> <td> <ColoredCircle color={seg.color} /> </td> <td className="segEdit" contentEditable="true" suppressContentEditableWarning="true" onKeyUp={evt => this.onUpdateLabelOrDesc(seg.id, evt, true)} > {seg.meta.SegmentLabel} </td> <td contentEditable="true" suppressContentEditableWarning="true" onKeyUp={evt => this.onUpdateLabelOrDesc(seg.id, evt, false) } > {seg.meta.SegmentDescription} </td> </tr> ))} </tbody> </table> </div> </div> ); } } <gh_stars>0 import { useSelector } from 'react-redux'; import { getShowData, getShowLoadingState } from 'store/show/selectors'; import { ShowOrganism } from 'organisms/show'; import { BaseTemplate } from 'templates/base'; function ShowPage() { const showData = useSelector(getShowData); const isShowLoading = useSelector(getShowLoadingState); return ( <BaseTemplate pageTitle={showData?.name} isLoading={isShowLoading} > <ShowOrganism /> </BaseTemplate> ); } export default ShowPage; <gh_stars>1-10 /* Copyright 2020 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ import '../_version.js'; /** * A plugin, designed to be used with PrecacheController, to translate URLs into * the corresponding cache key, based on the current revision info. * * @private */ class PrecacheCacheKeyPlugin { constructor({ precacheController }) { this.cacheKeyWillBeUsed = async ({ request, params, }) => { const cacheKey = params && params.cacheKey || this._precacheController.getCacheKeyForURL(request.url); return cacheKey ? new Request(cacheKey) : request; }; this._precacheController = precacheController; } } export { PrecacheCacheKeyPlugin }; <reponame>chhiring90/tama const axios = require('axios'); const catchAsync = require('./catchAsync'); const tenorGif = catchAsync(async (query, options) => { const { TENOR_URL, TENOR_TOKEN } = process.env; let tenor = TENOR_URL.replace('<KEY>', TENOR_TOKEN); if (options && options.gifType) { tenor = tenor.replace('<QUERY>', `${options.gifType} ${query}`); } tenor = tenor.replace('<QUERY>', `${query}`); const response = await axios.get(tenor); const { results } = response.data; const gif = results[Math.floor(Math.random() * results.length)].url; return gif; }); module.exports = tenorGif;<filename>preload.js<gh_stars>0 window.addEventListener('DOMContentLoaded', () => { for (const type of ['chrome', 'node', 'electron']) { //replaceText(`${type}-version`, process.versions[type]) } })import React, { useEffect } from "react" import { injectIntl } from "react-intl" import { shallowEqual, useDispatch, useSelector } from "react-redux" import familyMemberFields from "./fields/familyMemberFields" import { fetchFamilyMembers } from "../../store/actions" import { DataTable } from "../../../../../../../../components/partials/controls" import { useFamilyMembersUIContext } from "../../context/FamilyMembersUIContext" const FamilyMemberTable = ({ intl, folderParam }) => { // FamilyMembers UI Context const familyMembersUIProps = useFamilyMembersUIContext() const columns = familyMemberFields({ intl, familyMembersUIProps }) // Getting curret state of familyMembers list from store (Redux) const { totalSize, familyMembers: entities = [], isFetching } = useSelector( (state) => ({ ...state.admin.familyMember }), shallowEqual ) // FamilyMembers Redux state const dispatch = useDispatch() useEffect(() => { // clear selections list familyMembersUIProps.setIds([]) // server call by queryParams dispatch(fetchFamilyMembers({ ...(familyMembersUIProps.queryParams || {}), param: folderParam })) // eslint-disable-next-line react-hooks/exhaustive-deps }, [familyMembersUIProps.queryParams, dispatch]) return ( <DataTable isFetching={isFetching} entities={entities} columns={columns} totalSize={totalSize} queryParams={familyMembersUIProps.queryParams} onQueryParamsChange={familyMembersUIProps.setQueryParams} /> ) } //ids={familyMembersUIProps.ids} //setIds={familyMembersUIProps.setIds} export default injectIntl(FamilyMemberTable) <filename>_nuxt/72293ffca3357152974b.js (window.webpackJsonp=window.webpackJsonp||[]).push([[8],{643:function(n,e,o){var content=o(644); "string"==typeof content&&(content=[[n.i,content,""]]),content.locals&&(n.exports=content.locals); (0,o(44).default)("797461a0",content,!0,{sourceMap:!1})},644:function(n,e,o){(n.exports=o(43)(!1)).push([n.i,'/*! Buefy v0.8.3 | MIT License | github.com/buefy/buefy */\n\n@keyframes fadeOut {\n from {\n opacity: 1; \n }\n to {\n opacity: 0; \n }\n}\n\n@keyframes fadeOutDown {\n from {\n opacity: 1; \n }\n to {\n opacity: 0; \n transform: translate3d(0, 100%, 0); \n }\n}\n\n@keyframes fadeOutUp {\n from {\n opacity: 1; \n }\n to {\n opacity: 0; \n transform: translate3d(0, -100%, 0); \n }\n}\n\n@keyframes fadeIn {\n from {\n opacity: 0; \n }\n to {\n opacity: 1; \n }\n}\n\n@keyframes fadeInDown {\n from {\n opacity: 0; \n transform: translate3d(0, -100%, 0); \n }\n to {\n opacity: 1; \n transform: none; \n }\n}\n\n@keyframes fadeInUp {\n from {\n opacity: 0; \n transform: translate3d(0, 100%, 0); \n }\n to {\n opacity: 1; \n transform: none; \n }\n}\n\n/**\r\n * Vue Transitions\r\n */\n\n\n.slide-prev-enter-active,\n.slide-prev-leave-active {\n transition: transform 250ms cubic-bezier(0.785, 0.135, 0.15, 0.86); \n}\n\n.slide-prev-leave-to {\n transform: translate3d(-100%, 0, 0); \n position: absolute; \n width: 100%; \n}\n\n.slide-prev-enter {\n transform: translate3d(100%, 0, 0); \n position: absolute; \n width: 100%; \n}\n\n/*! bulma.io v0.7.5 | MIT License | github.com/jgthms/bulma */\n@keyframes spinAround {\n from {\n transform: rotate(0deg); \n }\n to {\n transform: rotate(359deg); \n }\n}\n\n.delete, .modal-close, .is-unselectable, .button, .pagination-previous {\n -webkit-touch-callout: none; \n -webkit-user-select: none; \n -moz-user-select: none; \n -ms-user-select: none; \n user-select: none; \n}\n\n.select:not(.is-multiple):not(.is-loading)::after {\n border: 3px solid transparent; \n border-radius: 2px; \n border-right: 0; \n border-top: 0; \n content: " "; \n display: block; \n height: 0.625em; \n margin-top: -0.4375em; \n pointer-events: none; \n position: absolute; \n top: 50%; \n transform: rotate(-45deg); \n transform-origin: center; \n width: 0.625em; \n}\n\n .content:not(:last-child), .notification:not(:last-child), .progress:not(:last-child), .table:not(:last-child), .title:not(:last-child),\n.subtitle:not(:last-child), .block:not(:last-child), .level:not(:last-child), .list:not(:last-child), .message:not(:last-child) {\n margin-bottom: 1.5rem; \n}\n\n.delete, .modal-close {\n -moz-appearance: none; \n -webkit-appearance: none; \n background-color: rgba(10, 10, 10, 0.2); \n border: none; \n border-radius: 290486px; \n cursor: pointer; \n pointer-events: auto; \n display: inline-block; \n flex-grow: 0; \n flex-shrink: 0; \n font-size: 0; \n height: 20px; \n max-height: 20px; \n max-width: 20px; \n min-height: 20px; \n min-width: 20px; \n outline: none; \n position: relative; \n vertical-align: top; \n width: 20px; \n}\n\n.delete::before, .modal-close::before, .delete::after, .modal-close::after {\n background-color: white; \n content: ""; \n display: block; \n left: 50%; \n position: absolute; \n top: 50%; \n transform: translateX(-50%) translateY(-50%) rotate(45deg); \n transform-origin: center center; \n}\n\n.delete::before, .modal-close::before {\n height: 2px; \n width: 50%; \n}\n\n.delete::after, .modal-close::after {\n height: 50%; \n width: 2px; \n}\n\n.delete:hover, .modal-close:hover, .delete:focus, .modal-close:focus {\n background-color: rgba(10, 10, 10, 0.3); \n}\n\n.delete:active, .modal-close:active {\n background-color: rgba(10, 10, 10, 0.4); \n}\n\n.is-small.delete, .is-small.modal-close {\n height: 16px; \n max-height: 16px; \n max-width: 16px; \n min-height: 16px; \n min-width: 16px; \n width: 16px; \n}\n\n.is-medium.delete, .is-medium.modal-close {\n height: 24px; \n max-height: 24px; \n max-width: 24px; \n min-height: 24px; \n min-width: 24px; \n width: 24px; \n}\n\n.button.is-loading::after, .select.is-loading::after, .control.is-loading::after {\n animation: spinAround 500ms infinite linear; \n border: 2px solid #dbdbdb; \n border-radius: 290486px; \n border-right-color: transparent; \n border-top-color: transparent; \n content: ""; \n display: block; \n height: 1em; \n position: relative; \n width: 1em; \n}\n\n .modal, .modal-background {\n bottom: 0; \n left: 0; \n position: absolute; \n right: 0; \n top: 0; \n}\n\n.button, .input, .textarea, .select select, .pagination-previous {\n -moz-appearance: none; \n -webkit-appearance: none; \n align-items: center; \n border: 1px solid transparent; \n border-radius: 4px; \n box-shadow: none; \n display: inline-flex; \n font-size: 1rem; \n height: 2.25em; \n justify-content: flex-start; \n line-height: 1.5; \n padding-bottom: calc(0.375em - 1px); \n padding-left: calc(0.625em - 1px); \n padding-right: calc(0.625em - 1px); \n padding-top: calc(0.375em - 1px); \n position: relative; \n vertical-align: top; \n}\n\n.button:focus, .input:focus, .textarea:focus, .select select:focus, .pagination-previous:focus, .is-focused.button, .is-focused.input, .is-focused.textarea, .select select.is-focused, .is-focused.pagination-previous, .button:active, .input:active, .textarea:active, .select select:active, .pagination-previous:active, .is-active.button, .is-active.input, .is-active.textarea, .select select.is-active, .is-active.pagination-previous {\n outline: none; \n}\n\n.button[disabled], .input[disabled], .textarea[disabled], .select select[disabled], .pagination-previous[disabled],\n.select fieldset[disabled] select {\n cursor: not-allowed; \n}\n\n/*! minireset.css v0.0.4 | MIT License | github.com/jgthms/minireset.css */\nhtml,\nbody,\np,\nul,\nli,\ntextarea,\npre,\niframe,\nhr,\nh1 {\n margin: 0; \n padding: 0; \n}\n\nh1 {\n font-size: 100%; \n font-weight: normal; \n}\n\nul {\n list-style: none; \n}\n\nbutton,\ninput,\nselect,\ntextarea {\n margin: 0; \n}\n\nhtml {\n box-sizing: border-box; \n}\n\n*, *::before, *::after {\n box-sizing: inherit; \n}\n\nimg,\nembed,\niframe {\n height: auto; \n max-width: 100%; \n}\n\niframe {\n border: 0; \n}\n\ntable {\n border-collapse: collapse; \n border-spacing: 0; \n}\n\ntd {\n padding: 0; \n}\n\ntd:not([align]) {\n text-align: left; \n}\n\nhtml {\n background-color: white; \n font-size: 16px; \n -moz-osx-font-smoothing: grayscale; \n -webkit-font-smoothing: antialiased; \n min-width: 300px; \n overflow-x: hidden; \n overflow-y: scroll; \n text-rendering: optimizeLegibility; \n text-size-adjust: 100%; \n}\n\narticle,\nfooter,\nheader,\nsection {\n display: block; \n}\n\nbody,\nbutton,\ninput,\nselect,\ntextarea {\n font-family: BlinkMacSystemFont, -apple-system, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "Helvetica", "Arial", sans-serif; \n}\n\ncode,\npre {\n -moz-osx-font-smoothing: auto; \n -webkit-font-smoothing: auto; \n font-family: monospace; \n}\n\nbody {\n color: #4a4a4a; \n font-size: 1em; \n font-weight: 400; \n line-height: 1.5; \n}\n\na {\n color: #7957d5; \n cursor: pointer; \n text-decoration: none; \n}\n\na strong {\n color: currentColor; \n}\n\na:hover {\n color: #363636; \n}\n\ncode {\n background-color: whitesmoke; \n color: #ff3860; \n font-size: 0.875em; \n font-weight: normal; \n padding: 0.25em 0.5em 0.25em; \n}\n\nhr {\n background-color: whitesmoke; \n border: none; \n display: block; \n height: 2px; \n margin: 1.5rem 0; \n}\n\nimg {\n height: auto; \n max-width: 100%; \n}\n\ninput[type="checkbox"],\ninput[type="radio"] {\n vertical-align: baseline; \n}\n\nspan {\n font-style: inherit; \n font-weight: inherit; \n}\n\nstrong {\n color: #363636; \n font-weight: 700; \n}\n\npre {\n -webkit-overflow-scrolling: touch; \n background-color: whitesmoke; \n color: #4a4a4a; \n font-size: 0.875em; \n overflow-x: auto; \n padding: 1.25rem 1.5rem; \n white-space: pre; \n word-wrap: normal; \n}\n\npre code {\n background-color: transparent; \n color: currentColor; \n font-size: 1em; \n padding: 0; \n}\n\ntable td {\n vertical-align: top; \n}\n\ntable td:not([align]) {\n text-align: left; \n}\n\n.is-size-4 {\n font-size: 1.5rem !important; \n}\n\n.is-size-7 {\n font-size: 0.75rem !important; \n}\n\n.has-text-centered {\n text-align: center !important; \n}\n\n.is-italic {\n font-style: italic !important; \n}\n\n.has-text-link {\n color: #7957d5 !important; \n}\n\na.has-text-link:hover, a.has-text-link:focus {\n color: #5a32c7 !important; \n}\n\n.has-text-info {\n color: #167df0 !important; \n}\n\na.has-text-info:hover, a.has-text-info:focus {\n color: #0d64c6 !important; \n}\n\n.has-background-info {\n background-color: #167df0 !important; \n}\n\n.has-text-success {\n color: #23d160 !important; \n}\n\na.has-text-success:hover, a.has-text-success:focus {\n color: #1ca64c !important; \n}\n\n.has-background-success {\n background-color: #23d160 !important; \n}\n\n.has-text-warning {\n color: #ffdd57 !important; \n}\n\na.has-text-warning:hover, a.has-text-warning:focus {\n color: #ffd324 !important; \n}\n\n.has-background-warning {\n background-color: #ffdd57 !important; \n}\n\n.has-text-danger {\n color: #ff3860 !important; \n}\n\na.has-text-danger:hover, a.has-text-danger:focus {\n color: #ff0537 !important; \n}\n\n.has-background-danger {\n background-color: #ff3860 !important; \n}\n\n.button {\n background-color: white; \n border-color: #dbdbdb; \n border-width: 1px; \n color: #363636; \n cursor: pointer; \n justify-content: center; \n padding-bottom: calc(0.375em - 1px); \n padding-left: 0.75em; \n padding-right: 0.75em; \n padding-top: calc(0.375em - 1px); \n text-align: center; \n white-space: nowrap; \n}\n\n.button strong {\n color: inherit; \n}\n\n.button .icon, .button .icon.is-small, .button .icon.is-medium {\n height: 1.5em; \n width: 1.5em; \n}\n\n.button .icon:first-child:not(:last-child) {\n margin-left: calc(-0.375em - 1px); \n margin-right: 0.1875em; \n}\n\n.button .icon:last-child:not(:first-child) {\n margin-left: 0.1875em; \n margin-right: calc(-0.375em - 1px); \n}\n\n.button .icon:first-child:last-child {\n margin-left: calc(-0.375em - 1px); \n margin-right: calc(-0.375em - 1px); \n}\n\n.button:hover {\n border-color: #b5b5b5; \n color: #363636; \n}\n\n.button:focus, .button.is-focused {\n border-color: #7957d5; \n color: #363636; \n}\n\n.button:focus:not(:active), .button.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(121, 87, 213, 0.25); \n}\n\n.button:active, .button.is-active {\n border-color: #4a4a4a; \n color: #363636; \n}\n\n.button.is-text {\n background-color: transparent; \n border-color: transparent; \n color: #4a4a4a; \n text-decoration: underline; \n}\n\n.button.is-text:hover, .button.is-text:focus, .button.is-text.is-focused {\n background-color: whitesmoke; \n color: #363636; \n}\n\n.button.is-text:active, .button.is-text.is-active {\n background-color: #e8e8e8; \n color: #363636; \n}\n\n.button.is-text[disabled] {\n background-color: transparent; \n border-color: transparent; \n box-shadow: none; \n}\n\n.button.is-white {\n background-color: white; \n border-color: transparent; \n color: #0a0a0a; \n}\n\n.button.is-white:hover {\n background-color: #f9f9f9; \n border-color: transparent; \n color: #0a0a0a; \n}\n\n.button.is-white:focus, .button.is-white.is-focused {\n border-color: transparent; \n color: #0a0a0a; \n}\n\n.button.is-white:focus:not(:active), .button.is-white.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); \n}\n\n.button.is-white:active, .button.is-white.is-active {\n background-color: #f2f2f2; \n border-color: transparent; \n color: #0a0a0a; \n}\n\n.button.is-white[disabled] {\n background-color: white; \n border-color: transparent; \n box-shadow: none; \n}\n\n.button.is-white.is-loading::after {\n border-color: transparent transparent #0a0a0a #0a0a0a !important; \n}\n\n.button.is-white.is-outlined {\n background-color: transparent; \n border-color: white; \n color: white; \n}\n\n.button.is-white.is-outlined:hover, .button.is-white.is-outlined:focus, .button.is-white.is-outlined.is-focused {\n background-color: white; \n border-color: white; \n color: #0a0a0a; \n}\n\n.button.is-white.is-outlined.is-loading::after {\n border-color: transparent transparent white white !important; \n}\n\n.button.is-white.is-outlined.is-loading:hover::after, .button.is-white.is-outlined.is-loading.is-hovered::after, .button.is-white.is-outlined.is-loading:focus::after, .button.is-white.is-outlined.is-loading.is-focused::after {\n border-color: transparent transparent #0a0a0a #0a0a0a !important; \n}\n\n.button.is-white.is-outlined[disabled] {\n background-color: transparent; \n border-color: white; \n box-shadow: none; \n color: white; \n}\n\n.button.is-light {\n background-color: whitesmoke; \n border-color: transparent; \n color: #363636; \n}\n\n.button.is-light:hover {\n background-color: #eeeeee; \n border-color: transparent; \n color: #363636; \n}\n\n.button.is-light:focus, .button.is-light.is-focused {\n border-color: transparent; \n color: #363636; \n}\n\n.button.is-light:focus:not(:active), .button.is-light.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); \n}\n\n.button.is-light:active, .button.is-light.is-active {\n background-color: #e8e8e8; \n border-color: transparent; \n color: #363636; \n}\n\n.button.is-light[disabled] {\n background-color: whitesmoke; \n border-color: transparent; \n box-shadow: none; \n}\n\n.button.is-light.is-loading::after {\n border-color: transparent transparent #363636 #363636 !important; \n}\n\n.button.is-light.is-outlined {\n background-color: transparent; \n border-color: whitesmoke; \n color: whitesmoke; \n}\n\n.button.is-light.is-outlined:hover, .button.is-light.is-outlined:focus, .button.is-light.is-outlined.is-focused {\n background-color: whitesmoke; \n border-color: whitesmoke; \n color: #363636; \n}\n\n.button.is-light.is-outlined.is-loading::after {\n border-color: transparent transparent whitesmoke whitesmoke !important; \n}\n\n.button.is-light.is-outlined.is-loading:hover::after, .button.is-light.is-outlined.is-loading.is-hovered::after, .button.is-light.is-outlined.is-loading:focus::after, .button.is-light.is-outlined.is-loading.is-focused::after {\n border-color: transparent transparent #363636 #363636 !important; \n}\n\n.button.is-light.is-outlined[disabled] {\n background-color: transparent; \n border-color: whitesmoke; \n box-shadow: none; \n color: whitesmoke; \n}\n\n.button.is-link {\n background-color: #7957d5; \n border-color: transparent; \n color: white; \n}\n\n.button.is-link:hover {\n background-color: #714dd2; \n border-color: transparent; \n color: white; \n}\n\n.button.is-link:focus, .button.is-link.is-focused {\n border-color: transparent; \n color: white; \n}\n\n.button.is-link:focus:not(:active), .button.is-link.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(121, 87, 213, 0.25); \n}\n\n.button.is-link:active, .button.is-link.is-active {\n background-color: #6943d0; \n border-color: transparent; \n color: white; \n}\n\n.button.is-link[disabled] {\n background-color: #7957d5; \n border-color: transparent; \n box-shadow: none; \n}\n\n.button.is-link.is-loading::after {\n border-color: transparent transparent white white !important; \n}\n\n.button.is-link.is-outlined {\n background-color: transparent; \n border-color: #7957d5; \n color: #7957d5; \n}\n\n.button.is-link.is-outlined:hover, .button.is-link.is-outlined:focus, .button.is-link.is-outlined.is-focused {\n background-color: #7957d5; \n border-color: #7957d5; \n color: white; \n}\n\n.button.is-link.is-outlined.is-loading::after {\n border-color: transparent transparent #7957d5 #7957d5 !important; \n}\n\n.button.is-link.is-outlined.is-loading:hover::after, .button.is-link.is-outlined.is-loading.is-hovered::after, .button.is-link.is-outlined.is-loading:focus::after, .button.is-link.is-outlined.is-loading.is-focused::after {\n border-color: transparent transparent white white !important; \n}\n\n.button.is-link.is-outlined[disabled] {\n background-color: transparent; \n border-color: #7957d5; \n box-shadow: none; \n color: #7957d5; \n}\n\n.button.is-info {\n background-color: #167df0; \n border-color: transparent; \n color: #fff; \n}\n\n.button.is-info:hover {\n background-color: #0f77ea; \n border-color: transparent; \n color: #fff; \n}\n\n.button.is-info:focus, .button.is-info.is-focused {\n border-color: transparent; \n color: #fff; \n}\n\n.button.is-info:focus:not(:active), .button.is-info.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(22, 125, 240, 0.25); \n}\n\n.button.is-info:active, .button.is-info.is-active {\n background-color: #0e71de; \n border-color: transparent; \n color: #fff; \n}\n\n.button.is-info[disabled] {\n background-color: #167df0; \n border-color: transparent; \n box-shadow: none; \n}\n\n.button.is-info.is-loading::after {\n border-color: transparent transparent #fff #fff !important; \n}\n\n.button.is-info.is-outlined {\n background-color: transparent; \n border-color: #167df0; \n color: #167df0; \n}\n\n.button.is-info.is-outlined:hover, .button.is-info.is-outlined:focus, .button.is-info.is-outlined.is-focused {\n background-color: #167df0; \n border-color: #167df0; \n color: #fff; \n}\n\n.button.is-info.is-outlined.is-loading::after {\n border-color: transparent transparent #167df0 #167df0 !important; \n}\n\n.button.is-info.is-outlined.is-loading:hover::after, .button.is-info.is-outlined.is-loading.is-hovered::after, .button.is-info.is-outlined.is-loading:focus::after, .button.is-info.is-outlined.is-loading.is-focused::after {\n border-color: transparent transparent #fff #fff !important; \n}\n\n.button.is-info.is-outlined[disabled] {\n background-color: transparent; \n border-color: #167df0; \n box-shadow: none; \n color: #167df0; \n}\n\n.button.is-success {\n background-color: #23d160; \n border-color: transparent; \n color: #fff; \n}\n\n.button.is-success:hover {\n background-color: #22c65b; \n border-color: transparent; \n color: #fff; \n}\n\n.button.is-success:focus, .button.is-success.is-focused {\n border-color: transparent; \n color: #fff; \n}\n\n.button.is-success:focus:not(:active), .button.is-success.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); \n}\n\n.button.is-success:active, .button.is-success.is-active {\n background-color: #20bc56; \n border-color: transparent; \n color: #fff; \n}\n\n.button.is-success[disabled] {\n background-color: #23d160; \n border-color: transparent; \n box-shadow: none; \n}\n\n.button.is-success.is-loading::after {\n border-color: transparent transparent #fff #fff !important; \n}\n\n.button.is-success.is-outlined {\n background-color: transparent; \n border-color: #23d160; \n color: #23d160; \n}\n\n.button.is-success.is-outlined:hover, .button.is-success.is-outlined:focus, .button.is-success.is-outlined.is-focused {\n background-color: #23d160; \n border-color: #23d160; \n color: #fff; \n}\n\n.button.is-success.is-outlined.is-loading::after {\n border-color: transparent transparent #23d160 #23d160 !important; \n}\n\n.button.is-success.is-outlined.is-loading:hover::after, .button.is-success.is-outlined.is-loading.is-hovered::after, .button.is-success.is-outlined.is-loading:focus::after, .button.is-success.is-outlined.is-loading.is-focused::after {\n border-color: transparent transparent #fff #fff !important; \n}\n\n.button.is-success.is-outlined[disabled] {\n background-color: transparent; \n border-color: #23d160; \n box-shadow: none; \n color: #23d160; \n}\n\n.button.is-warning {\n background-color: #ffdd57; \n border-color: transparent; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.button.is-warning:hover {\n background-color: #ffdb4a; \n border-color: transparent; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.button.is-warning:focus, .button.is-warning.is-focused {\n border-color: transparent; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.button.is-warning:focus:not(:active), .button.is-warning.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); \n}\n\n.button.is-warning:active, .button.is-warning.is-active {\n background-color: #ffd83d; \n border-color: transparent; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.button.is-warning[disabled] {\n background-color: #ffdd57; \n border-color: transparent; \n box-shadow: none; \n}\n\n.button.is-warning.is-loading::after {\n border-color: transparent transparent rgba(0, 0, 0, 0.7) rgba(0, 0, 0, 0.7) !important; \n}\n\n.button.is-warning.is-outlined {\n background-color: transparent; \n border-color: #ffdd57; \n color: #ffdd57; \n}\n\n.button.is-warning.is-outlined:hover, .button.is-warning.is-outlined:focus, .button.is-warning.is-outlined.is-focused {\n background-color: #ffdd57; \n border-color: #ffdd57; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.button.is-warning.is-outlined.is-loading::after {\n border-color: transparent transparent #ffdd57 #ffdd57 !important; \n}\n\n.button.is-warning.is-outlined.is-loading:hover::after, .button.is-warning.is-outlined.is-loading.is-hovered::after, .button.is-warning.is-outlined.is-loading:focus::after, .button.is-warning.is-outlined.is-loading.is-focused::after {\n border-color: transparent transparent rgba(0, 0, 0, 0.7) rgba(0, 0, 0, 0.7) !important; \n}\n\n.button.is-warning.is-outlined[disabled] {\n background-color: transparent; \n border-color: #ffdd57; \n box-shadow: none; \n color: #ffdd57; \n}\n\n.button.is-danger {\n background-color: #ff3860; \n border-color: transparent; \n color: #fff; \n}\n\n.button.is-danger:hover {\n background-color: #ff2b56; \n border-color: transparent; \n color: #fff; \n}\n\n.button.is-danger:focus, .button.is-danger.is-focused {\n border-color: transparent; \n color: #fff; \n}\n\n.button.is-danger:focus:not(:active), .button.is-danger.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); \n}\n\n.button.is-danger:active, .button.is-danger.is-active {\n background-color: #ff1f4b; \n border-color: transparent; \n color: #fff; \n}\n\n.button.is-danger[disabled] {\n background-color: #ff3860; \n border-color: transparent; \n box-shadow: none; \n}\n\n.button.is-danger.is-loading::after {\n border-color: transparent transparent #fff #fff !important; \n}\n\n.button.is-danger.is-outlined {\n background-color: transparent; \n border-color: #ff3860; \n color: #ff3860; \n}\n\n.button.is-danger.is-outlined:hover, .button.is-danger.is-outlined:focus, .button.is-danger.is-outlined.is-focused {\n background-color: #ff3860; \n border-color: #ff3860; \n color: #fff; \n}\n\n.button.is-danger.is-outlined.is-loading::after {\n border-color: transparent transparent #ff3860 #ff3860 !important; \n}\n\n.button.is-danger.is-outlined.is-loading:hover::after, .button.is-danger.is-outlined.is-loading.is-hovered::after, .button.is-danger.is-outlined.is-loading:focus::after, .button.is-danger.is-outlined.is-loading.is-focused::after {\n border-color: transparent transparent #fff #fff !important; \n}\n\n.button.is-danger.is-outlined[disabled] {\n background-color: transparent; \n border-color: #ff3860; \n box-shadow: none; \n color: #ff3860; \n}\n\n.button.is-small {\n border-radius: 2px; \n font-size: 0.75rem; \n}\n\n.button.is-medium {\n font-size: 1.25rem; \n}\n\n.button[disabled] {\n background-color: white; \n border-color: #dbdbdb; \n box-shadow: none; \n opacity: 0.5; \n}\n\n.button.is-loading {\n color: transparent !important; \n pointer-events: none; \n}\n\n.button.is-loading::after {\n position: absolute; \n left: calc(50% - (1em / 2)); \n top: calc(50% - (1em / 2)); \n position: absolute !important; \n}\n\n.container {\n flex-grow: 1; \n margin: 0 auto; \n position: relative; \n width: auto; \n}\n\n@media screen and (min-width: 1024px) {\n .container {\n max-width: 960px; \n }\n}\n\n@media screen and (min-width: 1216px) {\n .container {\n max-width: 1152px; \n }\n}\n\n@media screen and (min-width: 1408px) {\n .container {\n max-width: 1344px; \n }\n}\n\n.content li + li {\n margin-top: 0.25em; \n}\n\n.content p:not(:last-child),\n.content ul:not(:last-child),\n.content pre:not(:last-child),\n.content table:not(:last-child) {\n margin-bottom: 1em; \n}\n\n.content h1 {\n color: #363636; \n font-weight: 600; \n line-height: 1.125; \n}\n\n.content h1 {\n font-size: 2em; \n margin-bottom: 0.5em; \n}\n\n.content h1:not(:first-child) {\n margin-top: 1em; \n}\n\n.content ul {\n list-style: disc outside; \n margin-left: 2em; \n margin-top: 1em; \n}\n\n.content ul ul {\n list-style-type: circle; \n margin-top: 0.5em; \n}\n\n.content ul ul ul {\n list-style-type: square; \n}\n\n.content pre {\n -webkit-overflow-scrolling: touch; \n overflow-x: auto; \n padding: 1.25em 1.5em; \n white-space: pre; \n word-wrap: normal; \n}\n\n.content table {\n width: 100%; \n}\n\n.content table td {\n border: 1px solid #dbdbdb; \n border-width: 0 0 1px; \n padding: 0.5em 0.75em; \n vertical-align: top; \n}\n\n.content table tbody tr:last-child td {\n border-bottom-width: 0; \n}\n\n.content.is-small {\n font-size: 0.75rem; \n}\n\n.content.is-medium {\n font-size: 1.25rem; \n}\n\n.icon {\n align-items: center; \n display: inline-flex; \n justify-content: center; \n height: 1.5rem; \n width: 1.5rem; \n}\n\n.icon.is-small {\n height: 1rem; \n width: 1rem; \n}\n\n.icon.is-medium {\n height: 2rem; \n width: 2rem; \n}\n\n.notification {\n background-color: whitesmoke; \n border-radius: 4px; \n padding: 1.25rem 2.5rem 1.25rem 1.5rem; \n position: relative; \n}\n\n.notification a:not(.button):not(.dropdown-item) {\n color: currentColor; \n text-decoration: underline; \n}\n\n.notification strong {\n color: currentColor; \n}\n\n.notification code,\n.notification pre {\n background: white; \n}\n\n.notification pre code {\n background: transparent; \n}\n\n.notification > .delete {\n position: absolute; \n right: 0.5rem; \n top: 0.5rem; \n}\n\n.notification .title,\n.notification .subtitle,\n.notification .content {\n color: currentColor; \n}\n\n.notification.is-white {\n background-color: white; \n color: #0a0a0a; \n}\n\n.notification.is-light {\n background-color: whitesmoke; \n color: #363636; \n}\n\n.notification.is-link {\n background-color: #7957d5; \n color: white; \n}\n\n.notification.is-info {\n background-color: #167df0; \n color: #fff; \n}\n\n.notification.is-success {\n background-color: #23d160; \n color: #fff; \n}\n\n.notification.is-warning {\n background-color: #ffdd57; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.notification.is-danger {\n background-color: #ff3860; \n color: #fff; \n}\n\n.progress {\n -moz-appearance: none; \n -webkit-appearance: none; \n border: none; \n border-radius: 290486px; \n display: block; \n height: 1rem; \n overflow: hidden; \n padding: 0; \n width: 100%; \n}\n\n.progress::-webkit-progress-bar {\n background-color: #dbdbdb; \n}\n\n.progress::-webkit-progress-value {\n background-color: #4a4a4a; \n}\n\n.progress::-moz-progress-bar {\n background-color: #4a4a4a; \n}\n\n.progress::-ms-fill {\n background-color: #4a4a4a; \n border: none; \n}\n\n.progress.is-white::-webkit-progress-value {\n background-color: white; \n}\n\n.progress.is-white::-moz-progress-bar {\n background-color: white; \n}\n\n.progress.is-white::-ms-fill {\n background-color: white; \n}\n\n.progress.is-white:indeterminate {\n background-image: linear-gradient(to right, white 30%, #dbdbdb 30%); \n}\n\n.progress.is-black::-webkit-progress-value {\n background-color: #0a0a0a; \n}\n\n.progress.is-black::-moz-progress-bar {\n background-color: #0a0a0a; \n}\n\n.progress.is-black::-ms-fill {\n background-color: #0a0a0a; \n}\n\n.progress.is-black:indeterminate {\n background-image: linear-gradient(to right, #0a0a0a 30%, #dbdbdb 30%); \n}\n\n.progress.is-light::-webkit-progress-value {\n background-color: whitesmoke; \n}\n\n.progress.is-light::-moz-progress-bar {\n background-color: whitesmoke; \n}\n\n.progress.is-light::-ms-fill {\n background-color: whitesmoke; \n}\n\n.progress.is-light:indeterminate {\n background-image: linear-gradient(to right, whitesmoke 30%, #dbdbdb 30%); \n}\n\n.progress.is-dark::-webkit-progress-value {\n background-color: #363636; \n}\n\n.progress.is-dark::-moz-progress-bar {\n background-color: #363636; \n}\n\n.progress.is-dark::-ms-fill {\n background-color: #363636; \n}\n\n.progress.is-dark:indeterminate {\n background-image: linear-gradient(to right, #363636 30%, #dbdbdb 30%); \n}\n\n.progress.is-primary::-webkit-progress-value {\n background-color: #7957d5; \n}\n\n.progress.is-primary::-moz-progress-bar {\n background-color: #7957d5; \n}\n\n.progress.is-primary::-ms-fill {\n background-color: #7957d5; \n}\n\n.progress.is-primary:indeterminate {\n background-image: linear-gradient(to right, #7957d5 30%, #dbdbdb 30%); \n}\n\n.progress.is-link::-webkit-progress-value {\n background-color: #7957d5; \n}\n\n.progress.is-link::-moz-progress-bar {\n background-color: #7957d5; \n}\n\n.progress.is-link::-ms-fill {\n background-color: #7957d5; \n}\n\n.progress.is-link:indeterminate {\n background-image: linear-gradient(to right, #7957d5 30%, #dbdbdb 30%); \n}\n\n.progress.is-info::-webkit-progress-value {\n background-color: #167df0; \n}\n\n.progress.is-info::-moz-progress-bar {\n background-color: #167df0; \n}\n\n.progress.is-info::-ms-fill {\n background-color: #167df0; \n}\n\n.progress.is-info:indeterminate {\n background-image: linear-gradient(to right, #167df0 30%, #dbdbdb 30%); \n}\n\n.progress.is-success::-webkit-progress-value {\n background-color: #23d160; \n}\n\n.progress.is-success::-moz-progress-bar {\n background-color: #23d160; \n}\n\n.progress.is-success::-ms-fill {\n background-color: #23d160; \n}\n\n.progress.is-success:indeterminate {\n background-image: linear-gradient(to right, #23d160 30%, #dbdbdb 30%); \n}\n\n.progress.is-warning::-webkit-progress-value {\n background-color: #ffdd57; \n}\n\n.progress.is-warning::-moz-progress-bar {\n background-color: #ffdd57; \n}\n\n.progress.is-warning::-ms-fill {\n background-color: #ffdd57; \n}\n\n.progress.is-warning:indeterminate {\n background-image: linear-gradient(to right, #ffdd57 30%, #dbdbdb 30%); \n}\n\n.progress.is-danger::-webkit-progress-value {\n background-color: #ff3860; \n}\n\n.progress.is-danger::-moz-progress-bar {\n background-color: #ff3860; \n}\n\n.progress.is-danger::-ms-fill {\n background-color: #ff3860; \n}\n\n.progress.is-danger:indeterminate {\n background-image: linear-gradient(to right, #ff3860 30%, #dbdbdb 30%); \n}\n\n.progress:indeterminate {\n animation-duration: 1.5s; \n animation-iteration-count: infinite; \n animation-name: moveIndeterminate; \n animation-timing-function: linear; \n background-color: #dbdbdb; \n background-image: linear-gradient(to right, #4a4a4a 30%, #dbdbdb 30%); \n background-position: top left; \n background-repeat: no-repeat; \n background-size: 150% 150%; \n}\n\n.progress:indeterminate::-webkit-progress-bar {\n background-color: transparent; \n}\n\n.progress:indeterminate::-moz-progress-bar {\n background-color: transparent; \n}\n\n.progress.is-small {\n height: 0.75rem; \n}\n\n.progress.is-medium {\n height: 1.25rem; \n}\n\n.progress.is-large {\n height: 1.5rem; \n}\n\n@keyframes moveIndeterminate {\n from {\n background-position: 200% 0; \n }\n to {\n background-position: -200% 0; \n }\n}\n\n.table {\n background-color: white; \n color: #363636; \n}\n\n.table td {\n border: 1px solid #dbdbdb; \n border-width: 0 0 1px; \n padding: 0.5em 0.75em; \n vertical-align: top; \n}\n\n.table td.is-white {\n background-color: white; \n border-color: white; \n color: #0a0a0a; \n}\n\n.table td.is-light {\n background-color: whitesmoke; \n border-color: whitesmoke; \n color: #363636; \n}\n\n.table td.is-link {\n background-color: #7957d5; \n border-color: #7957d5; \n color: white; \n}\n\n.table td.is-info {\n background-color: #167df0; \n border-color: #167df0; \n color: #fff; \n}\n\n.table td.is-success {\n background-color: #23d160; \n border-color: #23d160; \n color: #fff; \n}\n\n.table td.is-warning {\n background-color: #ffdd57; \n border-color: #ffdd57; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.table td.is-danger {\n background-color: #ff3860; \n border-color: #ff3860; \n color: #fff; \n}\n\n.table td.is-selected {\n background-color: #7957d5; \n color: white; \n}\n\n.table td.is-selected a,\n.table td.is-selected strong {\n color: currentColor; \n}\n\n.table tr.is-selected {\n background-color: #7957d5; \n color: white; \n}\n\n.table tr.is-selected a,\n.table tr.is-selected strong {\n color: currentColor; \n}\n\n.table tr.is-selected td,\n.table tr.is-selected th {\n border-color: white; \n color: currentColor; \n}\n\n.table tbody {\n background-color: transparent; \n}\n\n.table tbody tr:last-child td {\n border-bottom-width: 0; \n}\n\n.table.is-bordered td {\n border-width: 1px; \n}\n\n.table.is-bordered tr:last-child td {\n border-bottom-width: 1px; \n}\n\n.tag:not(body) {\n align-items: center; \n background-color: whitesmoke; \n border-radius: 4px; \n color: #4a4a4a; \n display: inline-flex; \n font-size: 0.75rem; \n height: 2em; \n justify-content: center; \n line-height: 1.5; \n padding-left: 0.75em; \n padding-right: 0.75em; \n white-space: nowrap; \n}\n\n.tag:not(body) .delete {\n margin-left: 0.25rem; \n margin-right: -0.375rem; \n}\n\n.tag:not(body).is-white {\n background-color: white; \n color: #0a0a0a; \n}\n\n.tag:not(body).is-light {\n background-color: whitesmoke; \n color: #363636; \n}\n\n.tag:not(body).is-link {\n background-color: #7957d5; \n color: white; \n}\n\n.tag:not(body).is-info {\n background-color: #167df0; \n color: #fff; \n}\n\n.tag:not(body).is-success {\n background-color: #23d160; \n color: #fff; \n}\n\n.tag:not(body).is-warning {\n background-color: #ffdd57; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.tag:not(body).is-danger {\n background-color: #ff3860; \n color: #fff; \n}\n\n.tag:not(body).is-medium {\n font-size: 1rem; \n}\n\n.tag:not(body) .icon:first-child:not(:last-child) {\n margin-left: -0.375em; \n margin-right: 0.1875em; \n}\n\n.tag:not(body) .icon:last-child:not(:first-child) {\n margin-left: 0.1875em; \n margin-right: -0.375em; \n}\n\n.tag:not(body) .icon:first-child:last-child {\n margin-left: -0.375em; \n margin-right: -0.375em; \n}\n\na.tag:hover {\n text-decoration: underline; \n}\n\n.title,\n.subtitle {\n word-break: break-word; \n}\n\n\n.title span,\n.subtitle span {\n font-weight: inherit; \n}\n\n.title .tag,\n.subtitle .tag {\n vertical-align: middle; \n}\n\n.title {\n color: #363636; \n font-size: 2rem; \n font-weight: 600; \n line-height: 1.125; \n}\n\n.title strong {\n color: inherit; \n font-weight: inherit; \n}\n\n.title:not(.is-spaced) + .subtitle {\n margin-top: -1.25rem; \n}\n\n.title.is-1 {\n font-size: 3rem; \n}\n\n.title.is-2 {\n font-size: 2.5rem; \n}\n\n.title.is-3 {\n font-size: 2rem; \n}\n\n.title.is-4 {\n font-size: 1.5rem; \n}\n\n.title.is-5 {\n font-size: 1.25rem; \n}\n\n.title.is-6 {\n font-size: 1rem; \n}\n\n.title.is-7 {\n font-size: 0.75rem; \n}\n\n.subtitle {\n color: #4a4a4a; \n font-size: 1.25rem; \n font-weight: 400; \n line-height: 1.25; \n}\n\n.subtitle strong {\n color: #363636; \n font-weight: 600; \n}\n\n.subtitle:not(.is-spaced) + .title {\n margin-top: -1.25rem; \n}\n\n.subtitle.is-1 {\n font-size: 3rem; \n}\n\n.subtitle.is-2 {\n font-size: 2.5rem; \n}\n\n.subtitle.is-3 {\n font-size: 2rem; \n}\n\n.subtitle.is-4 {\n font-size: 1.5rem; \n}\n\n.subtitle.is-5 {\n font-size: 1.25rem; \n}\n\n.subtitle.is-6 {\n font-size: 1rem; \n}\n\n.subtitle.is-7 {\n font-size: 0.75rem; \n}\n\n.input, .textarea, .select select {\n background-color: white; \n border-color: #dbdbdb; \n border-radius: 4px; \n color: #363636; \n}\n\n.input::-moz-placeholder, .textarea::-moz-placeholder, .select select::-moz-placeholder {\n color: rgba(54, 54, 54, 0.3); \n}\n\n.input::-webkit-input-placeholder, .textarea::-webkit-input-placeholder, .select select::-webkit-input-placeholder {\n color: rgba(54, 54, 54, 0.3); \n}\n\n.input:-moz-placeholder, .textarea:-moz-placeholder, .select select:-moz-placeholder {\n color: rgba(54, 54, 54, 0.3); \n}\n\n.input:-ms-input-placeholder, .textarea:-ms-input-placeholder, .select select:-ms-input-placeholder {\n color: rgba(54, 54, 54, 0.3); \n}\n\n.input:hover, .textarea:hover, .select select:hover, .select select.is-hovered {\n border-color: #b5b5b5; \n}\n\n.input:focus, .textarea:focus, .select select:focus, .is-focused.input, .is-focused.textarea, .select select.is-focused, .input:active, .textarea:active, .select select:active, .is-active.input, .is-active.textarea, .select select.is-active {\n border-color: #7957d5; \n box-shadow: 0 0 0 0.125em rgba(121, 87, 213, 0.25); \n}\n\n.input[disabled], .textarea[disabled], .select select[disabled],\n.select fieldset[disabled] select {\n background-color: whitesmoke; \n border-color: whitesmoke; \n box-shadow: none; \n color: #7a7a7a; \n}\n\n.input[disabled]::-moz-placeholder, .textarea[disabled]::-moz-placeholder, .select select[disabled]::-moz-placeholder,\n.select fieldset[disabled] select::-moz-placeholder {\n color: rgba(122, 122, 122, 0.3); \n}\n\n.input[disabled]::-webkit-input-placeholder, .textarea[disabled]::-webkit-input-placeholder, .select select[disabled]::-webkit-input-placeholder,\n.select fieldset[disabled] select::-webkit-input-placeholder {\n color: rgba(122, 122, 122, 0.3); \n}\n\n.input[disabled]:-moz-placeholder, .textarea[disabled]:-moz-placeholder, .select select[disabled]:-moz-placeholder,\n.select fieldset[disabled] select:-moz-placeholder {\n color: rgba(122, 122, 122, 0.3); \n}\n\n.input[disabled]:-ms-input-placeholder, .textarea[disabled]:-ms-input-placeholder, .select select[disabled]:-ms-input-placeholder,\n.select fieldset[disabled] select:-ms-input-placeholder {\n color: rgba(122, 122, 122, 0.3); \n}\n\n.input, .textarea {\n box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.1); \n max-width: 100%; \n width: 100%; \n}\n\n.input[readonly], .textarea[readonly] {\n box-shadow: none; \n}\n\n.is-white.input, .is-white.textarea {\n border-color: white; \n}\n\n.is-white.input:focus, .is-white.textarea:focus, .is-white.is-focused.input, .is-white.is-focused.textarea, .is-white.input:active, .is-white.textarea:active, .is-white.is-active.input, .is-white.is-active.textarea {\n box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); \n}\n\n.is-light.input, .is-light.textarea {\n border-color: whitesmoke; \n}\n\n.is-light.input:focus, .is-light.textarea:focus, .is-light.is-focused.input, .is-light.is-focused.textarea, .is-light.input:active, .is-light.textarea:active, .is-light.is-active.input, .is-light.is-active.textarea {\n box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); \n}\n\n.is-link.input, .is-link.textarea {\n border-color: #7957d5; \n}\n\n.is-link.input:focus, .is-link.textarea:focus, .is-link.is-focused.input, .is-link.is-focused.textarea, .is-link.input:active, .is-link.textarea:active, .is-link.is-active.input, .is-link.is-active.textarea {\n box-shadow: 0 0 0 0.125em rgba(121, 87, 213, 0.25); \n}\n\n.is-info.input, .is-info.textarea {\n border-color: #167df0; \n}\n\n.is-info.input:focus, .is-info.textarea:focus, .is-info.is-focused.input, .is-info.is-focused.textarea, .is-info.input:active, .is-info.textarea:active, .is-info.is-active.input, .is-info.is-active.textarea {\n box-shadow: 0 0 0 0.125em rgba(22, 125, 240, 0.25); \n}\n\n.is-success.input, .is-success.textarea {\n border-color: #23d160; \n}\n\n.is-success.input:focus, .is-success.textarea:focus, .is-success.is-focused.input, .is-success.is-focused.textarea, .is-success.input:active, .is-success.textarea:active, .is-success.is-active.input, .is-success.is-active.textarea {\n box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); \n}\n\n.is-warning.input, .is-warning.textarea {\n border-color: #ffdd57; \n}\n\n.is-warning.input:focus, .is-warning.textarea:focus, .is-warning.is-focused.input, .is-warning.is-focused.textarea, .is-warning.input:active, .is-warning.textarea:active, .is-warning.is-active.input, .is-warning.is-active.textarea {\n box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); \n}\n\n.is-danger.input, .is-danger.textarea {\n border-color: #ff3860; \n}\n\n.is-danger.input:focus, .is-danger.textarea:focus, .is-danger.is-focused.input, .is-danger.is-focused.textarea, .is-danger.input:active, .is-danger.textarea:active, .is-danger.is-active.input, .is-danger.is-active.textarea {\n box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); \n}\n\n.is-small.input, .is-small.textarea {\n border-radius: 2px; \n font-size: 0.75rem; \n}\n\n.is-medium.input, .is-medium.textarea {\n font-size: 1.25rem; \n}\n\n.textarea {\n display: block; \n max-width: 100%; \n min-width: 100%; \n padding: 0.625em; \n resize: vertical; \n}\n\n.textarea:not([rows]) {\n max-height: 600px; \n min-height: 120px; \n}\n\n.textarea[rows] {\n height: initial; \n}\n\n .radio {\n cursor: pointer; \n display: inline-block; \n line-height: 1.25; \n position: relative; \n}\n\n .radio input {\n cursor: pointer; \n}\n\n .radio:hover {\n color: #363636; \n}\n\n .radio[disabled] {\n color: #7a7a7a; \n cursor: not-allowed; \n}\n\n.radio + .radio {\n margin-left: 0.5em; \n}\n\n.select {\n display: inline-block; \n max-width: 100%; \n position: relative; \n vertical-align: top; \n}\n\n.select:not(.is-multiple) {\n height: 2.25em; \n}\n\n.select:not(.is-multiple):not(.is-loading)::after {\n border-color: #7957d5; \n right: 1.125em; \n z-index: 4; \n}\n\n.select.is-rounded select {\n border-radius: 290486px; \n padding-left: 1em; \n}\n\n.select select {\n cursor: pointer; \n display: block; \n font-size: 1em; \n max-width: 100%; \n outline: none; \n}\n\n.select select::-ms-expand {\n display: none; \n}\n\n.select select[disabled]:hover {\n border-color: whitesmoke; \n}\n\n.select select:not([multiple]) {\n padding-right: 2.5em; \n}\n\n.select select[multiple] {\n height: auto; \n padding: 0; \n}\n\n.select select[multiple] option {\n padding: 0.5em 1em; \n}\n\n.select:not(.is-multiple):not(.is-loading):hover::after {\n border-color: #363636; \n}\n\n.select.is-white:not(:hover)::after {\n border-color: white; \n}\n\n.select.is-white select {\n border-color: white; \n}\n\n.select.is-white select:hover, .select.is-white select.is-hovered {\n border-color: #f2f2f2; \n}\n\n.select.is-white select:focus, .select.is-white select.is-focused, .select.is-white select:active, .select.is-white select.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); \n}\n\n.select.is-black:not(:hover)::after {\n border-color: #0a0a0a; \n}\n\n.select.is-black select {\n border-color: #0a0a0a; \n}\n\n.select.is-black select:hover, .select.is-black select.is-hovered {\n border-color: black; \n}\n\n.select.is-black select:focus, .select.is-black select.is-focused, .select.is-black select:active, .select.is-black select.is-active {\n box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); \n}\n\n.select.is-light:not(:hover)::after {\n border-color: whitesmoke; \n}\n\n.select.is-light select {\n border-color: whitesmoke; \n}\n\n.select.is-light select:hover, .select.is-light select.is-hovered {\n border-color: #e8e8e8; \n}\n\n.select.is-light select:focus, .select.is-light select.is-focused, .select.is-light select:active, .select.is-light select.is-active {\n box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); \n}\n\n.select.is-dark:not(:hover)::after {\n border-color: #363636; \n}\n\n.select.is-dark select {\n border-color: #363636; \n}\n\n.select.is-dark select:hover, .select.is-dark select.is-hovered {\n border-color: #292929; \n}\n\n.select.is-dark select:focus, .select.is-dark select.is-focused, .select.is-dark select:active, .select.is-dark select.is-active {\n box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); \n}\n\n.select.is-primary:not(:hover)::after {\n border-color: #7957d5; \n}\n\n.select.is-primary select {\n border-color: #7957d5; \n}\n\n.select.is-primary select:hover, .select.is-primary select.is-hovered {\n border-color: #6943d0; \n}\n\n.select.is-primary select:focus, .select.is-primary select.is-focused, .select.is-primary select:active, .select.is-primary select.is-active {\n box-shadow: 0 0 0 0.125em rgba(121, 87, 213, 0.25); \n}\n\n.select.is-link:not(:hover)::after {\n border-color: #7957d5; \n}\n\n.select.is-link select {\n border-color: #7957d5; \n}\n\n.select.is-link select:hover, .select.is-link select.is-hovered {\n border-color: #6943d0; \n}\n\n.select.is-link select:focus, .select.is-link select.is-focused, .select.is-link select:active, .select.is-link select.is-active {\n box-shadow: 0 0 0 0.125em rgba(121, 87, 213, 0.25); \n}\n\n.select.is-info:not(:hover)::after {\n border-color: #167df0; \n}\n\n.select.is-info select {\n border-color: #167df0; \n}\n\n.select.is-info select:hover, .select.is-info select.is-hovered {\n border-color: #0e71de; \n}\n\n.select.is-info select:focus, .select.is-info select.is-focused, .select.is-info select:active, .select.is-info select.is-active {\n box-shadow: 0 0 0 0.125em rgba(22, 125, 240, 0.25); \n}\n\n.select.is-success:not(:hover)::after {\n border-color: #23d160; \n}\n\n.select.is-success select {\n border-color: #23d160; \n}\n\n.select.is-success select:hover, .select.is-success select.is-hovered {\n border-color: #20bc56; \n}\n\n.select.is-success select:focus, .select.is-success select.is-focused, .select.is-success select:active, .select.is-success select.is-active {\n box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); \n}\n\n.select.is-warning:not(:hover)::after {\n border-color: #ffdd57; \n}\n\n.select.is-warning select {\n border-color: #ffdd57; \n}\n\n.select.is-warning select:hover, .select.is-warning select.is-hovered {\n border-color: #ffd83d; \n}\n\n.select.is-warning select:focus, .select.is-warning select.is-focused, .select.is-warning select:active, .select.is-warning select.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); \n}\n\n.select.is-danger:not(:hover)::after {\n border-color: #ff3860; \n}\n\n.select.is-danger select {\n border-color: #ff3860; \n}\n\n.select.is-danger select:hover, .select.is-danger select.is-hovered {\n border-color: #ff1f4b; \n}\n\n.select.is-danger select:focus, .select.is-danger select.is-focused, .select.is-danger select:active, .select.is-danger select.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); \n}\n\n.select.is-small {\n border-radius: 2px; \n font-size: 0.75rem; \n}\n\n.select.is-medium {\n font-size: 1.25rem; \n}\n\n.select.is-large {\n font-size: 1.5rem; \n}\n\n.select.is-disabled::after {\n border-color: #7a7a7a; \n}\n\n.select.is-fullwidth {\n width: 100%; \n}\n\n.select.is-fullwidth select {\n width: 100%; \n}\n\n.select.is-loading::after {\n margin-top: 0; \n position: absolute; \n right: 0.625em; \n top: 0.625em; \n transform: none; \n}\n\n.select.is-loading.is-small:after {\n font-size: 0.75rem; \n}\n\n.select.is-loading.is-medium:after {\n font-size: 1.25rem; \n}\n\n.select.is-loading.is-large:after {\n font-size: 1.5rem; \n}\n\n.file-icon {\n align-items: center; \n display: flex; \n height: 1em; \n justify-content: center; \n margin-right: 0.5em; \n width: 1em; \n}\n\n.label {\n color: #363636; \n display: block; \n font-size: 1rem; \n font-weight: 600; \n}\n\n.label:not(:last-child) {\n margin-bottom: 0.5em; \n}\n\n.label.is-small {\n font-size: 0.75rem; \n}\n\n.label.is-medium {\n font-size: 1.25rem; \n}\n\n.field:not(:last-child) {\n margin-bottom: 0.75rem; \n}\n\n.field.is-grouped {\n display: flex; \n justify-content: flex-start; \n}\n\n.field.is-grouped > .control {\n flex-shrink: 0; \n}\n\n.field.is-grouped > .control:not(:last-child) {\n margin-bottom: 0; \n margin-right: 0.75rem; \n}\n\n.field.is-grouped > .control.is-expanded {\n flex-grow: 1; \n flex-shrink: 1; \n}\n\n.field.is-grouped.is-grouped-centered {\n justify-content: center; \n}\n\n.field.is-grouped.is-grouped-right {\n justify-content: flex-end; \n}\n\n.field.is-grouped.is-grouped-multiline {\n flex-wrap: wrap; \n}\n\n.field.is-grouped.is-grouped-multiline > .control:last-child, .field.is-grouped.is-grouped-multiline > .control:not(:last-child) {\n margin-bottom: 0.75rem; \n}\n\n.field.is-grouped.is-grouped-multiline:last-child {\n margin-bottom: -0.75rem; \n}\n\n.field.is-grouped.is-grouped-multiline:not(:last-child) {\n margin-bottom: 0; \n}\n\n.control {\n box-sizing: border-box; \n clear: both; \n font-size: 1rem; \n position: relative; \n text-align: left; \n}\n\n.control.has-icons-left .input:focus ~ .icon, .control.has-icons-left .taginput .taginput-container.is-focusable:focus ~ .icon,\n.control.has-icons-left .select:focus ~ .icon, .control.has-icons-right .input:focus ~ .icon, .control.has-icons-right .taginput .taginput-container.is-focusable:focus ~ .icon,\n.control.has-icons-right .select:focus ~ .icon {\n color: #7a7a7a; \n}\n\n.control.has-icons-left .input.is-small ~ .icon, .control.has-icons-left .taginput .is-small.taginput-container.is-focusable ~ .icon,\n.control.has-icons-left .select.is-small ~ .icon, .control.has-icons-right .input.is-small ~ .icon, .control.has-icons-right .taginput .is-small.taginput-container.is-focusable ~ .icon,\n.control.has-icons-right .select.is-small ~ .icon {\n font-size: 0.75rem; \n}\n\n.control.has-icons-left .input.is-medium ~ .icon, .control.has-icons-left .taginput .is-medium.taginput-container.is-focusable ~ .icon,\n.control.has-icons-left .select.is-medium ~ .icon, .control.has-icons-right .input.is-medium ~ .icon, .control.has-icons-right .taginput .is-medium.taginput-container.is-focusable ~ .icon,\n.control.has-icons-right .select.is-medium ~ .icon {\n font-size: 1.25rem; \n}\n\n.control.has-icons-left .input.is-large ~ .icon, .control.has-icons-left .taginput .is-large.taginput-container.is-focusable ~ .icon,\n.control.has-icons-left .select.is-large ~ .icon, .control.has-icons-right .input.is-large ~ .icon, .control.has-icons-right .taginput .is-large.taginput-container.is-focusable ~ .icon,\n.control.has-icons-right .select.is-large ~ .icon {\n font-size: 1.5rem; \n}\n\n.control.has-icons-left .icon, .control.has-icons-right .icon {\n color: #dbdbdb; \n height: 2.25em; \n pointer-events: none; \n position: absolute; \n top: 0; \n width: 2.25em; \n z-index: 4; \n}\n\n.control.has-icons-left .input, .control.has-icons-left .taginput .taginput-container.is-focusable,\n.control.has-icons-left .select select {\n padding-left: 2.25em; \n}\n\n.control.has-icons-left .icon.is-left {\n left: 0; \n}\n\n.control.has-icons-right .input, .control.has-icons-right .taginput .taginput-container.is-focusable,\n.control.has-icons-right .select select {\n padding-right: 2.25em; \n}\n\n.control.has-icons-right .icon.is-right {\n right: 0; \n}\n\n.control.is-loading::after {\n position: absolute !important; \n right: 0.625em; \n top: 0.625em; \n z-index: 4; \n}\n\n.control.is-loading.is-small:after {\n font-size: 0.75rem; \n}\n\n.control.is-loading.is-medium:after {\n font-size: 1.25rem; \n}\n\n.control.is-loading.is-large:after {\n font-size: 1.5rem; \n}\n\n.card-header-icon {\n align-items: center; \n cursor: pointer; \n display: flex; \n justify-content: center; \n padding: 0.75rem; \n}\n\n.dropdown {\n display: inline-flex; \n position: relative; \n vertical-align: top; \n}\n\n.dropdown.is-active .dropdown-menu, .dropdown.is-hoverable:hover .dropdown-menu {\n display: block; \n}\n\n.dropdown.is-right .dropdown-menu {\n left: auto; \n right: 0; \n}\n\n.dropdown.is-up .dropdown-menu {\n bottom: 100%; \n padding-bottom: 4px; \n padding-top: initial; \n top: auto; \n}\n\n.dropdown-menu {\n display: none; \n left: 0; \n min-width: 12rem; \n padding-top: 4px; \n position: absolute; \n top: 100%; \n z-index: 20; \n}\n\n.dropdown-content {\n background-color: white; \n border-radius: 4px; \n box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); \n padding-bottom: 0.5rem; \n padding-top: 0.5rem; \n}\n\n.dropdown-item, .dropdown .dropdown-menu .has-link a {\n color: #4a4a4a; \n display: block; \n font-size: 0.875rem; \n line-height: 1.5; \n padding: 0.375rem 1rem; \n position: relative; \n}\n\na.dropdown-item, .dropdown .dropdown-menu .has-link a,\nbutton.dropdown-item {\n padding-right: 3rem; \n text-align: left; \n white-space: nowrap; \n width: 100%; \n}\n\na.dropdown-item:hover, .dropdown .dropdown-menu .has-link a:hover,\nbutton.dropdown-item:hover {\n background-color: whitesmoke; \n color: #0a0a0a; \n}\n\na.dropdown-item.is-active, .dropdown .dropdown-menu .has-link a.is-active,\nbutton.dropdown-item.is-active {\n background-color: #7957d5; \n color: white; \n}\n\n.dropdown-divider {\n background-color: #dbdbdb; \n border: none; \n display: block; \n height: 1px; \n margin: 0.5rem 0; \n}\n\n.level {\n align-items: center; \n justify-content: space-between; \n}\n\n.level code {\n border-radius: 4px; \n}\n\n.level img {\n display: inline-block; \n vertical-align: top; \n}\n\n.level.is-mobile {\n display: flex; \n}\n\n.level.is-mobile .level-left,\n.level.is-mobile .level-right {\n display: flex; \n}\n\n.level.is-mobile .level-left + .level-right {\n margin-top: 0; \n}\n\n@media screen and (min-width: 769px), print {\n .level {\n display: flex; \n }\n}\n\n.level-left,\n.level-right {\n flex-basis: auto; \n flex-grow: 0; \n flex-shrink: 0; \n}\n\n.level-left {\n align-items: center; \n justify-content: flex-start; \n}\n\n@media screen and (max-width: 768px) {\n .level-left + .level-right {\n margin-top: 1.5rem; \n }\n}\n\n@media screen and (min-width: 769px), print {\n .level-left {\n display: flex; \n }\n}\n\n.level-right {\n align-items: center; \n justify-content: flex-end; \n}\n\n@media screen and (min-width: 769px), print {\n .level-right {\n display: flex; \n }\n}\n\n.list {\n background-color: white; \n border-radius: 4px; \n box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); \n}\n\n.media {\n align-items: flex-start; \n display: flex; \n text-align: left; \n}\n\n.media .content:not(:last-child) {\n margin-bottom: 0.75rem; \n}\n\n.media .media {\n border-top: 1px solid rgba(219, 219, 219, 0.5); \n display: flex; \n padding-top: 0.75rem; \n}\n\n.media .media .content:not(:last-child),\n.media .media .control:not(:last-child) {\n margin-bottom: 0.5rem; \n}\n\n.media .media .media {\n padding-top: 0.5rem; \n}\n\n.media .media .media + .media {\n margin-top: 0.5rem; \n}\n\n.media + .media {\n border-top: 1px solid rgba(219, 219, 219, 0.5); \n margin-top: 1rem; \n padding-top: 1rem; \n}\n\n.media-left,\n.media-right {\n flex-basis: auto; \n flex-grow: 0; \n flex-shrink: 0; \n}\n\n.media-left {\n margin-right: 1rem; \n}\n\n.media-right {\n margin-left: 1rem; \n}\n\n.media-content {\n flex-basis: auto; \n flex-grow: 1; \n flex-shrink: 1; \n text-align: left; \n}\n\n@media screen and (max-width: 768px) {\n .media-content {\n overflow-x: auto; \n }\n}\n\n.menu {\n font-size: 1rem; \n}\n\n.menu.is-small {\n font-size: 0.75rem; \n}\n\n.menu.is-medium {\n font-size: 1.25rem; \n}\n\n.message {\n background-color: whitesmoke; \n border-radius: 4px; \n font-size: 1rem; \n}\n\n.message strong {\n color: currentColor; \n}\n\n.message a:not(.button):not(.tag):not(.dropdown-item) {\n color: currentColor; \n text-decoration: underline; \n}\n\n.message.is-small {\n font-size: 0.75rem; \n}\n\n.message.is-medium {\n font-size: 1.25rem; \n}\n\n.message.is-white {\n background-color: white; \n}\n\n.message.is-light {\n background-color: #fafafa; \n}\n\n.message.is-link {\n background-color: #f8f7fd; \n}\n\n.message.is-info {\n background-color: #f5fafe; \n}\n\n.message.is-success {\n background-color: #f6fef9; \n}\n\n.message.is-warning {\n background-color: #fffdf5; \n}\n\n.message.is-danger {\n background-color: #fff5f7; \n}\n\n.modal {\n align-items: center; \n display: none; \n flex-direction: column; \n justify-content: center; \n overflow: hidden; \n position: fixed; \n z-index: 40; \n}\n\n.modal.is-active {\n display: flex; \n}\n\n.modal-background {\n background-color: rgba(10, 10, 10, 0.86); \n}\n\n.modal-content,\n.modal-card {\n margin: 0 20px; \n max-height: calc(100vh - 160px); \n overflow: auto; \n position: relative; \n width: 100%; \n}\n\n@media screen and (min-width: 769px), print {\n .modal-content,\n .modal-card {\n margin: 0 auto; \n max-height: calc(100vh - 40px); \n width: 640px; \n }\n}\n\n.modal-close {\n background: none; \n height: 40px; \n position: fixed; \n right: 20px; \n top: 20px; \n width: 40px; \n}\n\n.modal-card {\n display: flex; \n flex-direction: column; \n max-height: calc(100vh - 40px); \n overflow: hidden; \n -ms-overflow-y: visible; \n}\n\n.modal-card-head,\n.modal-card-foot {\n align-items: center; \n background-color: whitesmoke; \n display: flex; \n flex-shrink: 0; \n justify-content: flex-start; \n padding: 20px; \n position: relative; \n}\n\n.modal-card-head {\n border-bottom: 1px solid #dbdbdb; \n border-top-left-radius: 6px; \n border-top-right-radius: 6px; \n}\n\n.modal-card-title {\n color: #363636; \n flex-grow: 1; \n flex-shrink: 0; \n font-size: 1.5rem; \n line-height: 1; \n}\n\n.modal-card-foot {\n border-bottom-left-radius: 6px; \n border-bottom-right-radius: 6px; \n border-top: 1px solid #dbdbdb; \n}\n\n.modal-card-foot .button:not(:last-child) {\n margin-right: 0.5em; \n}\n\n.modal-card-body {\n -webkit-overflow-scrolling: touch; \n background-color: white; \n flex-grow: 1; \n flex-shrink: 1; \n overflow: auto; \n padding: 20px; \n}\n\n.navbar {\n background-color: white; \n min-height: 3.25rem; \n position: relative; \n z-index: 30; \n}\n\n.navbar.is-white {\n background-color: white; \n color: #0a0a0a; \n}\n\n.navbar.is-white .navbar-brand > .navbar-item {\n color: #0a0a0a; \n}\n\n.navbar.is-white .navbar-brand > a.navbar-item:focus, .navbar.is-white .navbar-brand > a.navbar-item:hover, .navbar.is-white .navbar-brand > a.navbar-item.is-active {\n background-color: #f2f2f2; \n color: #0a0a0a; \n}\n\n.navbar.is-white .navbar-burger {\n color: #0a0a0a; \n}\n\n@media screen and (min-width: 1024px) {\n \n .navbar.is-white .navbar-end > .navbar-item {\n color: #0a0a0a; \n }\n \n .navbar.is-white .navbar-end > a.navbar-item:focus,\n .navbar.is-white .navbar-end > a.navbar-item:hover,\n .navbar.is-white .navbar-end > a.navbar-item.is-active {\n background-color: #f2f2f2; \n color: #0a0a0a; \n }\n .navbar.is-white .navbar-item.has-dropdown:focus .navbar-link,\n .navbar.is-white .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-white .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #f2f2f2; \n color: #0a0a0a; \n }\n .navbar.is-white .navbar-dropdown a.navbar-item.is-active {\n background-color: white; \n color: #0a0a0a; \n }\n}\n\n.navbar.is-light {\n background-color: whitesmoke; \n color: #363636; \n}\n\n.navbar.is-light .navbar-brand > .navbar-item {\n color: #363636; \n}\n\n.navbar.is-light .navbar-brand > a.navbar-item:focus, .navbar.is-light .navbar-brand > a.navbar-item:hover, .navbar.is-light .navbar-brand > a.navbar-item.is-active {\n background-color: #e8e8e8; \n color: #363636; \n}\n\n.navbar.is-light .navbar-burger {\n color: #363636; \n}\n\n@media screen and (min-width: 1024px) {\n \n .navbar.is-light .navbar-end > .navbar-item {\n color: #363636; \n }\n \n .navbar.is-light .navbar-end > a.navbar-item:focus,\n .navbar.is-light .navbar-end > a.navbar-item:hover,\n .navbar.is-light .navbar-end > a.navbar-item.is-active {\n background-color: #e8e8e8; \n color: #363636; \n }\n .navbar.is-light .navbar-item.has-dropdown:focus .navbar-link,\n .navbar.is-light .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-light .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #e8e8e8; \n color: #363636; \n }\n .navbar.is-light .navbar-dropdown a.navbar-item.is-active {\n background-color: whitesmoke; \n color: #363636; \n }\n}\n\n.navbar.is-link {\n background-color: #7957d5; \n color: white; \n}\n\n.navbar.is-link .navbar-brand > .navbar-item {\n color: white; \n}\n\n.navbar.is-link .navbar-brand > a.navbar-item:focus, .navbar.is-link .navbar-brand > a.navbar-item:hover, .navbar.is-link .navbar-brand > a.navbar-item.is-active {\n background-color: #6943d0; \n color: white; \n}\n\n.navbar.is-link .navbar-burger {\n color: white; \n}\n\n@media screen and (min-width: 1024px) {\n \n .navbar.is-link .navbar-end > .navbar-item {\n color: white; \n }\n \n .navbar.is-link .navbar-end > a.navbar-item:focus,\n .navbar.is-link .navbar-end > a.navbar-item:hover,\n .navbar.is-link .navbar-end > a.navbar-item.is-active {\n background-color: #6943d0; \n color: white; \n }\n .navbar.is-link .navbar-item.has-dropdown:focus .navbar-link,\n .navbar.is-link .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-link .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #6943d0; \n color: white; \n }\n .navbar.is-link .navbar-dropdown a.navbar-item.is-active {\n background-color: #7957d5; \n color: white; \n }\n}\n\n.navbar.is-info {\n background-color: #167df0; \n color: #fff; \n}\n\n.navbar.is-info .navbar-brand > .navbar-item {\n color: #fff; \n}\n\n.navbar.is-info .navbar-brand > a.navbar-item:focus, .navbar.is-info .navbar-brand > a.navbar-item:hover, .navbar.is-info .navbar-brand > a.navbar-item.is-active {\n background-color: #0e71de; \n color: #fff; \n}\n\n.navbar.is-info .navbar-burger {\n color: #fff; \n}\n\n@media screen and (min-width: 1024px) {\n \n .navbar.is-info .navbar-end > .navbar-item {\n color: #fff; \n }\n \n .navbar.is-info .navbar-end > a.navbar-item:focus,\n .navbar.is-info .navbar-end > a.navbar-item:hover,\n .navbar.is-info .navbar-end > a.navbar-item.is-active {\n background-color: #0e71de; \n color: #fff; \n }\n .navbar.is-info .navbar-item.has-dropdown:focus .navbar-link,\n .navbar.is-info .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-info .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #0e71de; \n color: #fff; \n }\n .navbar.is-info .navbar-dropdown a.navbar-item.is-active {\n background-color: #167df0; \n color: #fff; \n }\n}\n\n.navbar.is-success {\n background-color: #23d160; \n color: #fff; \n}\n\n.navbar.is-success .navbar-brand > .navbar-item {\n color: #fff; \n}\n\n.navbar.is-success .navbar-brand > a.navbar-item:focus, .navbar.is-success .navbar-brand > a.navbar-item:hover, .navbar.is-success .navbar-brand > a.navbar-item.is-active {\n background-color: #20bc56; \n color: #fff; \n}\n\n.navbar.is-success .navbar-burger {\n color: #fff; \n}\n\n@media screen and (min-width: 1024px) {\n \n .navbar.is-success .navbar-end > .navbar-item {\n color: #fff; \n }\n \n .navbar.is-success .navbar-end > a.navbar-item:focus,\n .navbar.is-success .navbar-end > a.navbar-item:hover,\n .navbar.is-success .navbar-end > a.navbar-item.is-active {\n background-color: #20bc56; \n color: #fff; \n }\n .navbar.is-success .navbar-item.has-dropdown:focus .navbar-link,\n .navbar.is-success .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-success .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #20bc56; \n color: #fff; \n }\n .navbar.is-success .navbar-dropdown a.navbar-item.is-active {\n background-color: #23d160; \n color: #fff; \n }\n}\n\n.navbar.is-warning {\n background-color: #ffdd57; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.navbar.is-warning .navbar-brand > .navbar-item {\n color: rgba(0, 0, 0, 0.7); \n}\n\n.navbar.is-warning .navbar-brand > a.navbar-item:focus, .navbar.is-warning .navbar-brand > a.navbar-item:hover, .navbar.is-warning .navbar-brand > a.navbar-item.is-active {\n background-color: #ffd83d; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.navbar.is-warning .navbar-burger {\n color: rgba(0, 0, 0, 0.7); \n}\n\n@media screen and (min-width: 1024px) {\n \n .navbar.is-warning .navbar-end > .navbar-item {\n color: rgba(0, 0, 0, 0.7); \n }\n \n .navbar.is-warning .navbar-end > a.navbar-item:focus,\n .navbar.is-warning .navbar-end > a.navbar-item:hover,\n .navbar.is-warning .navbar-end > a.navbar-item.is-active {\n background-color: #ffd83d; \n color: rgba(0, 0, 0, 0.7); \n }\n .navbar.is-warning .navbar-item.has-dropdown:focus .navbar-link,\n .navbar.is-warning .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-warning .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #ffd83d; \n color: rgba(0, 0, 0, 0.7); \n }\n .navbar.is-warning .navbar-dropdown a.navbar-item.is-active {\n background-color: #ffdd57; \n color: rgba(0, 0, 0, 0.7); \n }\n}\n\n.navbar.is-danger {\n background-color: #ff3860; \n color: #fff; \n}\n\n.navbar.is-danger .navbar-brand > .navbar-item {\n color: #fff; \n}\n\n.navbar.is-danger .navbar-brand > a.navbar-item:focus, .navbar.is-danger .navbar-brand > a.navbar-item:hover, .navbar.is-danger .navbar-brand > a.navbar-item.is-active {\n background-color: #ff1f4b; \n color: #fff; \n}\n\n.navbar.is-danger .navbar-burger {\n color: #fff; \n}\n\n@media screen and (min-width: 1024px) {\n \n .navbar.is-danger .navbar-end > .navbar-item {\n color: #fff; \n }\n \n .navbar.is-danger .navbar-end > a.navbar-item:focus,\n .navbar.is-danger .navbar-end > a.navbar-item:hover,\n .navbar.is-danger .navbar-end > a.navbar-item.is-active {\n background-color: #ff1f4b; \n color: #fff; \n }\n .navbar.is-danger .navbar-item.has-dropdown:focus .navbar-link,\n .navbar.is-danger .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-danger .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #ff1f4b; \n color: #fff; \n }\n .navbar.is-danger .navbar-dropdown a.navbar-item.is-active {\n background-color: #ff3860; \n color: #fff; \n }\n}\n\n.navbar > .container {\n align-items: stretch; \n display: flex; \n min-height: 3.25rem; \n width: 100%; \n}\n\n.navbar-brand {\n align-items: stretch; \n display: flex; \n flex-shrink: 0; \n min-height: 3.25rem; \n}\n\n.navbar-brand a.navbar-item:focus, .navbar-brand a.navbar-item:hover {\n background-color: transparent; \n}\n\n.navbar-burger {\n color: #4a4a4a; \n cursor: pointer; \n display: block; \n height: 3.25rem; \n position: relative; \n width: 3.25rem; \n margin-left: auto; \n}\n\n.navbar-burger span {\n background-color: currentColor; \n display: block; \n height: 1px; \n left: calc(50% - 8px); \n position: absolute; \n transform-origin: center; \n transition-duration: 86ms; \n transition-property: background-color, opacity, transform; \n transition-timing-function: ease-out; \n width: 16px; \n}\n\n.navbar-burger span:nth-child(1) {\n top: calc(50% - 6px); \n}\n\n.navbar-burger span:nth-child(2) {\n top: calc(50% - 1px); \n}\n\n.navbar-burger span:nth-child(3) {\n top: calc(50% + 4px); \n}\n\n.navbar-burger:hover {\n background-color: rgba(0, 0, 0, 0.05); \n}\n\n.navbar-burger.is-active span:nth-child(1) {\n transform: translateY(5px) rotate(45deg); \n}\n\n.navbar-burger.is-active span:nth-child(2) {\n opacity: 0; \n}\n\n.navbar-burger.is-active span:nth-child(3) {\n transform: translateY(-5px) rotate(-45deg); \n}\n\n.navbar-menu {\n display: none; \n}\n\n.navbar-item {\n color: #4a4a4a; \n display: block; \n line-height: 1.5; \n padding: 0.5rem 0.75rem; \n position: relative; \n}\n\n.navbar-item .icon:only-child {\n margin-left: -0.25rem; \n margin-right: -0.25rem; \n}\n\na.navbar-item {\n cursor: pointer; \n}\n\na.navbar-item:focus, a.navbar-item:focus-within, a.navbar-item:hover, a.navbar-item.is-active {\n background-color: #fafafa; \n color: #7957d5; \n}\n\n.navbar-item {\n display: block; \n flex-grow: 0; \n flex-shrink: 0; \n}\n\n.navbar-item img {\n max-height: 1.75rem; \n}\n\n.navbar-item.has-dropdown {\n padding: 0; \n}\n\n.navbar-dropdown {\n font-size: 0.875rem; \n padding-bottom: 0.5rem; \n padding-top: 0.5rem; \n}\n\n.navbar-dropdown .navbar-item {\n padding-left: 1.5rem; \n padding-right: 1.5rem; \n}\n\n@media screen and (max-width: 1023px) {\n .navbar > .container {\n display: block; \n }\n .navbar-brand .navbar-item {\n align-items: center; \n display: flex; \n }\n .navbar-menu {\n background-color: white; \n box-shadow: 0 8px 16px rgba(10, 10, 10, 0.1); \n padding: 0.5rem 0; \n }\n .navbar-menu.is-active {\n display: block; \n }\n}\n\n@media screen and (min-width: 1024px) {\n .navbar,\n .navbar-menu,\n .navbar-end {\n align-items: stretch; \n display: flex; \n }\n .navbar {\n min-height: 3.25rem; \n }\n .navbar.is-transparent a.navbar-item:focus, .navbar.is-transparent a.navbar-item:hover, .navbar.is-transparent a.navbar-item.is-active {\n background-color: transparent !important; \n }\n .navbar.is-transparent .navbar-item.has-dropdown.is-active .navbar-link, .navbar.is-transparent .navbar-item.has-dropdown.is-hoverable:focus .navbar-link, .navbar.is-transparent .navbar-item.has-dropdown.is-hoverable:focus-within .navbar-link, .navbar.is-transparent .navbar-item.has-dropdown.is-hoverable:hover .navbar-link {\n background-color: transparent !important; \n }\n .navbar.is-transparent .navbar-dropdown a.navbar-item:focus, .navbar.is-transparent .navbar-dropdown a.navbar-item:hover {\n background-color: whitesmoke; \n color: #0a0a0a; \n }\n .navbar.is-transparent .navbar-dropdown a.navbar-item.is-active {\n background-color: whitesmoke; \n color: #7957d5; \n }\n .navbar-burger {\n display: none; \n }\n .navbar-item {\n align-items: center; \n display: flex; \n }\n .navbar-item {\n display: flex; \n }\n .navbar-item.has-dropdown {\n align-items: stretch; \n }\n .navbar-item.has-dropdown-up .navbar-link::after {\n transform: rotate(135deg) translate(0.25em, -0.25em); \n }\n .navbar-item.has-dropdown-up .navbar-dropdown {\n border-bottom: 2px solid #dbdbdb; \n border-radius: 6px 6px 0 0; \n border-top: none; \n bottom: 100%; \n box-shadow: 0 -8px 8px rgba(10, 10, 10, 0.1); \n top: auto; \n }\n .navbar-item.is-active .navbar-dropdown {\n display: block; \n }\n .navbar-item.is-active .navbar-dropdown.is-boxed {\n opacity: 1; \n pointer-events: auto; \n transform: translateY(0); \n }\n .navbar-menu {\n flex-grow: 1; \n flex-shrink: 0; \n }\n .navbar-end {\n justify-content: flex-end; \n margin-left: auto; \n }\n .navbar-dropdown {\n background-color: white; \n border-bottom-left-radius: 6px; \n border-bottom-right-radius: 6px; \n border-top: 2px solid #dbdbdb; \n box-shadow: 0 8px 8px rgba(10, 10, 10, 0.1); \n display: none; \n font-size: 0.875rem; \n left: 0; \n min-width: 100%; \n position: absolute; \n top: 100%; \n z-index: 20; \n }\n .navbar-dropdown .navbar-item {\n padding: 0.375rem 1rem; \n white-space: nowrap; \n }\n .navbar-dropdown a.navbar-item {\n padding-right: 3rem; \n }\n .navbar-dropdown a.navbar-item:focus, .navbar-dropdown a.navbar-item:hover {\n background-color: whitesmoke; \n color: #0a0a0a; \n }\n .navbar-dropdown a.navbar-item.is-active {\n background-color: whitesmoke; \n color: #7957d5; \n }\n .navbar-dropdown.is-boxed {\n border-radius: 6px; \n border-top: none; \n box-shadow: 0 8px 8px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); \n display: block; \n opacity: 0; \n pointer-events: none; \n top: calc(100% + (-4px)); \n transform: translateY(-5px); \n transition-duration: 86ms; \n transition-property: opacity, transform; \n }\n .navbar-dropdown.is-right {\n left: auto; \n right: 0; \n }\n .navbar > .container .navbar-brand,\n .container > .navbar .navbar-brand {\n margin-left: -.75rem; \n }\n .navbar > .container .navbar-menu,\n .container > .navbar .navbar-menu {\n margin-right: -.75rem; \n }\n a.navbar-item.is-active {\n color: #0a0a0a; \n }\n a.navbar-item.is-active:not(:focus):not(:hover) {\n background-color: transparent; \n }\n .navbar-item.has-dropdown:focus .navbar-link, .navbar-item.has-dropdown:hover .navbar-link, .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #fafafa; \n }\n}\n\n.pagination-previous {\n font-size: 1em; \n justify-content: center; \n margin: 0.25rem; \n padding-left: 0.5em; \n padding-right: 0.5em; \n text-align: center; \n}\n\n.pagination-previous {\n border-color: #dbdbdb; \n color: #363636; \n min-width: 2.25em; \n}\n\n.pagination-previous:hover {\n border-color: #b5b5b5; \n color: #363636; \n}\n\n.pagination-previous:focus {\n border-color: #7957d5; \n}\n\n.pagination-previous:active {\n box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.2); \n}\n\n.pagination-previous[disabled] {\n background-color: #dbdbdb; \n border-color: #dbdbdb; \n box-shadow: none; \n color: #7a7a7a; \n opacity: 0.5; \n}\n\n.pagination-previous {\n padding-left: 0.75em; \n padding-right: 0.75em; \n white-space: nowrap; \n}\n\n@media screen and (max-width: 768px) {\n .pagination-previous {\n flex-grow: 1; \n flex-shrink: 1; \n }\n}\n\n@media screen and (min-width: 769px), print {\n .pagination-previous {\n order: 2; \n }\n}\n\n.panel-icon {\n display: inline-block; \n font-size: 14px; \n height: 1em; \n line-height: 1em; \n text-align: center; \n vertical-align: top; \n width: 1em; \n color: #7a7a7a; \n margin-right: 0.75em; \n}\n\n.column {\n display: block; \n flex-basis: 0; \n flex-grow: 1; \n flex-shrink: 1; \n padding: 0.75rem; \n}\n\n.columns.is-mobile > .column.is-two-thirds {\n flex: none; \n width: 66.6666%; \n}\n\n.columns.is-mobile > .column.is-1 {\n flex: none; \n width: 8.33333%; \n}\n\n.columns.is-mobile > .column.is-2 {\n flex: none; \n width: 16.66667%; \n}\n\n.columns.is-mobile > .column.is-3 {\n flex: none; \n width: 25%; \n}\n\n.columns.is-mobile > .column.is-4 {\n flex: none; \n width: 33.33333%; \n}\n\n.columns.is-mobile > .column.is-5 {\n flex: none; \n width: 41.66667%; \n}\n\n.columns.is-mobile > .column.is-6 {\n flex: none; \n width: 50%; \n}\n\n.columns.is-mobile > .column.is-7 {\n flex: none; \n width: 58.33333%; \n}\n\n.columns.is-mobile > .column.is-8 {\n flex: none; \n width: 66.66667%; \n}\n\n.columns.is-mobile > .column.is-9 {\n flex: none; \n width: 75%; \n}\n\n.columns.is-mobile > .column.is-12 {\n flex: none; \n width: 100%; \n}\n\n@media screen and (min-width: 769px), print {\n .column.is-two-thirds {\n flex: none; \n width: 66.6666%; \n }\n .column.is-1 {\n flex: none; \n width: 8.33333%; \n }\n .column.is-2 {\n flex: none; \n width: 16.66667%; \n }\n .column.is-3 {\n flex: none; \n width: 25%; \n }\n .column.is-4 {\n flex: none; \n width: 33.33333%; \n }\n .column.is-5 {\n flex: none; \n width: 41.66667%; \n }\n .column.is-6 {\n flex: none; \n width: 50%; \n }\n .column.is-7 {\n flex: none; \n width: 58.33333%; \n }\n .column.is-8 {\n flex: none; \n width: 66.66667%; \n }\n .column.is-9 {\n flex: none; \n width: 75%; \n }\n .column.is-12 {\n flex: none; \n width: 100%; \n }\n}\n\n.columns {\n margin-left: -0.75rem; \n margin-right: -0.75rem; \n margin-top: -0.75rem; \n}\n\n.columns:last-child {\n margin-bottom: -0.75rem; \n}\n\n.columns:not(:last-child) {\n margin-bottom: calc(1.5rem - 0.75rem); \n}\n\n.columns.is-centered {\n justify-content: center; \n}\n\n.columns.is-mobile {\n display: flex; \n}\n\n@media screen and (min-width: 769px), print {\n .columns:not(.is-desktop) {\n display: flex; \n }\n}\n\n.hero {\n align-items: stretch; \n display: flex; \n flex-direction: column; \n justify-content: space-between; \n}\n\n.hero .navbar {\n background: none; \n}\n\n.hero.is-white {\n background-color: white; \n color: #0a0a0a; \n}\n\n.hero.is-white a:not(.button):not(.dropdown-item):not(.tag):not(.pagination-link.is-current),\n.hero.is-white strong {\n color: inherit; \n}\n\n.hero.is-white .title {\n color: #0a0a0a; \n}\n\n.hero.is-white .subtitle {\n color: rgba(10, 10, 10, 0.9); \n}\n\n.hero.is-white .subtitle a:not(.button),\n.hero.is-white .subtitle strong {\n color: #0a0a0a; \n}\n\n@media screen and (max-width: 1023px) {\n .hero.is-white .navbar-menu {\n background-color: white; \n }\n}\n\n.hero.is-white .navbar-item {\n color: rgba(10, 10, 10, 0.7); \n}\n\n.hero.is-white a.navbar-item:hover, .hero.is-white a.navbar-item.is-active {\n background-color: #f2f2f2; \n color: #0a0a0a; \n}\n\n.hero.is-light {\n background-color: whitesmoke; \n color: #363636; \n}\n\n.hero.is-light a:not(.button):not(.dropdown-item):not(.tag):not(.pagination-link.is-current),\n.hero.is-light strong {\n color: inherit; \n}\n\n.hero.is-light .title {\n color: #363636; \n}\n\n.hero.is-light .subtitle {\n color: rgba(54, 54, 54, 0.9); \n}\n\n.hero.is-light .subtitle a:not(.button),\n.hero.is-light .subtitle strong {\n color: #363636; \n}\n\n@media screen and (max-width: 1023px) {\n .hero.is-light .navbar-menu {\n background-color: whitesmoke; \n }\n}\n\n.hero.is-light .navbar-item {\n color: rgba(54, 54, 54, 0.7); \n}\n\n.hero.is-light a.navbar-item:hover, .hero.is-light a.navbar-item.is-active {\n background-color: #e8e8e8; \n color: #363636; \n}\n\n.hero.is-link {\n background-color: #7957d5; \n color: white; \n}\n\n.hero.is-link a:not(.button):not(.dropdown-item):not(.tag):not(.pagination-link.is-current),\n.hero.is-link strong {\n color: inherit; \n}\n\n.hero.is-link .title {\n color: white; \n}\n\n.hero.is-link .subtitle {\n color: rgba(255, 255, 255, 0.9); \n}\n\n.hero.is-link .subtitle a:not(.button),\n.hero.is-link .subtitle strong {\n color: white; \n}\n\n@media screen and (max-width: 1023px) {\n .hero.is-link .navbar-menu {\n background-color: #7957d5; \n }\n}\n\n.hero.is-link .navbar-item {\n color: rgba(255, 255, 255, 0.7); \n}\n\n.hero.is-link a.navbar-item:hover, .hero.is-link a.navbar-item.is-active {\n background-color: #6943d0; \n color: white; \n}\n\n.hero.is-info {\n background-color: #167df0; \n color: #fff; \n}\n\n.hero.is-info a:not(.button):not(.dropdown-item):not(.tag):not(.pagination-link.is-current),\n.hero.is-info strong {\n color: inherit; \n}\n\n.hero.is-info .title {\n color: #fff; \n}\n\n.hero.is-info .subtitle {\n color: rgba(255, 255, 255, 0.9); \n}\n\n.hero.is-info .subtitle a:not(.button),\n.hero.is-info .subtitle strong {\n color: #fff; \n}\n\n@media screen and (max-width: 1023px) {\n .hero.is-info .navbar-menu {\n background-color: #167df0; \n }\n}\n\n.hero.is-info .navbar-item {\n color: rgba(255, 255, 255, 0.7); \n}\n\n.hero.is-info a.navbar-item:hover, .hero.is-info a.navbar-item.is-active {\n background-color: #0e71de; \n color: #fff; \n}\n\n.hero.is-success {\n background-color: #23d160; \n color: #fff; \n}\n\n.hero.is-success a:not(.button):not(.dropdown-item):not(.tag):not(.pagination-link.is-current),\n.hero.is-success strong {\n color: inherit; \n}\n\n.hero.is-success .title {\n color: #fff; \n}\n\n.hero.is-success .subtitle {\n color: rgba(255, 255, 255, 0.9); \n}\n\n.hero.is-success .subtitle a:not(.button),\n.hero.is-success .subtitle strong {\n color: #fff; \n}\n\n@media screen and (max-width: 1023px) {\n .hero.is-success .navbar-menu {\n background-color: #23d160; \n }\n}\n\n.hero.is-success .navbar-item {\n color: rgba(255, 255, 255, 0.7); \n}\n\n.hero.is-success a.navbar-item:hover, .hero.is-success a.navbar-item.is-active {\n background-color: #20bc56; \n color: #fff; \n}\n\n.hero.is-warning {\n background-color: #ffdd57; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.hero.is-warning a:not(.button):not(.dropdown-item):not(.tag):not(.pagination-link.is-current),\n.hero.is-warning strong {\n color: inherit; \n}\n\n.hero.is-warning .title {\n color: rgba(0, 0, 0, 0.7); \n}\n\n.hero.is-warning .subtitle {\n color: rgba(0, 0, 0, 0.9); \n}\n\n.hero.is-warning .subtitle a:not(.button),\n.hero.is-warning .subtitle strong {\n color: rgba(0, 0, 0, 0.7); \n}\n\n@media screen and (max-width: 1023px) {\n .hero.is-warning .navbar-menu {\n background-color: #ffdd57; \n }\n}\n\n.hero.is-warning .navbar-item {\n color: rgba(0, 0, 0, 0.7); \n}\n\n.hero.is-warning a.navbar-item:hover, .hero.is-warning a.navbar-item.is-active {\n background-color: #ffd83d; \n color: rgba(0, 0, 0, 0.7); \n}\n\n.hero.is-danger {\n background-color: #ff3860; \n color: #fff; \n}\n\n.hero.is-danger a:not(.button):not(.dropdown-item):not(.tag):not(.pagination-link.is-current),\n.hero.is-danger strong {\n color: inherit; \n}\n\n.hero.is-danger .title {\n color: #fff; \n}\n\n.hero.is-danger .subtitle {\n color: rgba(255, 255, 255, 0.9); \n}\n\n.hero.is-danger .subtitle a:not(.button),\n.hero.is-danger .subtitle strong {\n color: #fff; \n}\n\n@media screen and (max-width: 1023px) {\n .hero.is-danger .navbar-menu {\n background-color: #ff3860; \n }\n}\n\n.hero.is-danger .navbar-item {\n color: rgba(255, 255, 255, 0.7); \n}\n\n.hero.is-danger a.navbar-item:hover, .hero.is-danger a.navbar-item.is-active {\n background-color: #ff1f4b; \n color: #fff; \n}\n\n.hero.is-small .hero-body {\n padding-bottom: 1.5rem; \n padding-top: 1.5rem; \n}\n\n@media screen and (min-width: 769px), print {\n .hero.is-medium .hero-body {\n padding-bottom: 9rem; \n padding-top: 9rem; \n }\n}\n\n.hero-body {\n flex-grow: 1; \n flex-shrink: 0; \n padding: 3rem 1.5rem; \n}\n\n.section {\n padding: 3rem 1.5rem; \n}\n\n@media screen and (min-width: 1024px) {\n .section.is-medium {\n padding: 9rem 1.5rem; \n }\n}\n\n.footer {\n background-color: #fafafa; \n padding: 3rem 1.5rem 6rem; \n}\n\n@keyframes fadeOut {\n from {\n opacity: 1; \n }\n to {\n opacity: 0; \n }\n}\n\n@keyframes fadeOutDown {\n from {\n opacity: 1; \n }\n to {\n opacity: 0; \n transform: translate3d(0, 100%, 0); \n }\n}\n\n@keyframes fadeOutUp {\n from {\n opacity: 1; \n }\n to {\n opacity: 0; \n transform: translate3d(0, -100%, 0); \n }\n}\n\n@keyframes fadeIn {\n from {\n opacity: 0; \n }\n to {\n opacity: 1; \n }\n}\n\n@keyframes fadeInDown {\n from {\n opacity: 0; \n transform: translate3d(0, -100%, 0); \n }\n to {\n opacity: 1; \n transform: none; \n }\n}\n\n@keyframes fadeInUp {\n from {\n opacity: 0; \n transform: translate3d(0, 100%, 0); \n }\n to {\n opacity: 1; \n transform: none; \n }\n}\n\n/**\r\n * Vue Transitions\r\n */\n\n\n.slide-prev-enter-active,\n.slide-prev-leave-active {\n transition: transform 250ms cubic-bezier(0.785, 0.135, 0.15, 0.86); \n}\n\n.slide-prev-leave-to {\n transform: translate3d(-100%, 0, 0); \n position: absolute; \n width: 100%; \n}\n\n.slide-prev-enter {\n transform: translate3d(100%, 0, 0); \n position: absolute; \n width: 100%; \n}\n\n.autocomplete {\n position: relative; \n}\n\n.autocomplete .dropdown-menu {\n display: block; \n min-width: 100%; \n max-width: 100%; \n}\n\n.autocomplete .dropdown-menu.is-opened-top {\n top: auto; \n bottom: 100%; \n}\n\n.autocomplete .dropdown-content {\n overflow: auto; \n max-height: 200px; \n}\n\n.autocomplete .dropdown-item, .autocomplete .dropdown .dropdown-menu .has-link a, .dropdown .dropdown-menu .has-link .autocomplete a {\n white-space: nowrap; \n overflow: hidden; \n text-overflow: ellipsis; \n}\n\n.autocomplete .dropdown-item.is-hovered, .autocomplete .dropdown .dropdown-menu .has-link a.is-hovered, .dropdown .dropdown-menu .has-link .autocomplete a.is-hovered {\n background: whitesmoke; \n color: #0a0a0a; \n}\n\n.autocomplete .dropdown-item.is-disabled, .autocomplete .dropdown .dropdown-menu .has-link a.is-disabled, .dropdown .dropdown-menu .has-link .autocomplete a.is-disabled {\n opacity: 0.5; \n cursor: not-allowed; \n}\n\n.autocomplete.is-small {\n border-radius: 2px; \n font-size: 0.75rem; \n}\n\n.autocomplete.is-medium {\n font-size: 1.25rem; \n}\n\n.autocomplete.is-large {\n font-size: 1.5rem; \n}\n\n .dropdown .dropdown-menu .has-link .b-clockpicker a {\n font-size: inherit; \n padding: 0; \n}\n\n .dropdown .dropdown-menu .has-link .datepicker a {\n font-size: inherit; \n}\n\n.dropdown + .dropdown {\n margin-left: 0.5em; \n}\n\n.dropdown .background {\n bottom: 0; \n left: 0; \n position: absolute; \n right: 0; \n top: 0; \n position: fixed; \n background-color: rgba(10, 10, 10, 0.86); \n z-index: 40; \n cursor: pointer; \n}\n\n@media screen and (min-width: 1024px) {\n .dropdown .background {\n display: none; \n }\n}\n\n.dropdown .dropdown-menu .dropdown-item.is-disabled, .dropdown .dropdown-menu .has-link a.is-disabled {\n cursor: not-allowed; \n}\n\n.dropdown .dropdown-menu .dropdown-item.is-disabled:hover, .dropdown .dropdown-menu .has-link a.is-disabled:hover {\n background: inherit; \n color: inherit; \n}\n\n.dropdown .dropdown-menu .has-link a {\n padding-right: 3rem; \n white-space: nowrap; \n}\n\n.dropdown:not(.is-disabled) .dropdown-menu .dropdown-item.is-disabled, .dropdown:not(.is-disabled) .dropdown-menu .has-link a.is-disabled {\n opacity: 0.5; \n}\n\n.dropdown .navbar-item {\n height: 100%; \n}\n\n.dropdown.is-disabled {\n opacity: 0.5; \n cursor: not-allowed; \n}\n\n.dropdown.is-disabled .dropdown-trigger {\n pointer-events: none; \n}\n\n.dropdown.is-inline .dropdown-menu {\n position: static; \n display: inline-block; \n padding: 0; \n}\n\n.dropdown.is-top-right .dropdown-menu {\n top: auto; \n bottom: 100%; \n}\n\n.dropdown.is-top-left .dropdown-menu {\n top: auto; \n bottom: 100%; \n right: 0; \n left: auto; \n}\n\n.dropdown.is-bottom-left .dropdown-menu {\n right: 0; \n left: auto; \n}\n\n@media screen and (max-width: 1023px) {\n .dropdown.is-mobile-modal .dropdown-menu {\n position: fixed; \n width: calc(100vw - 40px); \n max-width: 460px; \n max-height: calc(100vh - 120px); \n top: 25% !important; \n left: 50% !important; \n bottom: auto !important; \n right: auto !important; \n transform: translate3d(-50%, -25%, 0); \n white-space: normal; \n overflow-y: auto; \n z-index: 50; \n }\n .dropdown.is-mobile-modal .dropdown-menu .dropdown-item, .dropdown.is-mobile-modal .dropdown-menu .has-link a {\n padding: 1rem 1.5rem; \n }\n}\n\n.field.is-grouped .field {\n flex-shrink: 0; \n}\n\n.field.is-grouped .field:not(:last-child) {\n margin-right: 0.75rem; \n}\n\n.control .help.counter {\n float: right; \n margin-left: 0.5em; \n}\n\n.control .icon.is-clickable {\n pointer-events: auto; \n cursor: pointer; \n}\n\n.icon {\n -webkit-touch-callout: none; \n -webkit-user-select: none; \n -moz-user-select: none; \n -ms-user-select: none; \n user-select: none; \n cursor: inherit; \n}\n\n.icon svg {\n background-color: transparent; \n fill: currentColor; \n stroke-width: 0; \n stroke: currentColor; \n pointer-events: none; \n width: 1.5rem; \n height: 1.5rem; \n}\n\n.loading-overlay {\n bottom: 0; \n left: 0; \n position: absolute; \n right: 0; \n top: 0; \n align-items: center; \n display: none; \n justify-content: center; \n overflow: hidden; \n}\n\n.loading-overlay.is-active {\n display: flex; \n}\n\n.loading-overlay.is-full-page {\n z-index: 999; \n position: fixed; \n}\n\n.loading-overlay.is-full-page .loading-icon:after {\n top: calc(50% - 2.5em); \n left: calc(50% - 2.5em); \n width: 5em; \n height: 5em; \n}\n\n.loading-overlay .loading-background {\n bottom: 0; \n left: 0; \n position: absolute; \n right: 0; \n top: 0; \n background: #7f7f7f; \n background: rgba(255, 255, 255, 0.5); \n}\n\n.loading-overlay .loading-icon {\n position: relative; \n}\n\n.loading-overlay .loading-icon:after {\n animation: spinAround 500ms infinite linear; \n border: 2px solid #dbdbdb; \n border-radius: 290486px; \n border-right-color: transparent; \n border-top-color: transparent; \n content: ""; \n display: block; \n height: 1em; \n position: relative; \n width: 1em; \n position: absolute; \n top: calc(50% - 1.5em); \n left: calc(50% - 1.5em); \n width: 3em; \n height: 3em; \n border-width: 0.25em; \n}\n\n.message .media,\n.notification .media {\n padding-top: 0; \n border: 0; \n}\n\n.notification > .delete {\n right: 0.5rem !important; \n top: 0.5rem !important; \n}\n\n.modal.is-full-screen > .animation-content,\n.modal.is-full-screen > .animation-content > .modal-card {\n width: 100%; \n height: 100%; \n max-height: 100vh; \n margin: 0; \n background-color: #ffffff; \n}\n\n.modal .animation-content {\n margin: 0 20px; \n}\n\n.modal .animation-content .modal-card {\n margin: 0; \n}\n\n@media screen and (max-width: 768px) {\n .modal .animation-content {\n width: 100%; \n }\n}\n\n.modal .modal-content {\n width: 100%; \n}\n\n.notices {\n position: fixed; \n display: flex; \n top: 0; \n bottom: 0; \n left: 0; \n right: 0; \n padding: 2em; \n overflow: hidden; \n z-index: 1000; \n pointer-events: none; \n}\n\n.notices .toast {\n display: inline-flex; \n animation-duration: 150ms; \n margin: 0.5em 0; \n text-align: center; \n box-shadow: 0 1px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04); \n border-radius: 2em; \n padding: 0.75em 1.5em; \n pointer-events: auto; \n opacity: 0.92; \n}\n\n.notices .toast.is-white {\n color: #0a0a0a; \n background: white; \n}\n\n.notices .toast.is-light {\n color: #363636; \n background: whitesmoke; \n}\n\n.notices .toast.is-link {\n color: white; \n background: #7957d5; \n}\n\n.notices .toast.is-info {\n color: #fff; \n background: #167df0; \n}\n\n.notices .toast.is-success {\n color: #fff; \n background: #23d160; \n}\n\n.notices .toast.is-warning {\n color: rgba(0, 0, 0, 0.7); \n background: #ffdd57; \n}\n\n.notices .toast.is-danger {\n color: #fff; \n background: #ff3860; \n}\n\n.notices .snackbar {\n display: inline-flex; \n align-items: center; \n justify-content: space-around; \n animation-duration: 150ms; \n margin: 0.5em 0; \n box-shadow: 0 1px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04); \n border-radius: 4px; \n pointer-events: auto; \n background: #363636; \n color: whitesmoke; \n min-height: 3em; \n}\n\n.notices .snackbar .text {\n padding: 0.5em 1em; \n}\n\n.notices .snackbar .action {\n margin-left: auto; \n padding: 0.5em; \n padding-left: 0; \n}\n\n.notices .snackbar .action .button {\n font-weight: 600; \n text-transform: uppercase; \n background: #363636; \n border: transparent; \n}\n\n.notices .snackbar .action .button:hover {\n background: #292929; \n}\n\n.notices .snackbar .action .button:active {\n background: #292929; \n}\n\n.notices .snackbar .action.is-white .button {\n color: white; \n}\n\n.notices .snackbar .action.is-black .button {\n color: #0a0a0a; \n}\n\n.notices .snackbar .action.is-light .button {\n color: whitesmoke; \n}\n\n.notices .snackbar .action.is-dark .button {\n color: #363636; \n}\n\n.notices .snackbar .action.is-primary .button {\n color: #7957d5; \n}\n\n.notices .snackbar .action.is-link .button {\n color: #7957d5; \n}\n\n.notices .snackbar .action.is-info .button {\n color: #167df0; \n}\n\n.notices .snackbar .action.is-success .button {\n color: #23d160; \n}\n\n.notices .snackbar .action.is-warning .button {\n color: #ffdd57; \n}\n\n.notices .snackbar .action.is-danger .button {\n color: #ff3860; \n}\n\n@media screen and (max-width: 768px) {\n .notices .snackbar {\n width: 100%; \n margin: 0; \n border-radius: 0; \n }\n}\n\n@media screen and (min-width: 769px), print {\n .notices .snackbar {\n min-width: 350px; \n max-width: 600px; \n overflow: hidden; \n }\n}\n\n.notices .notification {\n max-width: 600px; \n}\n\n.notices .toast.is-top, .notices .toast.is-bottom,\n.notices .snackbar.is-top,\n.notices .snackbar.is-bottom,\n.notices .notification.is-top,\n.notices .notification.is-bottom {\n align-self: center; \n}\n\n\n.notices .snackbar.is-top-right,\n.notices .snackbar.is-bottom-right {\n align-self: flex-end; \n}\n\n\n.notices .snackbar.is-top-left,\n.notices .snackbar.is-bottom-left {\n align-self: flex-start; \n}\n\n\n.notices .snackbar.is-toast {\n opacity: 0.92; \n}\n\n.notices.is-top {\n flex-direction: column; \n}\n\n.notices.is-bottom {\n flex-direction: column-reverse; \n}\n\n.notices.has-custom-container {\n position: absolute; \n}\n\n@media screen and (max-width: 768px) {\n .notices {\n padding: 0; \n position: fixed !important; \n }\n}\n\n.progress-wrapper {\n position: relative; \n}\n\n.progress-wrapper:not(:last-child) {\n margin-bottom: 1.5rem; \n}\n\n.progress-wrapper .progress-value {\n position: absolute; \n top: 0; \n left: 50%; \n transform: translateX(-50%); \n font-size: calc(1rem / 1.5); \n line-height: 1rem; \n font-weight: bold; \n}\n\n.progress-wrapper .progress {\n margin-bottom: 0; \n}\n\n.progress-wrapper .progress.is-small + .progress-value {\n font-size: calc(0.75rem / 1.5); \n line-height: 0.75rem; \n}\n\n.progress-wrapper .progress.is-medium + .progress-value {\n font-size: calc(1.25rem / 1.5); \n line-height: 1.25rem; \n}\n\n.progress-wrapper .progress.is-large + .progress-value {\n font-size: calc(1.5rem / 1.5); \n line-height: 1.5rem; \n}\n\n.progress-wrapper .progress::-webkit-progress-value {\n transition: width 0.5s ease; \n}\n\n.b-radio.radio {\n outline: none; \n display: inline-flex; \n align-items: center; \n -webkit-touch-callout: none; \n -webkit-user-select: none; \n -moz-user-select: none; \n -ms-user-select: none; \n user-select: none; \n}\n\n.b-radio.radio + .radio {\n margin-left: 0.5em; \n}\n\n.b-radio.radio input[type=radio] {\n position: absolute; \n left: 0; \n opacity: 0; \n outline: none; \n z-index: -1; \n}\n\n.b-radio.radio input[type=radio] + .check {\n display: flex; \n flex-shrink: 0; \n position: relative; \n cursor: pointer; \n width: 1.25em; \n height: 1.25em; \n transition: background 150ms ease-out; \n border-radius: 50%; \n border: 2px solid #7a7a7a; \n}\n\n.b-radio.radio input[type=radio] + .check:before {\n content: ""; \n display: flex; \n position: absolute; \n left: 50%; \n margin-left: calc(-1.25em/2); \n bottom: 50%; \n margin-bottom: calc(-1.25em/2); \n width: 1.25em; \n height: 1.25em; \n transition: transform 150ms ease-out; \n border-radius: 50%; \n transform: scale(0); \n background-color: #7957d5; \n}\n\n.b-radio.radio input[type=radio] + .check.is-white:before {\n background: white; \n}\n\n.b-radio.radio input[type=radio] + .check.is-black:before {\n background: #0a0a0a; \n}\n\n.b-radio.radio input[type=radio] + .check.is-light:before {\n background: whitesmoke; \n}\n\n.b-radio.radio input[type=radio] + .check.is-dark:before {\n background: #363636; \n}\n\n.b-radio.radio input[type=radio] + .check.is-primary:before {\n background: #7957d5; \n}\n\n.b-radio.radio input[type=radio] + .check.is-link:before {\n background: #7957d5; \n}\n\n.b-radio.radio input[type=radio] + .check.is-info:before {\n background: #167df0; \n}\n\n.b-radio.radio input[type=radio] + .check.is-success:before {\n background: #23d160; \n}\n\n.b-radio.radio input[type=radio] + .check.is-warning:before {\n background: #ffdd57; \n}\n\n.b-radio.radio input[type=radio] + .check.is-danger:before {\n background: #ff3860; \n}\n\n.b-radio.radio input[type=radio]:checked + .check {\n border-color: #7957d5; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-white {\n border-color: white; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-black {\n border-color: #0a0a0a; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-light {\n border-color: whitesmoke; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-dark {\n border-color: #363636; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-primary {\n border-color: #7957d5; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-link {\n border-color: #7957d5; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-info {\n border-color: #167df0; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-success {\n border-color: #23d160; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-warning {\n border-color: #ffdd57; \n}\n\n.b-radio.radio input[type=radio]:checked + .check.is-danger {\n border-color: #ff3860; \n}\n\n.b-radio.radio input[type=radio]:checked + .check:before {\n transform: scale(0.5); \n}\n\n.b-radio.radio input[type=radio]:focus + .check {\n box-shadow: 0 0 0.5em rgba(122, 122, 122, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check {\n box-shadow: 0 0 0.5em rgba(121, 87, 213, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-white {\n box-shadow: 0 0 0.5em rgba(255, 255, 255, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-black {\n box-shadow: 0 0 0.5em rgba(10, 10, 10, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-light {\n box-shadow: 0 0 0.5em rgba(245, 245, 245, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-dark {\n box-shadow: 0 0 0.5em rgba(54, 54, 54, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-primary {\n box-shadow: 0 0 0.5em rgba(121, 87, 213, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-link {\n box-shadow: 0 0 0.5em rgba(121, 87, 213, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-info {\n box-shadow: 0 0 0.5em rgba(22, 125, 240, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-success {\n box-shadow: 0 0 0.5em rgba(35, 209, 96, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-warning {\n box-shadow: 0 0 0.5em rgba(255, 221, 87, 0.8); \n}\n\n.b-radio.radio input[type=radio]:focus:checked + .check.is-danger {\n box-shadow: 0 0 0.5em rgba(255, 56, 96, 0.8); \n}\n\n.b-radio.radio .control-label {\n padding-left: 0.5em; \n}\n\n.b-radio.radio[disabled] {\n opacity: 0.5; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check {\n border-color: #7957d5; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-white {\n border-color: white; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-black {\n border-color: #0a0a0a; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-light {\n border-color: whitesmoke; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-dark {\n border-color: #363636; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-primary {\n border-color: #7957d5; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-link {\n border-color: #7957d5; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-info {\n border-color: #167df0; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-success {\n border-color: #23d160; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-warning {\n border-color: #ffdd57; \n}\n\n.b-radio.radio:hover input[type=radio]:not(:disabled) + .check.is-danger {\n border-color: #ff3860; \n}\n\n.b-radio.radio.is-small {\n border-radius: 2px; \n font-size: 0.75rem; \n}\n\n.b-radio.radio.is-medium {\n font-size: 1.25rem; \n}\n\n.b-radio.radio.is-large {\n font-size: 1.5rem; \n}\n\n.select select {\n padding-right: 2.5em; \n}\n\n.select select option {\n color: #4a4a4a; \n padding: 0.25em 0.5em; \n}\n\n.select select option:disabled {\n cursor: not-allowed; \n opacity: 0.5; \n}\n\n.select select optgroup {\n color: #b5b5b5; \n font-weight: 400; \n font-style: normal; \n padding: 0.25em 0; \n}\n\n.select.is-empty select {\n color: rgba(122, 122, 122, 0.7); \n}\n\n.b-slider {\n margin: 1em 0; \n background: transparent; \n width: 100%; \n}\n\n.b-slider .b-slider-track {\n display: flex; \n align-items: center; \n position: relative; \n cursor: pointer; \n background: #dbdbdb; \n border-radius: 4px; \n}\n\n.b-slider .b-slider-fill {\n position: absolute; \n height: 100%; \n box-shadow: 0px 0px 0px #7a7a7a; \n background: #dbdbdb; \n border-radius: 4px; \n border: 0px solid #7a7a7a; \n top: 50%; \n transform: translateY(-50%); \n}\n\n.b-slider .b-slider-thumb-wrapper {\n display: inline-flex; \n align-items: center; \n position: absolute; \n cursor: grab; \n transform: translate(-50%, -50%); \n top: 50%; \n flex-direction: column; \n}\n\n.b-slider .b-slider-thumb-wrapper .b-slider-thumb {\n box-shadow: none; \n border: 1px solid #b5b5b5; \n border-radius: 4px; \n background: white; \n}\n\n.b-slider .b-slider-thumb-wrapper .b-slider-thumb:focus {\n transform: scale(1.25); \n}\n\n.b-slider .b-slider-thumb-wrapper.is-dragging {\n cursor: grabbing; \n}\n\n.b-slider .b-slider-thumb-wrapper.is-dragging .b-slider-thumb {\n transform: scale(1.25); \n}\n\n.b-slider.is-rounded .b-slider-thumb {\n border-radius: 290486px; \n}\n\n.b-slider.is-disabled .b-slider-track {\n cursor: not-allowed; \n opacity: 0.5; \n}\n\n.b-slider.is-disabled .b-slider-thumb-wrapper {\n cursor: not-allowed; \n}\n\n.b-slider.is-disabled .b-slider-thumb-wrapper .b-slider-thumb {\n transform: scale(1); \n}\n\n.b-slider .b-slider-track {\n height: 0.5rem; \n}\n\n.b-slider .b-slider-thumb {\n height: 1rem; \n width: 1rem; \n}\n\n.b-slider .b-slider-tick {\n height: 0.25rem; \n}\n\n.b-slider .b-slider-tick-label {\n font-size: 0.75rem; \n position: absolute; \n top: calc(0.5rem / 2 + 2px); \n left: 50%; \n transform: translateX(-50%); \n}\n\n.b-slider.is-small .b-slider-track {\n height: 0.375rem; \n}\n\n.b-slider.is-small .b-slider-thumb {\n height: 0.75rem; \n width: 0.75rem; \n}\n\n.b-slider.is-small .b-slider-tick {\n height: 0.1875rem; \n}\n\n.b-slider.is-small .b-slider-tick-label {\n font-size: 0.75rem; \n position: absolute; \n top: calc(0.375rem / 2 + 2px); \n left: 50%; \n transform: translateX(-50%); \n}\n\n.b-slider.is-medium .b-slider-track {\n height: 0.625rem; \n}\n\n.b-slider.is-medium .b-slider-thumb {\n height: 1.25rem; \n width: 1.25rem; \n}\n\n.b-slider.is-medium .b-slider-tick {\n height: 0.3125rem; \n}\n\n.b-slider.is-medium .b-slider-tick-label {\n font-size: 0.75rem; \n position: absolute; \n top: calc(0.625rem / 2 + 2px); \n left: 50%; \n transform: translateX(-50%); \n}\n\n.b-slider.is-large .b-slider-track {\n height: 0.75rem; \n}\n\n.b-slider.is-large .b-slider-thumb {\n height: 1.5rem; \n width: 1.5rem; \n}\n\n.b-slider.is-large .b-slider-tick {\n height: 0.375rem; \n}\n\n.b-slider.is-large .b-slider-tick-label {\n font-size: 0.75rem; \n position: absolute; \n top: calc(0.75rem / 2 + 2px); \n left: 50%; \n transform: translateX(-50%); \n}\n\n.b-slider.is-white .b-slider-fill {\n background: white !important; \n}\n\n.b-slider.is-black .b-slider-fill {\n background: #0a0a0a !important; \n}\n\n.b-slider.is-light .b-slider-fill {\n background: whitesmoke !important; \n}\n\n.b-slider.is-dark .b-slider-fill {\n background: #363636 !important; \n}\n\n.b-slider.is-primary .b-slider-fill {\n background: #7957d5 !important; \n}\n\n.b-slider.is-link .b-slider-fill {\n background: #7957d5 !important; \n}\n\n.b-slider.is-info .b-slider-fill {\n background: #167df0 !important; \n}\n\n.b-slider.is-success .b-slider-fill {\n background: #23d160 !important; \n}\n\n.b-slider.is-warning .b-slider-fill {\n background: #ffdd57 !important; \n}\n\n.b-slider.is-danger .b-slider-fill {\n background: #ff3860 !important; \n}\n\n.b-slider .b-slider-tick {\n position: absolute; \n width: 3px; \n transform: translate(-50%, -50%); \n top: 50%; \n background: #b5b5b5; \n border-radius: 4px; \n}\n\n.b-slider .b-slider-tick.is-tick-hidden {\n background: transparent; \n}\n\n/*\r\nThis project is based on\r\n"bulma-steps" (https://github.com/Wikiki/bulma-steps) by\r\nWikiki (https://github.com/Wikiki) licensed under\r\nMIT (https://github.com/Wikiki/bulma-steps/blob/master/LICENSE)\r\n*/\n\n.switch {\n cursor: pointer; \n display: inline-flex; \n align-items: center; \n position: relative; \n -webkit-touch-callout: none; \n -webkit-user-select: none; \n -moz-user-select: none; \n -ms-user-select: none; \n user-select: none; \n}\n\n.switch + .switch {\n margin-left: 0.5em; \n}\n\n.switch input[type=checkbox] {\n position: absolute; \n left: 0; \n opacity: 0; \n outline: none; \n z-index: -1; \n}\n\n.switch input[type=checkbox] + .check {\n display: flex; \n align-items: center; \n flex-shrink: 0; \n width: 2.75em; \n height: 1.575em; \n padding: 0.2em; \n background: #b5b5b5; \n border-radius: 4px; \n transition: background 150ms ease-out; \n}\n\n.switch input[type=checkbox] + .check:before {\n content: ""; \n display: block; \n border-radius: 4px; \n width: 1.175em; \n height: 1.175em; \n background: whitesmoke; \n box-shadow: 0 3px 1px 0 rgba(0, 0, 0, 0.05), 0 2px 2px 0 rgba(0, 0, 0, 0.1), 0 3px 3px 0 rgba(0, 0, 0, 0.05); \n transition: transform 150ms ease-out, width 150ms ease-out; \n will-change: transform; \n}\n\n.switch input[type=checkbox] + .check.is-elastic:before {\n width: 1.75em; \n}\n\n.switch input[type=checkbox]:checked + .check {\n background: #7957d5; \n}\n\n.switch input[type=checkbox]:checked + .check.is-white {\n background: white; \n}\n\n.switch input[type=checkbox]:checked + .check.is-black {\n background: #0a0a0a; \n}\n\n.switch input[type=checkbox]:checked + .check.is-light {\n background: whitesmoke; \n}\n\n.switch input[type=checkbox]:checked + .check.is-dark {\n background: #363636; \n}\n\n.switch input[type=checkbox]:checked + .check.is-primary {\n background: #7957d5; \n}\n\n.switch input[type=checkbox]:checked + .check.is-link {\n background: #7957d5; \n}\n\n.switch input[type=checkbox]:checked + .check.is-info {\n background: #167df0; \n}\n\n.switch input[type=checkbox]:checked + .check.is-success {\n background: #23d160; \n}\n\n.switch input[type=checkbox]:checked + .check.is-warning {\n background: #ffdd57; \n}\n\n.switch input[type=checkbox]:checked + .check.is-danger {\n background: #ff3860; \n}\n\n.switch input[type=checkbox]:checked + .check:before {\n transform: translate3d(100%, 0, 0); \n}\n\n.switch input[type=checkbox]:checked + .check.is-elastic:before {\n transform: translate3d(36.36364%, 0, 0); \n}\n\n.switch input[type=checkbox]:focus {\n outline: none; \n}\n\n.switch input[type=checkbox]:focus + .check {\n box-shadow: 0 0 0.5em rgba(122, 122, 122, 0.6); \n}\n\n.switch input[type=checkbox]:focus:checked + .check {\n box-shadow: 0 0 0.5em rgba(121, 87, 213, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-white {\n box-shadow: 0 0 0.5em rgba(255, 255, 255, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-black {\n box-shadow: 0 0 0.5em rgba(10, 10, 10, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-light {\n box-shadow: 0 0 0.5em rgba(245, 245, 245, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-dark {\n box-shadow: 0 0 0.5em rgba(54, 54, 54, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-primary {\n box-shadow: 0 0 0.5em rgba(121, 87, 213, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-link {\n box-shadow: 0 0 0.5em rgba(121, 87, 213, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-info {\n box-shadow: 0 0 0.5em rgba(22, 125, 240, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-success {\n box-shadow: 0 0 0.5em rgba(35, 209, 96, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-warning {\n box-shadow: 0 0 0.5em rgba(255, 221, 87, 0.8); \n}\n\n.switch input[type=checkbox]:focus:checked + .check.is-danger {\n box-shadow: 0 0 0.5em rgba(255, 56, 96, 0.8); \n}\n\n.switch .control-label {\n padding-left: 0.5em; \n}\n\n.switch:hover input[type=checkbox] + .check {\n background: rgba(181, 181, 181, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check {\n background: rgba(121, 87, 213, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-white {\n background: rgba(255, 255, 255, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-black {\n background: rgba(10, 10, 10, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-light {\n background: rgba(245, 245, 245, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-dark {\n background: rgba(54, 54, 54, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-primary {\n background: rgba(121, 87, 213, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-link {\n background: rgba(121, 87, 213, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-info {\n background: rgba(22, 125, 240, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-success {\n background: rgba(35, 209, 96, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-warning {\n background: rgba(255, 221, 87, 0.9); \n}\n\n.switch:hover input[type=checkbox]:checked + .check.is-danger {\n background: rgba(255, 56, 96, 0.9); \n}\n\n.switch.is-rounded input[type=checkbox] + .check {\n border-radius: 290486px; \n}\n\n.switch.is-rounded input[type=checkbox] + .check:before {\n border-radius: 290486px; \n}\n\n.switch.is-outlined input[type=checkbox] + .check {\n background: transparent; \n border: 0.1rem solid #b5b5b5; \n}\n\n.switch.is-outlined input[type=checkbox] + .check:before {\n background: #b5b5b5; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check {\n border-color: #7957d5; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-white {\n background: transparent; \n border-color: white; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-white:before {\n background: white; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-black {\n background: transparent; \n border-color: #0a0a0a; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-black:before {\n background: #0a0a0a; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-light {\n background: transparent; \n border-color: whitesmoke; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-light:before {\n background: whitesmoke; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-dark {\n background: transparent; \n border-color: #363636; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-dark:before {\n background: #363636; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-primary {\n background: transparent; \n border-color: #7957d5; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-primary:before {\n background: #7957d5; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-link {\n background: transparent; \n border-color: #7957d5; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-link:before {\n background: #7957d5; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-info {\n background: transparent; \n border-color: #167df0; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-info:before {\n background: #167df0; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-success {\n background: transparent; \n border-color: #23d160; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-success:before {\n background: #23d160; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-warning {\n background: transparent; \n border-color: #ffdd57; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-warning:before {\n background: #ffdd57; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-danger {\n background: transparent; \n border-color: #ff3860; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check.is-danger:before {\n background: #ff3860; \n}\n\n.switch.is-outlined input[type=checkbox]:checked + .check:before {\n background: #7957d5; \n}\n\n.switch.is-outlined:hover input[type=checkbox] + .check {\n background: transparent; \n border-color: rgba(181, 181, 181, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check {\n background: transparent; \n border-color: rgba(121, 87, 213, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-white {\n border-color: rgba(255, 255, 255, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-black {\n border-color: rgba(10, 10, 10, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-light {\n border-color: rgba(245, 245, 245, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-dark {\n border-color: rgba(54, 54, 54, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-primary {\n border-color: rgba(121, 87, 213, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-link {\n border-color: rgba(121, 87, 213, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-info {\n border-color: rgba(22, 125, 240, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-success {\n border-color: rgba(35, 209, 96, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-warning {\n border-color: rgba(255, 221, 87, 0.9); \n}\n\n.switch.is-outlined:hover input[type=checkbox]:checked + .check.is-danger {\n border-color: rgba(255, 56, 96, 0.9); \n}\n\n.switch.is-small {\n border-radius: 2px; \n font-size: 0.75rem; \n}\n\n.switch.is-medium {\n font-size: 1.25rem; \n}\n\n.switch.is-large {\n font-size: 1.5rem; \n}\n\n.switch[disabled] {\n opacity: 0.5; \n cursor: not-allowed; \n color: #7a7a7a; \n}\n\n .dropdown .dropdown-menu .has-link .timepicker a {\n font-size: inherit; \n padding: 0; \n}\n\n.upload {\n position: relative; \n display: inline-flex; \n}\n\n.upload input[type=file] {\n position: absolute; \n top: 0; \n left: 0; \n width: 100%; \n height: 100%; \n opacity: 0; \n outline: none; \n cursor: pointer; \n z-index: -1; \n}\n\n.upload .upload-draggable {\n cursor: pointer; \n padding: 0.25em; \n border: 1px dashed #b5b5b5; \n border-radius: 6px; \n}\n\n.upload .upload-draggable.is-loading {\n position: relative; \n pointer-events: none; \n opacity: 0.5; \n}\n\n.upload .upload-draggable.is-loading:after {\n animation: spinAround 500ms infinite linear; \n border: 2px solid #dbdbdb; \n border-radius: 290486px; \n border-right-color: transparent; \n border-top-color: transparent; \n content: ""; \n display: block; \n height: 1em; \n position: relative; \n width: 1em; \n top: 0; \n left: calc(50% - 1.5em); \n width: 3em; \n height: 3em; \n border-width: 0.25em; \n}\n\n.upload .upload-draggable:hover.is-white {\n border-color: white; \n background: rgba(255, 255, 255, 0.05); \n}\n\n.upload .upload-draggable:hover.is-light {\n border-color: whitesmoke; \n background: rgba(245, 245, 245, 0.05); \n}\n\n.upload .upload-draggable:hover.is-link {\n border-color: #7957d5; \n background: rgba(121, 87, 213, 0.05); \n}\n\n.upload .upload-draggable:hover.is-info {\n border-color: #167df0; \n background: rgba(22, 125, 240, 0.05); \n}\n\n.upload .upload-draggable:hover.is-success {\n border-color: #23d160; \n background: rgba(35, 209, 96, 0.05); \n}\n\n.upload .upload-draggable:hover.is-warning {\n border-color: #ffdd57; \n background: rgba(255, 221, 87, 0.05); \n}\n\n.upload .upload-draggable:hover.is-danger {\n border-color: #ff3860; \n background: rgba(255, 56, 96, 0.05); \n}\n\n@media screen and (-ms-high-contrast: active), screen and (-ms-high-contrast: none) {\n .upload input[type=file] {\n z-index: auto; \n }\n .upload .upload-draggable + input[type=file] {\n z-index: -1; \n }\n}\n',""])}}]); <reponame>WillemLabu/intro-to-js /** * This JS waits until the page has loaded, * then goes and fetches all the posts * in our WordPress database, and displays * them all on our page. */ // Wait until the document has loaded completely $('document').ready(function(){ // Now, let's go fetch the WordPress posts from the API $.get('http://localhost/wordpress/wp-json/wp/v2/posts', function (data){ // Once we get a successful response, // lets just log it in our browser console. console.log(data); // SANITY CHECK! // Make sure we have proper data /** * The `if` just checks for a `true` value. * Therefore, if data's length is not 0, this will be true. * (And an array's length can never be less than 0) */ if (data.length) { // So, now that we know we have some proper data, // let's clear the waiting content wrapper of the // `loading` message: $('#content').html(''); // Secondly, we need to loop through the array // Use this, if you want to: // for (var i = 0; i < data.length; i++) { // or... // this one loops through the data in the opposite direction // starting at the last item, and moving forward for (var i = data.length - 1; i >= 0; i--) { // Assign a variable to store the current iteration // note the "data[i]" <- the `i` changes on every loop, // meaning we get a different post each time we run the loop. var post = data[i]; // From the browser console log (above), as well as from the // endpoint itself, we can gather the JSON structure. // Therefore, we know that the title and content sit here: var title = post.title.rendered; var content = post.content.rendered; // Now all that's left to do is to actually write it onto the page! // So, remember, this happens FOR EACH ITERATION of the loop we're in // right now! // Create an empty <h2>, and pop the title into it: var h2 = $('<h2 />').html(title); // Create an empty <div>, and place the content into it: var div = $('<div />').html(content); // Now, append them to the wrapper in our HTML page: $('#content').append(h2); $('#content').append(div); // Done! Yay! }; // and write each post onto the page } else { // Data was returned properly, // but there are no posts! // Let's create a warning message var message = "Oops, there doesn't seem to be any posts yet. " + "Sign into WordPress and go create some!"; // And place it on our page! $('#content').append(message); } }) // Handle errors with the $.get() .fail(function(){ // Let's create another message // to let the user know what went wrong! var message = "Oops, it seems the WP REST API endpoint is unreachable. " + "Make sure you have Apache and MySQL running, and that you're browsing from your localhost." // Remember, due to scope and closure, the `message` variable // doesn't exist inside this {block}, so we're free to use the same name again. console.warn(message); }); }); // END: document.ready<reponame>angus-c/react-function-plot<filename>src/lib/plotter.js import d3 from 'd3'; const defaultThickness = 4; export default class Plotter { constructor({selector = 'body', thickness = defaultThickness}) { Object.assign(this, {selector, thickness}); } addPath(fn) { this.d3Container = d3.select(this.selector); // render in a square SVG, adjust margins to center const width = this.d3Container[0][0].getBoundingClientRect().width; const height = this.d3Container[0][0].getBoundingClientRect().height; const marginOffset = Math.abs((width - height) / 2); const marginToAdjust = width > height ? 'margin-left' : 'margin-top'; this.size = Math.min(width, height); const {size, thickness} = this; const svgContainer = this.d3Container .append('svg') .attr('width', size) .attr('height', size) .attr('style', `${marginToAdjust}: ${marginOffset}px`) svgContainer.append('path') .attr('d', this.getLineFunction(fn)([...new Array(Math.round(size))].map((_, i) => i))) .attr('stroke', 'blue') .attr('stroke-width', thickness) .attr('fill', 'none'); } updatePath(fn) { const {size, thickness} = this; const svgContainer = this.d3Container.transition(); svgContainer.select('path') .attr('d', this.getLineFunction(fn)([...new Array(Math.round(size))].map((_, i) => i))) } getLineFunction(fn) { const {size, thickness} = this; return d3.svg.line() .x(i => i) .y(i => size - thickness / 2 - size * fn(i / size) * (1 - thickness / size)) .interpolate('linear'); } } const Fluxbone = require("fluxbone"); const Backbone = require("backbone"); class CounterModel extends Fluxbone.Model { get defaults() { return { number: 0 }; } validate(attrs, options) { if (attrs.number < 0) { return 'Count cannot be less than 0.' } } handleDispatch(action) { switch(action.type) { case "INCREMENT": this.set('number', this.get('number') + 1, { validate: true }) break; case "DECREMENT": this.set('number', this.get('number') - 1, { validate: true }) break; case "RESET": this.set(this.defaults) this.trigger('reset') break; default: break; } } } const store = Fluxbone.createStore({ counter: new CounterModel() }) class CounterView extends Backbone.View { initialize() { this.listenTo(this.model, "change", this.renderResult.bind(this)); this.listenTo(this.model, "invalid", this.showError.bind(this)); this.listenTo(this.model, "reset", this.hideError.bind(this)); } get events() { return { "click #inc": "inc", "click #dec": "dec", "click #reset": "reset" }; } inc(e) { e.preventDefault(); store.dispatch({ type: "INCREMENT" }); } dec(e) { e.preventDefault(); store.dispatch({ type: "DECREMENT" }); } reset(e) { e.preventDefault(); store.dispatch({ type: "RESET" }); } renderResult(model) { this.$("#result").text(model.get("number")); } showError(model, error) { this.$("#error").text(error); this.$("#error").show(); } hideError(model) { this.$("#error").hide(); this.$("#error").text(''); } render() { this.$el.html(` <div id="error" style="color: red; display: none"></div> <button id="inc">+</button> <button id="dec">-</button> <button id="reset">reset</button> <span id=result>0</span> `); return this; } } const view = new CounterView({ model: store.resources.counter}); Backbone.$("#main").append(view.render().el); import {InstantiationError, UnknownPieceFENError} from '../errors/errors'; export class Piece { constructor(whiteTurn){ const isASubChild = this instanceof Pawn || this instanceof Knight || this instanceof Bishop || this instanceof Rook || this instanceof Queen || this instanceof King; if (isASubChild) this.whiteTurn = whiteTurn; else throw new InstantiationError('Piece'); } /** * See https://goo.gl/nWOyYO */ toFEN(){ return ""; } static fromFEN(pieceFEN){ switch(pieceFEN){ case 'P': return new Pawn(true); case 'p': return new Pawn(false); case 'N': return new Knight(true); case 'n': return new Knight(false); case 'B': return new Bishop(true); case 'b': return new Bishop(false); case 'R': return new Rook(true); case 'r': return new Rook(false); case 'Q': return new Queen(true); case 'q': return new Queen(false); case 'K': return new King(true); case 'k': return new King(false); default: throw new UnknownPieceFENError(`${pieceFEN}`); } } }; export class Pawn extends Piece { constructor(whiteTurn){ super(whiteTurn); } toFEN(){ return this.whiteTurn ? 'P' : 'p'; } }; export class Knight extends Piece { constructor(whiteTurn){ super(whiteTurn); } toFEN(){ return this.whiteTurn ? 'N' : 'n'; } }; export class Bishop extends Piece { constructor(whiteTurn){ super(whiteTurn); } toFEN(){ return this.whiteTurn ? 'B' : 'b'; } }; export class Rook extends Piece { constructor(whiteTurn){ super(whiteTurn); } toFEN(){ return this.whiteTurn ? 'R' : 'r'; } }; export class Queen extends Piece { constructor(whiteTurn){ super(whiteTurn); } toFEN(){ return this.whiteTurn ? 'Q' : 'q'; } }; export class King extends Piece { constructor(whiteTurn){ super(whiteTurn); } toFEN(){ return this.whiteTurn ? 'K' : 'k'; } }<reponame>mlam0527/phaser /** * @author <NAME> <<EMAIL>> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var flip = true; var defaultModelName = 'untitled'; var currentGroup = ''; var currentMaterial = ''; /** * @ignore */ function stripComments (line) { var idx = line.indexOf('#'); return (idx > -1) ? line.substring(0, idx) : line; } /** * @ignore */ function currentModel (result) { if (result.models.length === 0) { result.models.push({ faces: [], name: defaultModelName, textureCoords: [], vertexNormals: [], vertices: [] }); } currentGroup = ''; return result.models[result.models.length - 1]; } /** * @ignore */ function parseObject (lineItems, result) { var modelName = lineItems.length >= 2 ? lineItems[1] : defaultModelName; result.models.push({ faces: [], name: modelName, textureCoords: [], vertexNormals: [], vertices: [] }); currentGroup = ''; } /** * @ignore */ function parseGroup (lineItems) { if (lineItems.length === 2) { currentGroup = lineItems[1]; } } /** * @ignore */ function parseVertexCoords (lineItems, result) { var len = lineItems.length; var x = (len >= 2) ? parseFloat(lineItems[1]) : 0; var y = (len >= 3) ? parseFloat(lineItems[2]) : 0; var z = (len >= 4) ? parseFloat(lineItems[3]) : 0; currentModel(result).vertices.push({ x: x, y: y, z: z }); } /** * @ignore */ function parseTextureCoords (lineItems, result) { var len = lineItems.length; var u = (len >= 2) ? parseFloat(lineItems[1]) : 0; var v = (len >= 3) ? parseFloat(lineItems[2]) : 0; var w = (len >= 4) ? parseFloat(lineItems[3]) : 0; if (isNaN(u)) { u = 0; } if (isNaN(v)) { v = 0; } if (isNaN(w)) { w = 0; } if (flip) { v = 1 - v; } currentModel(result).textureCoords.push({ u: u, v: v, w: w }); } /** * @ignore */ function parseVertexNormal (lineItems, result) { var len = lineItems.length; var x = (len >= 2) ? parseFloat(lineItems[1]) : 0; var y = (len >= 3) ? parseFloat(lineItems[2]) : 0; var z = (len >= 4) ? parseFloat(lineItems[3]) : 0; currentModel(result).vertexNormals.push({ x: x, y: y, z: z }); } /** * @ignore */ function parsePolygon (lineItems, result) { var totalVertices = lineItems.length - 1; if (totalVertices < 3) { return; } var face = { group: currentGroup, material: currentMaterial, vertices: [] }; for (var i = 0; i < totalVertices; i++) { var vertexString = lineItems[i + 1]; var vertexValues = vertexString.split('/'); var vvLen = vertexValues.length; if (vvLen < 1 || vvLen > 3) { continue; } var vertexIndex = 0; var textureCoordsIndex = 0; var vertexNormalIndex = 0; vertexIndex = parseInt(vertexValues[0], 10); if (vvLen > 1 && vertexValues[1] !== '') { textureCoordsIndex = parseInt(vertexValues[1], 10); } if (vvLen > 2) { vertexNormalIndex = parseInt(vertexValues[2], 10); } if (vertexIndex !== 0) { // Negative vertex indices refer to the nth last defined vertex // convert these to postive indices for simplicity if (vertexIndex < 0) { vertexIndex = currentModel(result).vertices.length + 1 + vertexIndex; } textureCoordsIndex -= 1; vertexIndex -= 1; vertexNormalIndex -= 1; face.vertices.push({ textureCoordsIndex: textureCoordsIndex, vertexIndex: vertexIndex, vertexNormalIndex: vertexNormalIndex }); } } currentModel(result).faces.push(face); } /** * @ignore */ function parseMtlLib (lineItems, result) { if (lineItems.length >= 2) { result.materialLibraries.push(lineItems[1]); } } /** * @ignore */ function parseUseMtl (lineItems) { if (lineItems.length >= 2) { currentMaterial = lineItems[1]; } } /** * Parses a Wavefront OBJ File, extracting the models from it and returning them * in an array. * * @function Phaser.Geom.ParseObj * @since 3.50.0 * * @param {string} data - The OBJ File data as a raw string. * @param {boolean} [flipUV=true] - * * @return {array} An array of model data. */ var ParseObj = function (data, flipUV) { if (flipUV === undefined) { flipUV = true; } flip = flipUV; // Store results in here var result = { materialLibraries: [], models: [] }; currentGroup = ''; currentMaterial = ''; var lines = data.split('\n'); for (var i = 0; i < lines.length; i++) { var line = stripComments(lines[i]); var lineItems = line.replace(/\s\s+/g, ' ').trim().split(' '); switch (lineItems[0].toLowerCase()) { case 'o': // Start A New Model parseObject(lineItems, result); break; case 'g': // Start a new polygon group parseGroup(lineItems); break; case 'v': // Define a vertex for the current model parseVertexCoords(lineItems, result); break; case 'vt': // Texture Coords parseTextureCoords(lineItems, result); break; case 'vn': // Define a vertex normal for the current model parseVertexNormal(lineItems, result); break; case 'f': // Define a Face/Polygon parsePolygon(lineItems, result); break; case 'mtllib': // Reference to a material library file (.mtl) parseMtlLib(lineItems, result); break; case 'usemtl': // Sets the current material to be applied to polygons defined from this point forward parseUseMtl(lineItems); break; } } return result; }; module.exports = ParseObj; export default {"name":"--pf-chart-global--layout--Height","value":300,"var":"var(--pf-chart-global--layout--Height)"} import _ from 'underscore'; import Backbone from 'backbone'; // use events and varaible name will cause eslint-plugin-backbone issue const evts = _.clone(Backbone.Events); export default evts; import { makeStyles } from '@material-ui/core/styles' import { smallDrawerWidth, largeDrawerWidth } from '../../components/LeftSideBar/LeftSideBar' export const itemStyles = { group: { backgroundColor: 'gray', color: 'white', '&:hover': { backgroundColor: 'lightgray' } }, hospital: { backgroundColor: 'darkgray', color: 'white', '&:hover': { backgroundColor: 'lightgray' } }, service: { backgroundColor: 'lightgray', color: 'black', '&:hover': { backgroundColor: 'white' } }, unit: { backgroundColor: 'white', color: 'black', '&:hover': { backgroundColor: 'lightgray' } } } export default makeStyles((theme) => ({ appBar: { marginLeft: smallDrawerWidth, width: `calc(100% - ${smallDrawerWidth}px)`, zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen }) }, appBarShift: { marginLeft: largeDrawerWidth, width: `calc(100% - ${largeDrawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen }) }, title: { borderBottom: '1px solid #D0D7D8', width: '100%', paddingTop: '80px', paddingBottom: '20px', marginBottom: '40px' }, buttons: { marginTop: theme.spacing(3), display: 'flex', justifyContent: 'flex-end' }, validateButton: { marginLeft: theme.spacing(2) } })) <gh_stars>0 var express = require('express'), cors = require('cors'), app = express(), port = process.env.PORT || 3000, mongoose = require('mongoose'), Level = require('./api/models/levelModel') Elements = require('./api/models/elementModel') Story = require('./api/models/storyModel') bodyParser = require('body-parser'); app.use(function(req, res, next){ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); next(); }) // mongoose instance connection url connection mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost/dataBase'); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); var routes = require('./api/routes/levelRoutes'); //importing route routes(app); //register the route app.listen(port); console.log('Server API started on: ' + port); import React from 'react' import { render } from 'react-dom' import promiseMiddleware from 'redux-promise' import Thunk from 'redux-thunk' import { createStore, applyMiddleware} from 'redux' import { Provider } from 'react-redux' import { Router, Route, Switch} from 'react-router-dom' import history from './lib/history' import rootReducer from './reducers' import Home from './containers/Home' import Albums from './containers/Albums' import Header from './components/Header/Header' import Token from './components/Token/Token' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import getMuiTheme from 'material-ui/styles/getMuiTheme' import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme' const store = createStore(rootReducer, applyMiddleware(promiseMiddleware, Thunk)) render( <Provider store={store}> <Router history={history}> <div> <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}> <div> <Header/> <Switch> <Route exact path="/" component={Home}/> <Route path="/artists/:id/albums" component={Albums}/> <Route path="/token" component={Token}/> </Switch> </div> </MuiThemeProvider> </div> </Router> </Provider>, document.getElementById('root'));'use strict'; var angular = require('angular'); var proxyquire = require('proxyquire'); var events = require('../events'); var util = require('./util'); describe('AppController', function () { var $controller = null; var $scope = null; var $rootScope = null; var fakeAnnotationMetadata = null; var fakeAnnotationUI = null; var fakeAuth = null; var fakeDrafts = null; var fakeFeatures = null; var fakeLocation = null; var fakeParams = null; var fakeSession = null; var fakeGroups = null; var fakeRoute = null; var fakeSettings = null; var fakeWindow = null; var sandbox = null; var createController = function (locals) { locals = locals || {}; locals.$scope = $scope; return $controller('AppController', locals); }; beforeEach(function () { fakeAnnotationMetadata = { location: function () { return 0; }, }; var AppController = proxyquire('../app-controller', util.noCallThru({ 'angular': angular, './annotation-metadata': fakeAnnotationMetadata, })); angular.module('h', []) .controller('AppController', AppController) .controller('AnnotationUIController', angular.noop); }); beforeEach(angular.mock.module('h')); beforeEach(angular.mock.module(function ($provide) { sandbox = sinon.sandbox.create(); fakeAnnotationUI = { tool: 'comment', clearSelectedAnnotations: sandbox.spy() }; fakeAuth = { logout: sandbox.stub().returns(Promise.resolve()), }; fakeDrafts = { contains: sandbox.stub(), remove: sandbox.spy(), all: sandbox.stub().returns([]), discard: sandbox.spy(), count: sandbox.stub().returns(0), unsaved: sandbox.stub().returns([]) }; fakeFeatures = { fetch: sandbox.spy(), flagEnabled: sandbox.stub().returns(false) }; fakeLocation = { search: sandbox.stub().returns({}) }; fakeParams = {id: 'test'}; fakeSession = { load: sandbox.stub().returns(Promise.resolve({userid: null})), }; fakeGroups = {focus: sandbox.spy()}; fakeRoute = {reload: sandbox.spy()}; fakeWindow = { top: {}, confirm: sandbox.stub() }; fakeSettings = { firstRun: false, }; $provide.value('annotationUI', fakeAnnotationUI); $provide.value('auth', fakeAuth); $provide.value('drafts', fakeDrafts); $provide.value('features', fakeFeatures); $provide.value('session', fakeSession); $provide.value('settings', fakeSettings); $provide.value('groups', fakeGroups); $provide.value('$route', fakeRoute); $provide.value('$location', fakeLocation); $provide.value('$routeParams', fakeParams); $provide.value('$window', fakeWindow); })); beforeEach(angular.mock.inject(function (_$controller_, _$rootScope_) { $controller = _$controller_; $rootScope = _$rootScope_; $scope = $rootScope.$new(); })); afterEach(function () { sandbox.restore(); }); describe('isSidebar property', function () { it('is false if the window is the top window', function () { fakeWindow.top = fakeWindow; createController(); assert.isFalse($scope.isSidebar); }); it('is true if the window is not the top window', function () { fakeWindow.top = {}; createController(); assert.isTrue($scope.isSidebar); }); }); it('auth.status is "unknown" on startup', function () { createController(); assert.equal($scope.auth.status, 'unknown'); }); it('sets auth.status to "logged-out" if userid is null', function () { createController(); return fakeSession.load().then(function () { assert.equal($scope.auth.status, 'logged-out'); }); }); it('sets auth.status to "logged-in" if userid is non-null', function () { fakeSession.load = function () { return Promise.resolve({userid: 'acct:<EMAIL>'}); }; createController(); return fakeSession.load().then(function () { assert.equal($scope.auth.status, 'logged-in'); }); }); it('sets userid, username, and provider properties at login', function () { fakeSession.load = function () { return Promise.resolve({userid: 'acct:<EMAIL>'}); }; createController(); return fakeSession.load().then(function () { assert.equal($scope.auth.userid, 'acct:<EMAIL>'); assert.equal($scope.auth.username, 'jim'); assert.equal($scope.auth.provider, 'hypothes.is'); }); }); it('updates auth when the logged-in user changes', function () { createController(); return fakeSession.load().then(function () { $scope.$broadcast(events.USER_CHANGED, { initialLoad: false, userid: 'acct:<EMAIL>', }); assert.deepEqual($scope.auth, { status: 'logged-in', userid: 'acct:<EMAIL>', username: 'john', provider: 'hypothes.is', }); }); }); it('does not show login form for logged in users', function () { createController(); assert.isFalse($scope.accountDialog.visible); }); it('does not show the share dialog at start', function () { createController(); assert.isFalse($scope.shareDialog.visible); }); it('does not reload the view when the logged-in user changes on first load', function () { createController(); fakeRoute.reload = sinon.spy(); $scope.$broadcast(events.USER_CHANGED, {initialLoad: true}); assert.notCalled(fakeRoute.reload); }); it('reloads the view when the logged-in user changes after first load', function () { createController(); fakeRoute.reload = sinon.spy(); $scope.$broadcast(events.USER_CHANGED, {initialLoad: false}); assert.calledOnce(fakeRoute.reload); }); describe('#login()', function () { it('shows the login dialog', function () { createController(); $scope.login(); assert.equal($scope.accountDialog.visible, true); }); }); describe('#share()', function () { it('shows the share dialog', function () { createController(); $scope.share(); assert.equal($scope.shareDialog.visible, true); }); }); describe('logout()', function () { it('prompts the user if there are drafts', function () { fakeDrafts.count.returns(1); createController(); $scope.logout(); assert.equal(fakeWindow.confirm.callCount, 1); }); it('emits "annotationDeleted" for each unsaved draft annotation', function () { fakeDrafts.unsaved = sandbox.stub().returns( ["draftOne", "draftTwo", "draftThree"] ); createController(); $rootScope.$emit = sandbox.stub(); $scope.logout(); assert($rootScope.$emit.calledThrice); assert.deepEqual( $rootScope.$emit.firstCall.args, ["annotationDeleted", "draftOne"]); assert.deepEqual( $rootScope.$emit.secondCall.args, ["annotationDeleted", "draftTwo"]); assert.deepEqual( $rootScope.$emit.thirdCall.args, ["annotationDeleted", "draftThree"]); }); it('discards draft annotations', function () { createController(); $scope.logout(); assert(fakeDrafts.discard.calledOnce); }); it('does not emit "annotationDeleted" if the user cancels the prompt', function () { createController(); fakeDrafts.count.returns(1); $rootScope.$emit = sandbox.stub(); fakeWindow.confirm.returns(false); $scope.logout(); assert($rootScope.$emit.notCalled); }); it('does not discard drafts if the user cancels the prompt', function () { createController(); fakeDrafts.count.returns(1); fakeWindow.confirm.returns(false); $scope.logout(); assert(fakeDrafts.discard.notCalled); }); it('does not prompt if there are no drafts', function () { createController(); fakeDrafts.count.returns(0); $scope.logout(); assert.equal(fakeWindow.confirm.callCount, 0); }); }); }); <filename>src/_sys/extensions/String/html.js define(["sys/models/test-proto"], test => { test(String, ["html"]); // // lit-html vs code extension support // String.html = (pieces, ...args) => String.raw(pieces, ...args); });<filename>shared/components/replyComment/index.js import React, { Component, PropTypes as Types } from 'react' import Textarea from 'react-textarea-autosize' import { VelocityTransitionGroup } from 'velocity-react' import styles from './index.scss' const enterAnimation = { animation: 'transition.slideLeftIn', stagger: 50, duration: 400, display: 'block', style: { display: 'none' } } const leaveAnimation = { animation: 'transition.slideRightOut', stagger: 50, duration: 400 } class ReplyComment extends Component { constructor (props) { super(props) this.state = { comment: '' } this.onSubmit = this.onSubmit.bind(this) } onSubmit (e) { e.preventDefault() } render () { const from = ( <div key={0} className='box' style={{marginBottom: '10px'}}> <Textarea className={'textarea-autoHeight ' + styles.replyTextArea} placeholder={`@${this.props.reply}:`} value={this.state.comment} onChange={e => this.setState({comment: e.target.value})} autofocus useCacheForDOMMeasurements /> </div> ) const sub = ( <div key={1}> <button type='submit' className='button-primary'>回复</button> </div> ) const dd = [from, sub] return ( <form onSubmit={this.onSubmit}> <VelocityTransitionGroup component='div' enter={enterAnimation} leave={leaveAnimation}> {this.props.show && dd} </VelocityTransitionGroup> </form> ) } } ReplyComment.propTypes = { reply: Types.string.isRequired, show: Types.bool.isRequired } export default ReplyComment const _ = require('lodash'); const gherkinUtils = require('./utils/gherkin.js'); const rule = 'no-restricted-tags'; const availableConfigs = { 'tags': [] }; function run(feature, unused, configuration) { if (!feature) { return []; } const forbiddenTags = configuration.tags; const language = feature.language; let errors = []; checkTags(feature, language, forbiddenTags, errors); feature.children.forEach(child => { // backgrounds don't have tags if (child.scenario) { checkTags(child.scenario, language, forbiddenTags, errors); child.scenario.examples.forEach(example => { checkTags(example, language, forbiddenTags, errors); }); } }); return errors; } function checkTags(node, language, forbiddenTags, errors) { const nodeType = gherkinUtils.getNodeType(node, language); node.tags.forEach(tag => { if (_.includes(forbiddenTags, tag.name)) { errors.push({ message: `Forbidden tag ${tag.name} on ${nodeType}`, rule : rule, line : tag.location.line }); } }); } module.exports = { name: rule, run: run, availableConfigs: availableConfigs }; <filename>src/pages/Intro.js import { Link } from "react-router-dom"; import Cover from '../assets/cover.png'; export default function Intro({ slide }) { if (slide !== 0) return null; return ( <div className=""> <div className="imageCover"> <img src={Cover} alt="Cover" className="h-screen w-full"/> <div className="textCover text-sm font-semibold"> <p><NAME></p> <p>2110191022</p> <p>3 D4 IT A</p> </div> <div className="tittleCover flex flex-col justify-center items-center"> <p className="text-3xl text-white">PENGAMBILAN KEPUTUSAN</p> <p className="text-4xl font-bold">DALAM KONDISI BERISIKO</p> <div className="mt-10"> <Link to="/calculate"> <div className="btn-start w-32 text-center text-base rounded-md cursor-pointer py-2">Mulai</div> </Link> </div> </div> </div> </div> ); } <filename>activities/Implode.activity/js/board.js function Board(){ // Board is represented as a dict from x coordinates to lists representing // columns of pieces. The beginning of the lists are the value of the piece // in the column at y=0, and subsequent values are for increasing values of // y. Missing values are represented either with None in the column list or // a missing column in the dict. this._data = {} this.repeat = function (arr, n){ var a = []; for (var i=0;i<n;[i++].push.apply(a,arr)); return a; } this.get_value = function(x, y){ // Return the value at coordinate (x,y), or undefined if no value is // present. var col = this._data[x] if(col == undefined) return undefined if((0 <= y) && (y < col.length)){ return col[y] } else return undefined } this.set_value = function(x, y, value){ // Set the value at coordinate (x,y) to the given value. // assert y >= 0 if(y >= 0){ var col = this._data[x] if(col == undefined){ if(value !== undefined){ var arr = this.repeat([undefined] , y) arr = arr.concat([value]) this._data[x] = arr } } else if(y < col.length){ col[y] = value if(value == undefined) this._trim_column(x) } else if(value == undefined){} else{ col = col.concat(this.repeat([undefined] , (y - col.length))) col = col.concat([value]) this._data[x] = col } } } this.get_column_height = function(x){ // Return the height of column x. col = this._data[x] if(col == undefined) return 0 else return col.length } this.width = function(){ return (this.max_x() - this.min_x()) } this.height = function(){ return (this.max_y() - this.min_y()) } this.min_x = function(){ if(Object.keys(this._data).length == 0) return 0 else{ var keys_arr = Object.keys(this._data) for(var i=0;i<keys_arr.length;i++){ keys_arr[i] = parseInt(keys_arr[i]) } return Math.min(0, Math.min(...keys_arr)) } } this.max_x = function(){ if(Object.keys(this._data).length == 0) return 0 else{ var keys_arr = Object.keys(this._data) for(var i=0;i<keys_arr.length;i++){ keys_arr[i] = parseInt(keys_arr[i]) } return Math.max(0, Math.max(...keys_arr)) + 1 } } this.min_y = function(){ return 0 } this.max_y = function(){ if(Object.keys(this._data).length == 0) return 0 else{ var value_arr = Object.values(this._data) var len_arr = [] for(var col=0;col<value_arr.length;col++){ len_arr[col] = value_arr[col].length } return Math.max(0, Math.max(...len_arr)) } } this.is_empty = function(){ return (Object.keys(this._data).length == 0) } this.get_col_value = function(x){ return this._data[x] } this._trim_column = function(x){ // Removes any undefined values at the top of the given column, removing the // column array entirely if it is empty var col = this._data[x] if(col[col.length-1] !== undefined){ return } var arr = [...Array(col.length).keys()].reverse() for(var i in arr){ i = parseInt(i); i = arr[i] if(col[i] !== undefined){ this._data[x] = col.slice(0,i + 1) return } } delete this._data[x] } this.items = function(){ var new_arr = [] var arr = Object.keys(this._data) for(var i in arr){ i = parseInt(i) new_arr.push([parseInt(arr[i]), this._data[parseInt(arr[i])]]) } return new_arr } this.insert_columns = function(col_index, num_columns){ // Inserts empty columns at the given index, pushing higher-numbered // columns higher // assert num_columns >= 0 if(num_columns >= 0){ var new_data = {} var arr = this.items(); for(var k in arr){ k = parseInt(k) var i = arr[k][0] var col = arr[k][1] if( i < col_index){ new_data[i] = col } else{ new_data[i + num_columns] = col } } this._data = JSON.parse(JSON.stringify(new_data)) } } this.simplify = function(){ var keys = Object.keys(this._data); for(var i in keys){ i = parseInt(i) i = keys[i] for(var j=0;j<this._data[i].length;j++){ var value = this._data[i][j]; if((value == -1) || (value == undefined) || (value == null)){ this._data[i].splice(j,1); j = j-1; } } if(this._data[i].length == 0){ delete this._data[i]; } } keys = Object.keys(this._data); for(var i=0;i<keys.length;i++){ if(i == parseInt(keys[i])){} else{ this._data[i] = this._data[parseInt(keys[i])]; delete this._data[parseInt(keys[i])]; // i = i-1; } } } this.__repr__ = function(){ var width = this.width() var height = this.height() var lines = [] for(var i in [...Array(height).keys()]){ var line = [] for(j in [...Array(width).keys()]){ i = parseInt(i) j = parseInt(j) var value = this.get_value(j, i) if(value == undefined) line.push('.') else if(value == -1) line.push('*') else line.push(value.toString()) } lines.push(line.join('')) } lines.reverse() return lines.join('\n') } } var max_size = []; function generate_board(fragmentation=0,max_colors=5,size=[30, 20]) { // Generates a new board of the given properties using the given random // seed as a starting point. Returns both the board and the list of // moves needed to solve it. max_size = size; var piece_sizes = _get_piece_sizes(fragmentation); var b = new Board() var winning_moves = [] for(var piece_size in piece_sizes){ piece_size = parseInt(piece_size) var arr = _try_add_piece(b, parseInt(piece_sizes[piece_size]), max_colors, max_size) var b = arr[0] var move = arr[1] if(move !== undefined){ winning_moves.splice(0, 0,move) } } return [b, winning_moves] } function _try_add_piece(b, piece_size, max_colors, max_size){ // Tries to add a piece of the given size to the board. Returns the // modified board on success or the original board on failure. // Also returns the lowest coordinate of the added piece (i.e. the canonical // move to remove it) or undefined if no piece added. var b2 = new Board(); b2._data = JSON.parse(JSON.stringify(b._data)) var change = _get_starting_change(b2, max_colors, max_size) if(change == undefined){ return [b, undefined] } _make_change(b2, change) var total_added_cells = 1 while(total_added_cells < piece_size){ var added_cells = _try_add_cells(b2, max_colors, max_size) if(added_cells > 0){ total_added_cells += added_cells } else{ if(total_added_cells >= 3) break else{ return [b, undefined] } } } var piece = _get_new_piece_coords(b2) var min_piece = piece[0] for(var i=1;i<piece.length;i++){ if((piece[i][0]<min_piece[0])&& (piece[i][1] < min_piece[1])){ min_piece = piece[i] } } _color_piece_random(b2, max_colors) return [b2, min_piece] } function arrayRemove(arr, value) { return arr.filter(function(ele){ return ele != value; }); } function choice(array) { return array[Math.floor(Math.random() * array.length)]; } function _get_starting_change(b, max_colors, max_size){ // Gets a valid initial change that adds a one-cell colorable piece to the // board, returning undefined if no such starting change exists. var changes = _enumerate_one_cell_changes(b, max_size) while(changes.length > 0){ var change = choice(changes) changes = arrayRemove(changes, change) if(_change_is_colorable(b, change, max_colors)){ return change } } return undefined } function _enumerate_one_cell_changes(b, max_size){ // Returns a list of all possible one-cell changes. var max_width = max_size[0] var max_height = max_size[1] var changes = [] var width = b.width() if (width < max_width && max_height >= 1){ var arr = [...Array(width+1).keys()] for(var i in arr){ i = parseInt(i) var obj = new _InsertColumnChange(arr[i], 1) changes.push(obj) } } var arr = [...Array(width).keys()] for (var i in arr){ i = parseInt(i) var col_height = b.get_column_height(arr[i]) if(col_height < max_height){ var height_arr = [...Array(col_height +1).keys()] for(var j in height_arr){ j = parseInt(j) var obj = new _InsertCellChange(arr[i], height_arr[j]) changes.push(obj) } } } return changes; } function _try_add_cells(b, max_colors, max_size){ // Tries to add a cell or cells to the new piece on the board in a way that // ensures the resulting board is within the given board size and is // colorable with the given colors. Returns the number of cells added // (zero, if no cell could be added). var a = _get_cell_changes(b, max_size) var cell_h_changes = a[0] var cell_v_changes = a[1] var col_changes = _get_col_changes(b, max_size) while (cell_h_changes.length > 0 || cell_v_changes.length > 0 || col_changes.length > 0){ var change = _remove_change(cell_h_changes, cell_v_changes, col_changes) if(_change_is_colorable(b, change, max_colors)){ _make_change(b, change) if(change instanceof _InsertCellChange){ return 1 } else{ return change.height } } } return 0 } function _get_cell_changes(b, max_size){ // Returns a list of all possible standard cell insertions. var max_width = max_size[0] var max_height = max_size[1] var h_changes = [] var v_changes = [] var width = b.width() for(var i in [...Array(width).keys()]){ i = parseInt(i) var col_height = b.get_column_height(i) if(col_height < max_height){ for(var j in [...Array(col_height + 1).keys()]){ j = parseInt(j) if(b.get_value(i, j) != -1){ if (b.get_value(i + 1, j) == -1 || b.get_value(i - 1, j) == -1){ var obj = new _InsertCellChange(i, j) h_changes.push(obj) } else if (b.get_value(i, j - 1) == -1 || b.get_value(i, j + 1) == -1){ var obj = new _InsertCellChange(i, j) v_changes.push(obj) } } } } } return [h_changes, v_changes] } function _get_col_changes(b, max_size){ // Returns a list of all possible column insertions. var max_width = max_size[0] var max_height = max_size[1] var width = b.width() if(width == max_width || max_height < 1){ return [] } var highest_new_pieces = [] for(var i in [...Array(width).keys()]){ i = parseInt(i) var col_height = b.get_column_height(i) var highest_new_piece = 0 for(var j in [...Array(col_height).keys()]){ j = parseInt(j) var value = b.get_value(i, j) if(value == -1){ highest_new_piece = j + 1 } } highest_new_pieces.push(highest_new_piece) } var changes = [] var arr1 = highest_new_pieces.concat([0]) var arr2 = [0].concat(highest_new_pieces) var arr = [arr1,arr2] var transposed = arr.reduce((r, a) => a.map((v, i) => (r[i] || []).concat(v)), []); for (var i in transposed){ i = parseInt(i) var height1 = transposed[i][0] var height2 = transposed[i][1] var height = Math.max(height1, height2) if(height > 0){ var obj = new _InsertColumnChange(i, height) changes.push(obj) } } return changes } function _remove_change(cell_h_changes, cell_v_changes, col_changes){ // Removes a change from cell changes or col changes (less likely) and // returns it. var h_weight = cell_h_changes.length * 10 var v_weight = cell_v_changes.length * 5 var col_weight = col_changes.length * 1 var value = Math.floor(Math.random() * (h_weight + v_weight + col_weight)); if(value < h_weight){ return _pick(cell_h_changes) } else if(value < (h_weight + v_weight)){ return _pick(cell_v_changes) } else{ return _pick(col_changes) } } function _pick(items){ var index = Math.floor(Math.random() * (items.length)); if(items[index]){ return items.splice(index,1)[0] } else{ return items.pop(); } } function _change_is_colorable(b, change, max_colors){ // Returns True if the board is still colorable after the given change is // made, False otherwise. var b2 = new Board(); b2._data = JSON.parse(JSON.stringify(b._data)) _make_change(b2, change) var colors = _get_new_piece_colors(b2, max_colors) return colors.length > 0 } function _make_change(b, change){ // Makes the given change to the board (side-affects board parameter). if (change instanceof _InsertColumnChange){ b.insert_columns(change.col, 1) b._data = JSON.parse(JSON.stringify(b._data)) var arr = [...Array(change.height).keys()] for( var i in arr){ i = parseInt(i) b.set_value(change.col, arr[i], -1) } } else if(change instanceof _InsertCellChange){ var new_indexes = [] var data = [] var col_height = b.get_column_height(change.col) if(change.height <= col_height) { for(var i in [...Array(col_height).keys()]){ i = parseInt(i) var value = b.get_value(change.col, i) if (i == change.height){ data.push(-1) } if(value == -1){ new_indexes.push(i) } else{ data.push(value) } } if(change.height == col_height){ data.push(-1) } for(index in new_indexes){ index = parseInt(index); data.splice(new_indexes[index],0, -1); } for (var i in data){ i = parseInt(i) var value = data[i] b.set_value(change.col, i, value) } } } } function _color_piece_random(b, max_colors){ // Colors in the new piece on the board with a random color using the given // random number generator and number of colors. var colors = _get_new_piece_colors(b, max_colors) var color = choice(colors) _color_piece(b, color) } function _color_piece(b, color){ // Colors in the new piece on the board with the given color. var coords = _get_new_piece_coords(b) for(var k in coords) { k = parseInt(k) var i = coords[k][0] var j = coords[k][1] b.set_value(i, j, color) } } function _get_new_piece_colors(b, max_colors){ // Returns the set of possible colors for the new piece. var colors = [] for(var i=1;i<(max_colors + 1);i++){ colors[i-1] = i } var coords = _get_new_piece_coords(b) for(var k in coords){ k = parseInt(k) var i = coords[k][0] var j = coords[k][1] var arr = [[-1, 0], [1, 0], [0, -1], [0, 1]] for(var m in arr){ m = parseInt(m) var x_ofs = arr[m][0] var y_ofs = arr[m][1] colors = arrayRemove(colors,b.get_value(i + x_ofs, j + y_ofs)) } } return colors } function _get_new_piece_coords(b){ // Returns a list of new piece coordinates. var coords = [] var arr = [...Array(b.width()).keys()] for (var i in arr){ i = parseInt(i) var col_height = b.get_column_height(arr[i]) var arr2 = [...Array(col_height).keys()] for (var j in arr2){ j = parseInt(j) i = arr[i] j = arr2[j] if (b.get_value(i, j) == -1){ coords.push([i, j]) } } } return coords } function _get_piece_sizes(fragmentation){ // Returns a list containing the new piece sizes for the board. var max_area = max_size[0] * max_size[1] * 0.5; var total_area = 0; var piece_sizes = [] while(total_area < max_area){ var piece_size = _get_piece_size(max_area,fragmentation) total_area = total_area + piece_size piece_sizes.push(piece_size); } return piece_sizes } function _get_piece_size(max_area,fragmentation){ // Returns a random piece size using the given random number generator, // fragmentation, and board size. var upper_bound = Math.ceil(Math.sqrt(max_area)); value = Math.random() var exp = fragmentation piece_size = parseInt(Math.max(3, Math.pow(value, exp) * upper_bound)) return piece_size } function _InsertColumnChange(col, height){ // Represents the action of inserting a column into the board at column // "col" containing "height" cells. this.col = col; this.height = height; this.__eq__ = function(other){ return ((other instanceof _InsertColumnChange) && (this.col == this.col) && (this.height == other.height)) } this.__ne__ = function(other){ return ! this.__eq__(other) } this.__repr__ = function(){ return `_InsertColumnChange(${this.col}, ${this.height})` } } function _InsertCellChange(col, height){ // Represents the action of inserting a cell into the board in column // "col" at height "height". this.col = col; this.height = height; this.__eq__ = function(other){ return ((other instanceof _InsertCellChange) && (this.col == other.col) && (this.height == other.height)) } this.__ne__ = function(other){ return ! this.__eq__(other) } this.__repr__ = function(){ return `_InsertCellChange(${this.col}, ${this.height})` } }<reponame>jpylisela/threefab THREEFAB.Toolbox = Backbone.View.extend({ initialize:function() { $('.toolbox-list').bind('click', function(event) { event.preventDefault(); var target = event.target || event.srcElement, className; if(target.tagName.toLowerCase() === "a") { className = target.className; $.publish(THREEFAB.Events.PRIMITIVE_ADDED, target.className); } }); $('.light-list').bind('click', function(event) { event.preventDefault(); var target = event.target || event.srcElement, className; if(target.tagName.toLowerCase() === "a") { className = target.className; $.publish(THREEFAB.Events.LIGHT_ADDED, target.className); } }); $('.export').bind('click', function(event) { $.publish(THREEFAB.Events.EXPORTER_GENERATE); }); $('.import').bind('click', function(event) { $.publish(THREEFAB.Events.IMPORT_EXTERNAL); }); } }); <reponame>IkwhanChang/bbb-file-manager /********************************************* This SD Card Module demo sends audio from card to Audio Module output, by piping file stream. *********************************************/ var tessel = require('tessel'), sdlib = require('../'), // use 'sdcard' in your own code aulib = require('audio-vs1053b'); sdlib.use(tessel.port['A'], {getFilesystems:true}, function (e,arr) { if (e) throw e; var fs = arr[0]; fs.readFile("sample.mp3", function (e,d) { if (e) throw e; console.log("Read file,", d.length, "bytes"); fs = null; // NOTE: audio lib breaks sdcard still! var audio = aulib.use(tessel.port['B']); audio.on('ready', function () { audio.setOutput('headphone', function () { console.log("Audio ready, playing file."); audio.play(d, function () { console.log("play said:", arguments); }); }); }); }); }); <reponame>hoanglongla/Team6-FE import React from 'react'; let direction = 'ltr'; if (typeof window !== 'undefined') { direction = document.getElementsByTagName('html')[0].getAttribute('dir'); } const withDirection = Component => props => { return <Component {...props} data-rtl={direction} />; }; export default withDirection; export { direction }; import { isArray, isObj, createElem, appendChild, extend} from "./utils"; import {obi} from "./obi"; export const createRouting = () => { let w = window, toValue = (mix) => { if (!mix) return ''; var str = decodeURIComponent(mix); if (str === 'false') return false; if (str === 'true') return true; return (+str * 0 === 0) ? (+str) : str; }, getParams = (str) => { let tmp, k, out = {}, indi; str = str || w.location.search; indi = str.indexOf("?"); if (indi < 0) return; str = str.substr(indi + 1); let arr = str.split('&'); while (tmp = arr.shift()) { tmp = tmp.split('='); k = tmp.shift(); if (out[k] !== void 0) out[k] = [].concat(out[k], toValue(tmp.shift())); else out[k] = toValue(tmp.shift()); } return out; }, stringifyParams = (obj) => { var enc = encodeURIComponent, k, i, tmp, str = ''; for (k in obj) { if ((tmp = obj[k]) !== void 0) { if (isArray(tmp)) { for (i = 0; i < tmp.length; i++) { str && (str += '&'); str += enc(k) + '=' + enc(tmp[i]); } } else { str && (str += '&'); str += enc(k) + '=' + enc(tmp); } } } return '?' + str; }, getLocation = () => { let {pathname, search} = w.location; return {url: pathname + search, pathname, search, params: getParams()} }, setUrl = (path, search, type) => { search = isObj(search) ? stringifyParams(search) : search; w.history[type + 'State'](null, null, path + search) }, initLoc = getLocation(), {url: _lastUrl, pathname: _lastPathname} = initLoc; let routing = obi({ // pre-pending with $ ignores updates when setting them $lastUrl: _lastUrl, $lastPathname: _lastPathname, $lastType: 'initial', ...initLoc, getParams, stringifyParams, getLocation, route(path, search, type) { type = type || 'push'; path = path || location.pathname; search = search || ''; const {pathname, url} = getLocation(); if (type !== 'replace') (_lastUrl = url, _lastPathname = pathname); setUrl(path, search, type); type === 'replace' ? setTimeout(() => updateLocation({type})) : updateLocation({type}); } }); routing.routerSwitch = ({root, pathMap, noMatch}) => { let next = null, toLast = false, {pathname, $lastPathname, $lastUrl, $lastType, url} = routing, noChange = url === $lastUrl; noMatch = noMatch || '/'; if (root) next = pathMap['/' + pathname.split('/')[1]] || pathMap[noMatch]; else if (pathMap[pathname]) next = pathMap[pathname]; else if ($lastPathname !== pathname && pathMap[$lastPathname]) { routing.route($lastUrl, location.search, 'replace'); next = pathMap[$lastPathname]; toLast = true; } else if (noMatch && pathMap[noMatch]) { routing.route(noMatch, location.search, 'replace'); next = pathMap[noMatch]; } return {next, toLast, noChange, replacedLast: $lastType === 'replace'}; }; var updateLocation = (e) => { routing.$merge({ ...getLocation(), $lastUrl: e.type === 'popstate' ? routing.url : _lastUrl, $lastPathname: e.type === 'popstate' ? routing.pathname : _lastPathname, $lastType: e.type }) }; w.addEventListener("popstate", updateLocation); return routing; }; export const routing = createRouting(); export const CustomElementsRouter = ({transition, pathMap, noMatch, loadingIndicator, lazyMap}) => { transition = typeof transition === 'number' ? transition : transition === true ? 150 : 0; var initial = true, elem, getMountPoint, timeout, unsub, transitionStyle = `opacity ${transition}ms ease-in-out`, {routerSwitch} = routing, CE = customElements, clearMountingPoint = (e) => { let child = e.lastElementChild; while (child) (e.removeChild(child), child = e.lastElementChild) }, m = (parentNode, elem) => (clearMountingPoint(parentNode), appendChild(parentNode, elem)), mount = (elementName, parentNode) => { clearTimeout(timeout); elem = createElem(elementName); if (initial || !transition) return m(parentNode, elem); extend(parentNode.style, {transition: transitionStyle, opacity: 0}); timeout = setTimeout(() => { m(parentNode, elem); extend(parentNode.style, {transition: transitionStyle, opacity: 1}) }, transition ? transition + 10 : 0); }, mountLazy = (elementName, to) => { loadingIndicator && mount(loadingIndicator, to); lazyMap && lazyMap[elementName] && lazyMap[elementName]().then(() => CE.whenDefined(elementName).then(() => // in case of slow network and the user decides to locate somewhere else before // the request has finished, check that the pathMap matches the element name before exec the mount // so that the previously requested element doesn't mount over the current pathMap[location.pathname] === elementName && mount(elementName, to) )); }, doRoute = () => { let {next, toLast, noChange, replacedLast} = routerSwitch({pathMap, noMatch}), parentNode = getMountPoint && getMountPoint(); if (!(parentNode && parentNode.nodeName) || toLast || replacedLast || (noChange && !initial)) return; next && CE.get(next) ? mount(next, parentNode) : mountLazy(next, parentNode); }; return { mountTo: getNodeToMountToFunction => { unsub && unsub(); // you didn't follow directions!!! getMountPoint = getNodeToMountToFunction; doRoute(); initial = false; unsub = routing.$onChange(doRoute); return unsub; } } }; /* let router = CustomElementsRouter({ transition: 150, loadingIndicator: 'x-circle-loader', noMatch: '/0', pathMap: { '/0': 'intro-0', '/1': 'page-1', }, lazyMap: { 'intro-0': () => import('./pages/intro-0'), 'page-1': () => import('./pages/page-1'), }, }); ... lifeCycle() { return router.mountTo(() => this.page_ref); } ... */ <filename>src/schemas/index.js exports.LayoutSchema = require('./Layout'); exports.WebsiteSchema = require('./Website'); exports.FolderSchema = require('./Folder'); exports.ShelfSchema = require('./Shelf'); exports.RedirectSchema = require('./Redirect'); <filename>packages/ui/shared/src/hocs/tests/withBatchStartUpdate.test.js import React from "react"; import { UPLOADER_EVENTS } from "@rpldy/uploader"; import useUploadyContext from "../../hooks/useUploadyContext"; import withBatchStartUpdate from "../withBatchStartUpdate"; import mockContext from "../../tests/mocks/UploadyContext.mock"; jest.mock("../../hooks/useUploadyContext"); describe("withRequestPreSendUpdate tests", () => { beforeAll(() => { useUploadyContext.mockReturnValue(mockContext); }); beforeEach(() => { clearJestMocks( mockContext, ); }); it("should do nothing without id", () => { const MyComp = withBatchStartUpdate((props) => { return <div>{props.name}</div>; }); const wrapper = mount(<MyComp name="bob"/>); expect(wrapper).toHaveText("bob"); expect(mockContext.on).not.toHaveBeenCalled(); }); it("shouldn't unregister if no id on first render", () => { const MyComp = withBatchStartUpdate((props) => { return <div>{props.name}</div>; }); const wrapper = mount(<MyComp name="bob"/>); wrapper.setProps({ id: "bi1" }); expect(mockContext.on).toHaveBeenCalledTimes(1); expect(mockContext.off).not.toHaveBeenCalled(); }); it("should provide update data for matching item id", async () => { let handlerPromise; const items = [{ id: "bi0" }, { id: "bi1" }]; const options = { option: 1 }; const batch = { id: "b1", items }; const MockComp = jest.fn((props) => <div>{props.name}-{props.requestData?.batch.id || ""}</div>); mockContext.on.mockImplementationOnce((name, handler) => { handlerPromise = handler(batch, options); expect(handlerPromise).toBeInstanceOf(Promise); }); const MyComp = withBatchStartUpdate(MockComp); const wrapper = mount(<MyComp id={"b1"} name="bob"/>); expect(wrapper).toHaveText("bob-b1"); expect(MockComp).toHaveBeenCalledWith({ id: "b1", name: "bob", requestData: null, updateRequest: null, }, {}); expect(MockComp).toHaveBeenCalledWith({ id: "b1", name: "bob", requestData: { items, options, batch }, updateRequest: expect.any(Function), }, {}); expect(mockContext.on) .toHaveBeenCalledWith(UPLOADER_EVENTS.BATCH_START, expect.any(Function)); MockComp.mock.calls[1][0].updateRequest("test"); expect(mockContext.off) .toHaveBeenCalledWith(UPLOADER_EVENTS.BATCH_START, expect.any(Function)); const handlerResult = await handlerPromise; expect(handlerResult).toBe("test"); }); it("shouldn't provide update data for different item id", () => { const items = [{ id: "bi0" }, { id: "bi1" }]; const options = { option: 1 }; const batch = { id: "b1", items }; const MockComp = jest.fn((props) => <div>{props.id}-{props.name}-{props.requestData?.batch.id || ""}</div>); mockContext.on.mockImplementationOnce((name, handler) => { const handlerPromise = handler(batch, options); expect(handlerPromise).toBeUndefined(); }); const MyComp = withBatchStartUpdate(MockComp); const wrapper = mount(<MyComp id={"b2"} name="bob"/>); expect(wrapper).toHaveText("b2-bob-"); expect(mockContext.on) .toHaveBeenCalledWith(UPLOADER_EVENTS.BATCH_START, expect.any(Function)); expect(MockComp).toHaveBeenCalledTimes(1); expect(MockComp).toHaveBeenCalledWith({ id: "b2", name: "bob", requestData: null, updateRequest: null, }, {}); }); it("should unregister handler on id change", async () => { const items = [{ id: "bi0" }, { id: "bi1" }]; const options = { option: 1 }; const batch = { id: "b1", items }; const MockComp = jest.fn((props) => <div>{props.name}-{props.requestData?.batch.id || ""}</div>); mockContext.on.mockImplementationOnce((name, handler) => { const handlerPromise = handler(batch, options); expect(handlerPromise).toBeInstanceOf(Promise); }); const MyComp = withBatchStartUpdate(MockComp); const wrapper = mount(<MyComp id={"b1"} name="bob"/>); expect(mockContext.on) .toHaveBeenCalledWith(UPLOADER_EVENTS.BATCH_START, expect.any(Function)); wrapper.setProps({ id: "b2" }); expect(mockContext.off) .toHaveBeenCalledWith(UPLOADER_EVENTS.BATCH_START, expect.any(Function)); expect(mockContext.on).toHaveBeenCalledTimes(2); }); }); <gh_stars>0 /* global _vfbCountryConfig */ jQuery(document).ready(function($) { if ( $.fn.addressfield ) { var configuredFields = [ 'vfb-addresspart-address-1', 'vfb-addresspart-city', 'vfb-addresspart-province', 'vfb-addresspart-zip' ]; // On page load, localize the address block based on the country if ( $( '.vfb-address-block' ).length > 0 ) { $( '.vfb-address-block' ).each( function() { var addrID = $( this ).attr( 'id' ), addrCountry = $( this ).find( '.vfb-addresspart-country' ).val(); $( '#' + addrID ).addressfield( _vfbCountryConfig[addrCountry], configuredFields ); }); } // On country change $( '.vfb-addresspart-country' ).change( function() { var addressBlock = $( this ).closest( '.vfb-address-block' ); // Trigger the addressfield plugin with the country's data. addressBlock.addressfield( _vfbCountryConfig[this.value], configuredFields ); }); } });process.argv.map(::console.log); let hasOwnProp = Object.prototype.hasOwnProperty; let obj = { x: 100 }; obj::hasOwnProp("x");<gh_stars>0 const webpack = require("webpack"); const { merge } = require("webpack-merge"); const common = require("./webpack.common"); const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin"); const SpeedMeasurePlugin = require("speed-measure-webpack-plugin"); const smp = new SpeedMeasurePlugin(); //配置了 SpeedMeasurePlugin 后,热更新就无效了,会提示 runtime is undefined。 //解决方案:仅在分析构建速度时打开 SpeedMeasurePlugin 插件, const isNeedSpeed = false const config = merge(common, { // 开发模式 mode: "development", // 开发工具,开启 source map,编译调试 devtool: "eval-cheap-module-source-map", devServer: { // 告诉服务器从哪里提供内容,只有在你想要提供静态文件时才需要。 static: "./dist", hot: true, port: 8080, // 端口号 open: true, // 是否自动打开浏览器 // proxy: { // '/api': { // target: 'http://localhost:3000', // pathRewrite: { '^/api': '' }, // }, // }, }, plugins: [ new webpack.HotModuleReplacementPlugin(), new ReactRefreshWebpackPlugin(), ], }); module.exports = isNeedSpeed ? smp.wrap(config) : config; <gh_stars>0 class Phantom { rows; cols; direction; class; constructor(rows, cols, color) { this.rows = rows; this.cols = cols; this.direction = ""; this.class = color; } movePhantom() { this.direction = getRandom(0, 3); if (this.direction == 0) { this.cols++; //Right } else if (this.direction == 1) { this.rows++; //Down } else if (this.direction == 2) { this.cols--; //Left } else if (this.direction == 3) { this.rows--; //Up } this.testCollisionPhantom(); let div = document.createElement("div"); div.classList.add(this.class); div.style.gridRow = this.rows; div.style.gridColumn = this.cols; _grid.append(div); Pacman.stopGame(); } //Defines the limits for the PHANTOMS on the Map ##################################### testCollisionPhantom() { if (gridTable[this.rows - 1][this.cols - 1] == 0) { if (this.direction == 0) { this.cols--; //Right } else if (this.direction == 1) { this.rows--; //Down } else if (this.direction == 2) { this.cols++; //Left } else if (this.direction == 3) { this.rows++; //Up } } //Defines the middle limits if (this.cols > gridTable[0].length) { this.cols = 1; } if (this.cols < 1) { this.cols = gridTable[0].length; } } } <filename>introducao-javascript/js/remover-paciente.js var pacientes = document.querySelectorAll(".paciente"); // pacientes.forEach(function (paciente) { // paciente.addEventListener("dblclick",function(event){ // this.remove(); // }); // }); var tabela = document.querySelector("#tabela-pacientes"); tabela.addEventListener("dblclick",function(event){ console.log(event.target.tagName); var alvo = event.target; var paiAlvo = alvo.parentNode; paiAlvo.classList.add("fadeOut"); setTimeout(function(){ paiAlvo.remove(); }, 500); });var fs = require('fs'), path = require('path'), platform = require('platform'), parseClf = require('clf-parser'); /** * Find all the log files within the directory * * @param logsDirectory Directory of the logs * @param callback Functionr receiving an array of file paths */ var findLogs = function (logsDirectory, callback) { fs.readdir(logsDirectory, function (err, files) { files = files.filter(function (name) { return path.extname(name) == '.log'; }).map(function (name) { return path.join(logsDirectory, name) }); callback(files); }); }; /** * Read a log file * * @param logPath Path to the file * @param callback Function processing the data within the log */ var readLog = function (logPath, callback) { fs.readFile(logPath, 'utf8', function (err, data) { callback(data); }); }; /** * Map a log string to a log object * * @param logString * @returns {{remoteAddress: *, method: *, path: *, status: *, contentLength: *, referer: *, userAgent: *, user: *}} */ var mapLog = function (logString) { //var matches = LOG_REGEX.exec(logString); // First parse the log var parsedLog = parseClf(logString); var log = { remoteAddress: parsedLog.remote_addr, method: parsedLog.method, path: parsedLog.path, status: parsedLog.status, contentLength: parsedLog.body_bytes_sent, referer: parsedLog.http_referer, userAgent: parsedLog.http_user_agent, user: parsedLog.remote_user }; // Date var date = parsedLog.time_local; log.date = { day: date.getDate(), month: date.getMonth() + 1, year: date.getFullYear() }; log.time = { hour: date.getHours(), minute: date.getMinutes(), second: date.getSeconds() }; // Time taken parsing var lastQuote = logString.lastIndexOf('"'); if (lastQuote >= 0) { var responseTime = logString.substring(lastQuote + 1).trim(); if (responseTime) log.responseTime = parseFloat(responseTime); } // Parse the platform info var platformInfo = platform.parse(log.userAgent); log.browser = { name: platformInfo.name, version: platformInfo.version }; log.os = platformInfo.os; // OS X special platform handling if (log.os.family != null && log.os.family.substring(0, 4) == 'OS X') { if (log.os.version == null) log.os.version = log.os.family.substring(5); if (log.os.version != null) { var product = log.os.version; var firstPoint = product.indexOf('.'); var secondPoint = product.lastIndexOf('.'); if (firstPoint != secondPoint) product = product.substring(0, product.lastIndexOf('.')); log.os.family = 'OS X ' + product; } } return log; }; /** * Process an array of log strings * * @param logs * @param filename * @returns {Array} */ var processLogs = function (logStrings, filename) { return logStrings .split('\n') .filter(function (log) { return log; }) .map(function (log) { log = mapLog(log); log.filename = filename; return log; }); }; /** * Log Processor * * It will find all the logs within the directory, process them and store them into the DB * * @param logsDirectory Directory of the logs * @param logRepository LogRepository * @returns {Function} * @constructor */ var LogProcessor = function (logsDirectory, logRepository) { /** * Process function */ return function () { // Start the analysis var analysis = { date: new Date(), files: [] } logRepository.insertAnalysis(analysis, function (analysis) { // Find log files findLogs(logsDirectory, function (files) { // Process each file files.forEach(function (file) { readLog(file, function (logs) { logs = processLogs(logs, file) logRepository.removeLogsByFilename(file); logRepository.insertLogs(logs); logRepository.addProcessedFileToAnalysis(analysis, { filename: file, logs: logs.length }) }); }); }); }); }; }; module.exports = LogProcessor;<reponame>lautarobock/brew-o-matic (function() { var index = angular.module('login',['calculator']); index.run(function($rootScope) { $rootScope.loginSuccess = false; }); index.controller("LoginController",function($scope,$rootScope,User,Notification,notificationData,pushListener,CalculatorPopup) { $scope.openCalcPopup = function() { CalculatorPopup.open(); }; $scope.$on('g+login',function(event,authResult) { if ( authResult == null ) { $rootScope.loginSuccess = true; $scope.loginError = ''; $rootScope.$apply(); } else if ( authResult['access_token']) { // Autorizado correctamente // Oculta el botón de inicio de sesión ahora que el usuario está autorizado, por ejemplo: //Guardo el token gapi.auth.setToken(authResult); //Pido los datos del usuario gapi.client.load('oauth2', 'v2', function() { var request = gapi.client.oauth2.userinfo.get(); request.execute(function (obj){ User.getByGoogleId({ id:obj.id, name: obj.name },function(user){ $rootScope.loginSuccess = true; $rootScope.user = user; console.log(user); }); }); }); } else if ( authResult.googleId ) { //En este caso viene de login interno de la app mobile (en un iframe) User.getByGoogleId({ id: authResult.googleId, name: authResult.name },function(user){ $rootScope.loginSuccess = true; $rootScope.user = user; console.log(user); }); } else if ( authResult['error'] == "immediate_failed") { $rootScope.loginSuccess = true; $scope.loginError = ''; $rootScope.$apply(); } else if ( authResult['error'] ) { $rootScope.loginSuccess = true; $scope.loginError = authResult['error']; $scope.$apply(); $rootScope.$apply(); console.log('There was an error: ' + authResult['error']); } else { $rootScope.loginSuccess = true; $scope.loginError = JSON.stringify(authResult); $scope.$apply(); $rootScope.$apply(); console.log('Error inesperado'); } }); $scope.googleSignIn = function() { googleSignIn(); }; notificationData.listener = function() { $scope.notificationClass = ''; $scope.notificationCount = 0; }; notificationData.updateListener = function() { $scope.findNotificationsCount(); }; $scope.notificationClass = ''; $scope.notificationCount = 0; $scope.$watch('user',function(user) { if (user) { $scope.findNotificationsCount(); //setInterval($scope.findNotificationsCount,60*1000); pushListener.on("NOTIFICATION_ADD_" + user._id, function(data) { console.log("INFO","New Notification (Count)", data); $scope.findNotificationsCount(); }); } }); $scope.findNotificationsCount = function() { console.log("Actualizacion notificaciones"); Notification.findNews(function(nots) { $scope.notificationCount = nots.length; $scope.notificationClass = nots.length != 0 ? 'gt-notificaction-count-alert' : ''; }); }; }); })();<filename>website/app.js /* Global Variables */ const COUNTRY_CODES_URL = '/country-codes'; const NEW_ENTRY_URL = '/new-entry'; const RECENT_ENTRIES_URL = '/recent-entries'; let recentEntriesData = []; // API requests const getWeatherData = async (url = '') => { const res = await fetch(url, { method: 'GET', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' } }) try { return await res.json(); } catch (e) { console.log(e); } } const postEntry = async (url = '', data = {}) => { const res = await fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), // body data type must match "Content-Type" header }); try { return await res.json(); } catch (e) { console.log("error", e); } } // Get country codes from server const getCountyCodes = async (url = '') => { const res = await fetch(url, { method: 'GET', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' } }) try { return await res.json(); } catch (e) { console.log("error", e); } } // Get current location from browser api and init page function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position) => { const url = `/coordinates?lat=${position.coords.latitude}&lon=${position.coords.longitude}`; getWeatherData(url) .then((data) => { drawChart(data); recentEntries().then((data) => { recentEntriesData = [...data]; generateEntries(recentEntriesData); }); }); }); } else { const msgNoGeolocation = document.getElementById('msgNoGeolocation'); msgNoGeolocation.innerHTML = "Geolocation is not supported by this browser."; } } // Get recent entries form node server const recentEntries = async () => { const res = await fetch(RECENT_ENTRIES_URL, { method: 'GET', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, }) try { return await res.json(); } catch (e) { console.log("error", e); } } function generateEntries(entries) { if (!entries || !entries.length > 0) { return; } const entryList = document.getElementById('entryList'); let templateElemStr = ''; entries.forEach((entry, index) => { const newEntry = `<li onclick="loadEntry(${index})" class="entryItem"> <span><span class="entryLabel">Location: </span>${entry.name}</span><br> <span><span class="entryLabel">Period: </span>${entry.date[0]} - ${entry.date[6]}</span><br> <span><span class="entryLabel">Feelings: </span>${entry.feelings}</span> </li>`; templateElemStr = `${templateElemStr}${newEntry}`; }) entryList.innerHTML = ''; if (templateElemStr) { document.getElementById('entry').style.display = 'block'; } entryList.insertAdjacentHTML("beforeend", templateElemStr); } function generateCountryCodeDropdownList(countryCodes) { const dropdownElem = document.getElementById('countryCode'); let templateElemStr = `<option value=""> choose a country</option>`; for (let i = 0; i < countryCodes.length; i++) { const newDropdownItem = `<option value="${countryCodes[i].alpha2Code}">${countryCodes[i].name}</option>`; templateElemStr = `${templateElemStr}${newDropdownItem}`; } dropdownElem.insertAdjacentHTML("beforeend", templateElemStr); } // Load entry form recent entries list function loadEntry(index) { drawChart(recentEntriesData[index]); window.scrollTo({top: 0, behavior: 'smooth'}); } function drawChart(data) { const canvas = document.getElementById("weatherChart"); canvas.style.backgroundColor = 'rgba(242, 53, 87, 0.1)'; const ctx = canvas.getContext('2d'); new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: data.date, datasets: [ { label: 'min ℃', borderColor: 'rgb(34, 178, 218)', fill: false, data: data.minTemp }, { label: 'max ℃', borderColor: 'rgb(242, 53, 87)', fill: false, data: data.maxTemp } ] }, // Configuration options go here options: { title: { display: true, text: `Temperature in ${data.name}` }, responsive: true, maintainAspectRatio: false } }); } function submitForm(ev) { ev.preventDefault(); const elements = ev.target.elements; let obj = {}; for (let item of elements) { obj[item.name] = item.value; } postEntry(NEW_ENTRY_URL, obj) .then((data) => { if (!data) { alert(`No data could be found for your current entries`); } drawChart(data); recentEntries().then((data) => { recentEntriesData = [...data]; generateEntries(recentEntriesData); }); window.scrollTo({top: 0, behavior: 'smooth'}); }); } setTimeout(() => { getCountyCodes(COUNTRY_CODES_URL) .then((countryCodes) => { generateCountryCodeDropdownList(countryCodes); }); getLocation(); document.getElementById('weatherForm').addEventListener('submit', submitForm) }, 0); import React, { forwardRef } from 'react'; import PropTypes from 'prop-types'; const HouseDoor = forwardRef(({ color, size, ...rest }, ref) => { return ( <svg ref={ref} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width={size} height={size} fill={color} {...rest} > <path d="M8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4.5a.5.5 0 0 0 .5-.5v-4h2v4a.5.5 0 0 0 .5.5H14a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293L8.354 1.146zM2.5 14V7.707l5.5-5.5 5.5 5.5V14H10v-4a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5v4H2.5z" /> </svg> ); }); HouseDoor.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; HouseDoor.defaultProps = { color: 'currentColor', size: '1em', }; export default HouseDoor; <reponame>Dante83/A-Terra-Incognito export function configureAddNormals(config){ config.addNodeType({ type: "addNormals", label: "Add Normals", description: "Combines two normal map vectors in world space.", initialWidth: 150, inputs: ports => [ ports.vec3({name: 'normalVector1', label: 'Normal 1'}), ports.float({name: 'normalStrength1', label: 'Normal 1 Strength', defaultValue: 1.0}), ports.vec3({name: 'normalVector2', label: 'Normal 2'}), ports.float({name: 'normalStrength2', label: 'Normal 2 Strength', defaultValue: 1.0}) ], outputs: ports => [ ports.vec3({name: 'vec3', label: 'Combined Normal'}) ] }); }; <gh_stars>1-10 /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2015, Joyent, Inc. */ /* * tst.jsonparser.js: basic test of json parser stream */ var mod_assert = require('assert'); var JsonParserStream = require('../lib/vstream-json-parser'); var stream = new JsonParserStream(); var warnings, objects; var done = false; process.on('exit', function () { mod_assert.ok(done, 'premature exit'); }); warnings = []; objects = []; stream.on('warn', function (context, kind, error) { warnings.push({ 'context': context, 'kind': kind, 'error': error }); }); stream.on('data', function (obj) { objects.push(obj); }); stream.on('end', function () { mod_assert.equal(warnings.length, 2); mod_assert.equal(warnings[0].context.label(), 'json parser input 3: value \'null\''); mod_assert.equal(warnings[0].kind, 'null value'); mod_assert.equal(warnings[0].error.message, '"null" is not allowed'); mod_assert.equal(warnings[1].context.label(), 'json parser input 5: value \'{\''); mod_assert.equal(warnings[1].kind, 'invalid json'); mod_assert.equal(warnings[1].error.message, 'Unexpected end of input'); mod_assert.deepEqual(objects, [ {}, { 'a': 'b' }, { 'a': 'b', 'c': null }, { 'poochie': 'dog' } ]); done = true; console.log('TEST PASSED'); }); stream.write('{}'); stream.write('{ "a": "b" }'); stream.write('null'); stream.write('{ "a": "b", "c": null }'); stream.write('{'); stream.end('{ "poochie": "dog" }'); import R from 'ramda' import React from 'react' import {view as viewForm} from './Form' import {Show} from './constants' import {Form as UpdateForm, SetFilter, ToggleCompleted} from './actions' import {forward} from '../../elmar' const filters = { [Show.All]: _ => true, [Show.Active]: x => !x.completed, [Show.Completed]: x => x.completed } const todoStyle = todo => ({ textDecoration: todo.completed ? 'line-through' : 'none', cursor: 'pointer' }) const viewTodo = (signal, todo) => ( <li key={todo.id}> <span onClick={signal(ToggleCompleted(todo.id))} style={todoStyle(todo)}>{todo.text}</span> </li> ) export default (signal, model) => ( <div> {viewForm(forward(signal, UpdateForm), model.form)} <ul>{model.todos.filter(filters[model.show]).map(R.partial(viewTodo, [signal]))}</ul> <p> <button onClick={signal(SetFilter(Show.All))}>Show All</button> <br/> <button onClick={signal(SetFilter(Show.Active))}>Show Active</button> <br/> <button onClick={signal(SetFilter(Show.Completed))}>Show Completed</button> </p> </div> ) /** * Created by daniel on 4/17/17. */ import GatesManager from '../../../../app/utils/HardwareSimulator/Gates/GatesManager'; import HDLTokenizer from '../../../../app/utils/HardwareSimulator/Gates/HDLTokenizer'; import GateClass from '../../../../app/utils/HardwareSimulator/Gates/GateCalss'; describe('And', () => { let instance; beforeAll(() => { const gm = GatesManager.getInstance(); gm.setBuiltInDir('/Users/daniel/Projects/Nand2TetrisElectron/resources/builtInChips'); gm.setWorkingDir('/Users/daniel/Projects/Nand2TetrisElectron/resources'); const input = new HDLTokenizer(`${__dirname}/../assets/And.hdl`); const result = GateClass.readHDL(input, 'And'); instance = result; }) it('input Pins Name', () => { expect(instance.inputPinsInfo.map(o => o.name)).toEqual(['a', 'b']); }); it('input Pins widths', () => { expect(instance.inputPinsInfo.map(o => o.width)).toEqual([1, 1]); }); it('names to numbers', () => { expect(instance.namesToNumbers).toEqual({ a: 0, b: 1, nandout: 0, out: 0 }); }); it('names to types', () => { expect(instance.namesToTypes).toEqual({ a: 1, b: 1, nandout: 3, out: 2 }); }); }); <filename>src/stores/providers/video.provider.js import React, { useState } from "react"; import VideoContext from "../contexts/video.context"; const VideoProvider = ({ children }) => { const [showVideoOverlay, toggleVideoOverlay] = useState(false); const [selectedVideo, setVideoId] = useState(null); const [videoPlaying, toggleVideoPlay] = useState(false); const [selectedMatchVideos, setSelectedMatchVideos] = useState([]); const hideVideo = () => { toggleVideoOverlay(false); }; return ( <VideoContext.Provider value={{ showVideoOverlay, toggleVideoOverlay, videoPlaying, toggleVideoPlay, selectedVideo, setVideoId, selectedMatchVideos, setSelectedMatchVideos, hideVideo }} > {children} </VideoContext.Provider> ); }; export default VideoProvider; import Surface from './Surface'; const surface = new Surface('canvas'); surface.buildDummy(); document.querySelector('[name="exportAsJson"]').addEventListener('click', () => surface.exportAsJson()); <filename>storage/src/mock/category.js<gh_stars>0 const pdfFiles = [ { type: 'folder', name: 'MyFolder', }, { type: 'pdf', name: 'YouFile', } ]; const pptFiles = [ { type: 'folder', name: 'Folder1', }, { type: 'ppt', name: 'pptFile', }, ]; const homeworkFiles = [ { type: 'word', name: 'MyWord', }, { type: 'text', name: 'MyTXT', } ]; const commentFiles = [ { type: 'folder', name: 'MyFolder', }, { type: 'excel', name: 'MyExcel', }, { type: 'file', name: 'YouFile', } ]; const examFiles = [ { type: 'folder', name: 'examFolder', }, { type: 'audio', name: 'myAudio', } ]; const mindmapFiles = [ { type: 'folder', name: 'mindmapFolder', }, { type: 'video', name: 'myVideo', } ]; const otherFiles = [ { type: 'folder', name: 'OtherFolder', }, { type: 'image', name: 'OtherFile', } ]; export default { pdfFiles, pptFiles, homeworkFiles, commentFiles, examFiles, mindmapFiles, otherFiles, }; // for local dev only const express = require('express') const port = 8080 const app = express() app.use(express.static('src')) app.listen(port, () => { console.log(`listening on port ${port}`) }) <gh_stars>1-10 /* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://yuilibrary.com/license/ */ var util = require('../util'), log = require('../log'), git = require('../git'), config = require('../config'), proxy = require('../proxy'), api = require('../api'), path = require('path'), mods; config.register('simple-pull', 'set to true to automatically use the last commit when issuing a pull request'); mods = { yui: true, init: function(options) { this.user = 'yui'; this.repo = 'yui3'; this.simple = config.get('simple-pull'); if (options.parsed.user) { this.user = options.parsed.user; } if (options.parsed.simple) { this.simple = true; } if (!util.isYUI()) { log.bail('command only valid in the yui3 repo'); } if (!util.hasGithub()) { log.bail('github is not linked yet: yogi gh'); } var module = util.findModule(true); this.module = module; if (!module) { log.bail('are you in a module directory?'); } log.info('issuing a pull request to ' + this.user + ' for: ' + module.name); if (this.simple) { log.info('simple pull request, using last commit as message'); } this.request(); }, submit: function() { var self = this; log.info('looking up owner of ' + this.module.name); api.get('/components/' + this.module.name + '/author', function(err, author) { if (author && author.components && author.components.length) { var owner = author.components[0].author, lookup = (Array.isArray(owner)) ? owner : [owner]; log.info('found owner: ' + owner); log.debug('looking up user info'); api.get('/user/name/' + lookup.join(';') + '/github', function(err, github) { var owners = []; if (github && Array.isArray(github)) { github.forEach(function(i) { if (i.github) { owners.push(i.github); } }); } else if (github && github.github) { owners = [github.github]; } if (owners.length) { log.debug('found github username(s): ' + owners); owners.forEach(function(name) { self.body += '\nyogi pinging ' + self.module.name + ' owner: @' + name + '\n'; }); } else { log.warn('failed to locate default owner, submitting anyway'); } self.send(); }); } else { log.warn('failed to locate default owner, submitting anyway'); self.send(); } }); }, send: function() { log.info('submitting pull request'); var self = this, gh_user = config.get('gh_user'), gh_token = config.get('gh_token'), tag = '\nsubmitted with yogi', json = { title: self.title, body: self.body + tag, head: gh_user + ':' + self.branch, base: 'master' }, body = JSON.stringify(json), url = 'https:/'+'/api.github.com/repos/' + self.user + '/' + self.repo + '/pulls'; log.debug('POST ' + url); proxy.request().post({ url: url, headers: { 'Content-Length': body.length, 'Content-Type' : 'application/json', 'User-Agent': 'yogi CLI tool', 'Authorization': 'bearer ' + gh_token }, body: body }, function(err, res) { if (err) { log.bail(err); } var json = JSON.parse(res.body); if (json.errors) { json.errors.forEach(function(i) { log.error(i.message); }); } else { log.info('pull request successful'); log.log(json.html_url); } }); }, confirm: function() { var self = this; log.info('does this look correct?'); log.log('user: ' + this.user); log.log('repo: ' + this.repo); log.log('branch: ' + this.branch); log.log('title: ' + this.title); log.log('body: -------------------------'); log.log(this.body); util.prompt('ok? [y/N] ', function(ans) { if (ans.match(/^y(es)?$/i)) { self.submit(); } else { log.bail('bailing'); } }); }, request: function() { var self = this; git.status(function(status) { if (status && status.length) { log.bail('git root is dirty, please commit first'); } git.branch(function(branch) { log.info('using branch ' + branch); self.branch = branch; if (branch === 'master') { log.warn('you really really should be using a feature branch!'); util.prompt('are you sure you want to use the master branch? [y/N] ', function(ans) { ans = ans.toLowerCase() || 'n'; if (ans !== 'y') { log.bail('bailing'); } self.askTitle(); }); } else { self.askTitle(); } }); }); }, askTitle: function() { var self = this; git.log(function(logs) { var title = logs[0].note; if (self.simple && title) { self.title = title; self.body = ''; self.confirm(); } else { log.info('use the last commit as the title? [y/N] '); util.prompt('[' + title + ']: ', function(ans) { if (ans.match(/^y(es)?$/i)) { self.title = title; self.askBody(); } else { util.prompt('pull request title: ', function(title) { self.title = title; self.askBody(); }); } }); } }); }, askBody: function() { var defaultFile = path.join(__dirname, '../../configs/pr/default.txt'), self = this; util.longPrompt(defaultFile, function(ans) { self.body = ans; self.confirm(); }); }, help: function() { return [ 'pullrequest', 'submit a pull request to the yui/yui3 project', '--user <name> to send to another user', '--simple (use last commit as message)' ]; } }; util.mix(exports, mods); <filename>graceful-grasshoppers/pyspace-frontend/src/models/user.js<gh_stars>10-100 export default class User { constructor(details) { this.id = details.id; this.username = details.username; this.password = <PASSWORD>; this.confirm_password = <PASSWORD>_password; this.email = details.email; this.name = details.name; this.age = details.age; this.friends = details.friends; this.about = details.about; this.greeting = details.greeting; this.profile_picture = details.profilePicture; this.profile_comments = details.profileComments; this.latest_post = {title: null, content: null}; } } /** * Copyright 2015 LaxarJS * Released under the MIT license * http://www.laxarjs.org */ define( [ '../hal_http_client', 'laxar/laxar_testing', 'angular-mocks', './spec_data' ], function( halHttp, ax, ngMocks, specData ) { 'use strict'; describe( 'A hal http client', function() { var BASE_URL = 'http://host:1234'; var halClient; var $http; var $httpBackend; var $injector; var $rootScope; var data; var responseTransformerSpy; var onSpy5xxGlobal; var onSpy200; var onSpy2xx; var onSpy404; var onSpyXxx; var thenResolvedSpy; var thenRejectedSpy; beforeEach( function() { ngMocks.inject( function( _$httpBackend_, _$injector_, _$rootScope_ ) { $httpBackend = _$httpBackend_; $injector = _$injector_; $rootScope = _$rootScope_; } ); responseTransformerSpy = jasmine .createSpy( 'responseTransformerSpy' ) .andCallFake( function( response ) { return response; } ); onSpy5xxGlobal = jasmine.createSpy( 'onSpy5xxGlobal' ); $http = jasmine.createSpy( 'httpSpy' ).andCallFake( $injector.get( '$http' ) ); halClient = halHttp.create( $http, $injector.get( '$q' ), { headers: { 'Accept-Language': 'de' }, on: { '5xx': onSpy5xxGlobal }, responseTransformer: responseTransformerSpy } ); data = ax.object.deepClone( specData ); onSpy200 = jasmine.createSpy( 'onSpy200' ); onSpy2xx = jasmine.createSpy( 'onSpy2xx' ); onSpy404 = jasmine.createSpy( 'onSpy404' ); onSpyXxx = jasmine.createSpy( 'onSpyXxx' ); thenResolvedSpy = jasmine.createSpy( 'thenResolvedSpy' ); thenRejectedSpy = jasmine.createSpy( 'thenRejectedSpy' ); addMatchers( this ); } ); //////////////////////////////////////////////////////////////////////////////////////////////////////// afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); } ); //////////////////////////////////////////////////////////////////////////////////////////////////////// it( 'has a method to remove hal specific properties (ATP-9509)', function() { expect( halClient.removeHalKeys( { _links: { self: 'xxx' }, _embedded: { rel: { property: 1 } }, property: 42, car: { color: 'red' } } ) ).toEqual( { property: 42, car: { color: 'red' } } ); } ); //////////////////////////////////////////////////////////////////////////////////////////////////////// describe( 'on successful GET', function() { beforeEach( function() { $httpBackend.expectGET( BASE_URL + '/resource' ).respond( 200, { _links: { self: { href: BASE_URL + '/resource' } }, value: 123 }, { etag: 'myEtag' } ); var promise = halClient.get( BASE_URL + '/resource', { headers: { 'X-Custom-Header': 'such header' } } ); promise.then( thenResolvedSpy, thenRejectedSpy ); promise.on( { '200': onSpy200, '2xx': onSpy2xx, '404': onSpy404 } ); $httpBackend.flush(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'calls the configured response transformer', function() { expect( responseTransformerSpy ).toHaveBeenCalled(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'resolves the simple promise', function() { expect( thenResolvedSpy ).toHaveBeenCalled(); expect( thenRejectedSpy ).not.toHaveBeenCalled(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'calls the most specific matching on handler', function() { expect( onSpy200 ).toHaveBeenCalled(); expect( onSpy2xx ).not.toHaveBeenCalled(); expect( onSpy404 ).not.toHaveBeenCalled(); expect( onSpy5xxGlobal ).not.toHaveBeenCalled(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'sends default safe, global and local headers along', function() { var callArgs = $http.calls[0].args[0]; expect( callArgs.headers ).toEqual( { 'Accept': 'application/hal+json', 'Accept-Language': 'de', 'X-Custom-Header': 'such header' } ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// describe( 'when getting the same resource again', function() { beforeEach( function() { thenResolvedSpy.reset(); $http.reset(); $httpBackend.expectGET( BASE_URL + '/resource' ).respond( 304 ); halClient.get( BASE_URL + '/resource' ).then( thenResolvedSpy ); $httpBackend.flush(); } ); ////////////////////////////////////////////////////////////////////////////////////////////////// it( 'the client sends an if-none-match header with the previous etag', function() { expect( $http.calls[0].args[0].headers[ 'If-None-Match' ] ).toEqual( 'myEtag' ); } ); ////////////////////////////////////////////////////////////////////////////////////////////////// it( 'serves the value from cache', function() { expect( thenResolvedSpy.calls[0].args[0].data.value ).toEqual( 123 ); } ); } ); } ); //////////////////////////////////////////////////////////////////////////////////////////////////////// describe( 'on failed GET with error 404', function() { beforeEach( function() { $httpBackend.expectGET( BASE_URL + '/resource' ).respond( 404 ); var promise = halClient.get( BASE_URL + '/resource' ); promise.then( thenResolvedSpy, thenRejectedSpy ); promise.on( { '200': onSpy200, '2xx': onSpy2xx, '404': onSpy404 } ); $httpBackend.flush(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'rejects the simple promise', function() { expect( thenResolvedSpy ).not.toHaveBeenCalled(); expect( thenRejectedSpy ).toHaveBeenCalled(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'calls the most specific matching on handler', function() { expect( onSpy200 ).not.toHaveBeenCalled(); expect( onSpy2xx ).not.toHaveBeenCalled(); expect( onSpy404 ).toHaveBeenCalled(); expect( onSpy5xxGlobal ).not.toHaveBeenCalled(); } ); } ); //////////////////////////////////////////////////////////////////////////////////////////////////////// describe( 'on failed GET with error 500', function() { beforeEach( function() { $httpBackend.expectGET( BASE_URL + '/resource' ).respond( 500 ); var promise = halClient.get( BASE_URL + '/resource' ); promise.then( thenResolvedSpy, thenRejectedSpy ); promise.on( { '200': onSpy200, '2xx': onSpy2xx, '404': onSpy404 } ); $httpBackend.flush(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'rejects the simple promise', function() { expect( thenResolvedSpy ).not.toHaveBeenCalled(); expect( thenRejectedSpy ).toHaveBeenCalled(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'calls the most specific matching on handler (in this case the global handler)', function() { expect( onSpy200 ).not.toHaveBeenCalled(); expect( onSpy2xx ).not.toHaveBeenCalled(); expect( onSpy404 ).not.toHaveBeenCalled(); expect( onSpy5xxGlobal ).toHaveBeenCalled(); } ); } ); //////////////////////////////////////////////////////////////////////////////////////////////////////// describe( 'for multiple GETs during the same tick', function() { var httpSpy; var promise1; var promise2; var promise3; var promise4; var promise5; var deferred; beforeEach( function() { var $q = $injector.get( '$q' ); deferred = $q.defer(); httpSpy = jasmine.createSpy( '$http' ).andReturn( deferred.promise ); halClient = halHttp.create( httpSpy, $q, { headers: { 'Accept-Language': 'de' }, on: { '5xx': onSpy5xxGlobal }, responseTransformer: responseTransformerSpy } ); promise1 = halClient.get( BASE_URL + '/resource' ); promise2 = halClient.get( BASE_URL + '/resource' ); promise3 = halClient.get( BASE_URL + '/resource' ); promise4 = halClient.get( BASE_URL + '/resource', { headers: { 'If-None-Match': 'abc123' } } ); promise5 = halClient.get( BASE_URL + '/resource', { headers: { 'If-None-Match': 'abc123' } } ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'returns the promise of the first request when url and headers match (jira ATP-9313)', function() { expect( promise1 ).toBe( promise2 ); expect( promise2 ).toBe( promise3 ); expect( promise4 ).toBe( promise5 ); expect( promise1 ).not.toBe( promise4 ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'returns a new promise in the next tick (jira ATP-9313)', function() { deferred.resolve( { status: 200, headers: function() {} } ); $rootScope.$digest(); expect( promise1 ).not.toBe( halClient.get( BASE_URL + '/resource' ) ); } ); } ); //////////////////////////////////////////////////////////////////////////////////////////////////////// [ 'PUT', 'POST', 'PATCH', 'DELETE' ].forEach( function( method ) { describe( 'on successful ' + method, function() { beforeEach( function() { $httpBackend[ 'expect' + method ]( BASE_URL + '/resource' ).respond( 200 ); var promise; if( method === 'DELETE' ) { promise = halClient.del( BASE_URL + '/resource', { headers: { 'X-Custom-Header': 'such header' } } ); } else { promise = halClient[ method.toLowerCase() ]( BASE_URL + '/resource', { my: 'data' }, { headers: { 'X-Custom-Header': 'such header' } } ); } promise.then( thenResolvedSpy, thenRejectedSpy ); promise.on( { '200': onSpy200, '2xx': onSpy2xx, '404': onSpy404 } ); $httpBackend.flush(); } ); ////////////////////////////////////////////////////////////////////////////////////////////////// it( 'calls the configured response transformer', function() { expect( responseTransformerSpy ).toHaveBeenCalled(); } ); ////////////////////////////////////////////////////////////////////////////////////////////////// it( 'resolves the simple promise', function() { expect( thenResolvedSpy ).toHaveBeenCalled(); expect( thenRejectedSpy ).not.toHaveBeenCalled(); } ); ////////////////////////////////////////////////////////////////////////////////////////////////// it( 'calls the most specific matching on handler', function() { expect( onSpy200 ).toHaveBeenCalled(); expect( onSpy2xx ).not.toHaveBeenCalled(); expect( onSpy404 ).not.toHaveBeenCalled(); expect( onSpy5xxGlobal ).not.toHaveBeenCalled(); } ); ////////////////////////////////////////////////////////////////////////////////////////////////// it( 'sends default unsafe, global and local headers along', function() { var callArgs = $http.calls[0].args[0]; expect( callArgs.headers ).toEqual( { 'Accept': 'application/hal+json', 'Accept-Language': 'de', 'Content-Type': method === 'PATCH' ? 'application/json-patch+json' : 'application/json', 'X-Custom-Header': 'such header' } ); } ); ////////////////////////////////////////////////////////////////////////////////////////////////// if( method !== 'DELETE' ) { it( 'sends the data as request body', function() { var callArgs = $http.calls[0].args[0]; expect( callArgs.data ).toEqual( { my: 'data' } ); } ); } } ); } ); //////////////////////////////////////////////////////////////////////////////////////////////////////// describe( 'with follow relation functions', function() { var meHalResource; beforeEach( function() { meHalResource = data.ROOT; $httpBackend.whenGET( data.baseUrl + '/me/cars' ).respond( 200, data.CARS ); $httpBackend.whenGET( data.baseUrl + '/me/cars/0' ).respond( 200, data.CARS._embedded.car[0] ); $httpBackend.whenGET( data.baseUrl + '/me/cars/1' ).respond( 200, data.CARS._embedded.car[1] ); $httpBackend.whenGET( data.baseUrl + '/me/pets' ).respond( 200, data.PETS ); $httpBackend.whenGET( data.baseUrl + '/me/pets/0' ).respond( 200, data.PETS._embedded.pet[0] ); spyOn( halClient, 'follow' ).andCallThrough(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'has a function to test if a relation can be followed (ATP-9441)', function() { expect( halClient.canFollow( { }, 'relation' ) ).toBe( false ); expect( halClient.canFollow( { _links: { relation: {} } }, 'relation' ) ).toBe( true ); expect( halClient.canFollow( { _embedded: { relation: {} } }, 'relation' ) ).toBe( true ); expect( halClient.canFollow( { _links: { relation: {} }, _embedded: { relation: {} } }, 'relation' ) ) .toBe( true ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'has a function to retrieve the url of the first entry from a relation (ATP-9503)', function() { expect( halClient.firstRelationHref( { }, 'relation' ) ).toBe( null ); expect( halClient.firstRelationHref( { _links: { relation: { href: 'fancyUrl' } } }, 'relation' ) ).toEqual( 'fancyUrl' ); expect( halClient.firstRelationHref( { _links: { relation: [ { href: 'fancyUrl' }, { href: 'tooFancyUrl' } ] } }, 'relation' ) ).toEqual( 'fancyUrl' ); expect( halClient.firstRelationHref( { _embedded: { relation: { _links: { self: { href: 'embeddedFancyUrl' } } } } }, 'relation' ) ).toEqual( 'embeddedFancyUrl' ); expect( halClient.firstRelationHref( { _links: { relation: { href: 'linkedFancyUrl' } }, _embedded: { relation: { _links: { self: { href: 'embeddedFancyUrl' } } } } }, 'relation' ) ).toEqual( 'linkedFancyUrl' ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'fetches resources from the representation if already embedded', function() { halClient.follow( meHalResource, 'address' ).then( thenResolvedSpy, thenRejectedSpy ); $rootScope.$digest(); expect( $http ).not.toHaveBeenCalled(); expect( thenResolvedSpy ).toHaveBeenCalledWithProperties( { status: 200, data: meHalResource._embedded.address } ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'calls the most specific matching on handler', function() { halClient.follow( meHalResource, 'address' ).on( { '200': onSpy200, '2xx': onSpy2xx } ); $rootScope.$digest(); expect( onSpy200 ).toHaveBeenCalledWithProperties( { status: 200, data: meHalResource._embedded.address } ); expect( onSpy2xx ).not.toHaveBeenCalled(); expect( onSpy5xxGlobal ).not.toHaveBeenCalled(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'makes a GET request for a resource that is not embedded', function() { halClient.follow( meHalResource, 'cars' ).then( thenResolvedSpy, thenRejectedSpy ); $httpBackend.flush(); expect( $http ).toHaveBeenCalledWithProperties( { url: data.baseUrl + '/me/cars', method: 'GET' } ); expect( thenResolvedSpy ).toHaveBeenCalledWithProperties( { status: 200, data: data.CARS } ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'follows a complete collection if followAll is true', function() { halClient.follow( meHalResource, 'car', { followAll: true } ) .then( thenResolvedSpy, thenRejectedSpy ); $httpBackend.flush(); expect( $http ).toHaveBeenCalledWithProperties( { url: data.baseUrl + '/me/cars/0', method: 'GET' } ); expect( $http ).toHaveBeenCalledWithProperties( { url: data.baseUrl + '/me/cars/1', method: 'GET' } ); var callArgs = thenResolvedSpy.calls[0].args[0]; expect( callArgs[0].status ).toEqual( 200 ); expect( callArgs[0].data ).toEqual( data.CARS._embedded.car[0] ); expect( callArgs[1].status ).toEqual( 200 ); expect( callArgs[1].data ).toEqual( data.CARS._embedded.car[1] ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'follows a complete collection if followAll is true although there is only one link', function() { halClient.follow( meHalResource, 'pet', { followAll: true } ) .then( thenResolvedSpy, thenRejectedSpy ); $httpBackend.flush(); expect( $http ).toHaveBeenCalledWithProperties( { url: data.baseUrl + '/me/pets/0', method: 'GET' } ); var callArgs = thenResolvedSpy.calls[0].args[0]; expect( callArgs[0].status ).toEqual( 200 ); expect( callArgs[0].data ).toEqual( data.PETS._embedded.pet[0] ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'defines followAll as shortcut for follow with followAll being true', function() { halClient.followAll( meHalResource, 'pet', { headers: { 'X-More-Headers': 'yay' } } ) .then( thenResolvedSpy, thenRejectedSpy ); $httpBackend.flush(); expect( $http ).toHaveBeenCalledWithProperties( { url: data.baseUrl + '/me/pets/0', method: 'GET', headers: { Accept: 'application/hal+json', 'Accept-Language': 'de', 'X-More-Headers': 'yay' } } ); var callArgs = thenResolvedSpy.calls[0].args[0]; expect( callArgs[0].status ).toEqual( 200 ); expect( callArgs[0].data ).toEqual( data.PETS._embedded.pet[0] ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'can follow a set of embedded resources', function() { halClient.followAll( data.CARS, 'car' ).then( thenResolvedSpy, thenRejectedSpy ); $rootScope.$digest(); var callArgs = thenResolvedSpy.calls[0].args[0]; expect( callArgs[0].status ).toEqual( 200 ); expect( callArgs[0].data ).toEqual( data.CARS._embedded.car[0] ); expect( callArgs[1].status ).toEqual( 200 ); expect( callArgs[1].data ).toEqual( data.CARS._embedded.car[1] ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'can follow a set of embedded resources although there is only one element embedded (jira ATP-9300)', function() { var carData = data.CARS; carData._embedded.car = carData._embedded.car[0]; halClient.followAll( carData, 'car' ).then( thenResolvedSpy, thenRejectedSpy ); $rootScope.$digest(); var callArgs = thenResolvedSpy.calls[0].args[0]; expect( callArgs.length ).toEqual( 1 ); expect( callArgs[0].status ).toEqual( 200 ); expect( callArgs[0].data ).toEqual( carData._embedded.car ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'can follow an empty set of embedded resources and passes an empty list of responses with overall status 200 (jira ATP-9408)', function() { var carData = data.CARS; carData._embedded.car = []; halClient.followAll( carData, 'car' ).on( { '200': onSpy200, '2xx': onSpy2xx, 'xxx': onSpyXxx } ); $rootScope.$digest(); expect( onSpy200 ).toHaveBeenCalledWith( [] ); expect( onSpy2xx ).not.toHaveBeenCalled(); expect( onSpyXxx ).not.toHaveBeenCalled(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'calls a matching on handler if the status codes of all responses are the same', function() { halClient.followAll( meHalResource, 'car' ).on( { '200': onSpy200, '2xx': onSpy2xx, 'xxx': onSpyXxx } ); $httpBackend.flush(); expect( onSpy200 ).toHaveBeenCalled(); expect( onSpy2xx ).not.toHaveBeenCalled(); expect( onSpyXxx ).not.toHaveBeenCalled(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'calls xxx handler if the status codes of some responses are different', function() { meHalResource._links.car.push( { href: data.baseUrl + '/me/cars/2' } ); $httpBackend.whenGET( data.baseUrl + '/me/cars/2' ).respond( 404 ); halClient.followAll( meHalResource, 'car' ).on( { '200': onSpy200, '2xx': onSpy2xx, 'xxx': onSpyXxx } ); $httpBackend.flush(); var callArgs = onSpyXxx.calls[0].args[0]; expect( onSpy200 ).not.toHaveBeenCalled(); expect( onSpy2xx ).not.toHaveBeenCalled(); expect( onSpyXxx ).toHaveBeenCalled(); expect( callArgs[0].status ).toEqual( 200 ); expect( callArgs[1].status ).toEqual( 200 ); expect( callArgs[2].status ).toEqual( 404 ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'has a utility function to create a simple follow handler', function() { var addressFollower = halClient.thenFollow( 'address' ); addressFollower( { data: meHalResource } ).then( thenResolvedSpy, thenRejectedSpy ); $rootScope.$digest(); expect( thenResolvedSpy ).toHaveBeenCalledWithProperties( { status: 200, data: meHalResource._embedded.address } ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'has a utility function to create a simple followAll handler', function() { var carFollower = halClient.thenFollowAll( 'car' ); carFollower( { data: meHalResource } ).then( thenResolvedSpy, thenRejectedSpy ); $httpBackend.flush(); var callArgs = thenResolvedSpy.calls[0].args[0]; expect( callArgs[0].status ).toEqual( 200 ); expect( callArgs[0].data ).toEqual( data.CARS._embedded.car[0] ); expect( callArgs[1].status ).toEqual( 200 ); expect( callArgs[1].data ).toEqual( data.CARS._embedded.car[1] ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'supports following simple path fragment templated URIs (ATP-9391)', function() { $httpBackend.expectGET( data.baseUrl + '/me/carsByType/VW' ).respond( 200, {} ); halClient.follow( data.CARS, 'carsByType', { vars: { type: 'VW' } } ); $httpBackend.flush(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'supports following simple query string templated URIs (ATP-9391)', function() { $httpBackend.expectGET( data.baseUrl + '/me/carsByModel?model=DeLorean' ).respond( 200, {} ); halClient.follow( data.CARS, 'carsByModel', { vars: { model: 'DeLorean' } } ); $httpBackend.flush(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'supports following simple query and query continuation string templated URIs (ATP-9391)', function() { $httpBackend.expectGET( data.baseUrl + '/me/carsByTypeAndModel?type=VW&model=DeLorean' ).respond( 404 ); halClient.follow( data.CARS, 'carsByTypeAndModel', { vars: { type: 'VW', model: 'DeLorean' } } ); $httpBackend.flush(); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'URI encodes simple query and query continuation string templated URIs (ATP-9617)', function() { $httpBackend.expectGET( data.baseUrl + '/me/carsByTypeAndModel?type=Daimler%20Benz&model=T%201000%2B' ).respond( 404 ); halClient.follow( data.CARS, 'carsByTypeAndModel', { vars: { type: '<NAME>', model: 'T 1000+' } } ); $httpBackend.flush(); } ); } ); //////////////////////////////////////////////////////////////////////////////////////////////////////// describe( 'configured to queue unsafe requests', function() { var httpMock; var deferred; beforeEach( function() { httpMock = jasmine.createSpy( 'httpMock' ).andCallFake( function() { return deferred.promise; } ); ngMocks.inject( function( $q ) { deferred = $q.defer(); } ); halClient = halHttp.create( httpMock, $injector.get( '$q' ), { queueUnsafeRequests: true } ); halClient.post( 'first', {} ); halClient.post( 'second', {} ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'only starts the next request if the previous was fulfilled (ATP-9539)', function() { $rootScope.$digest(); expect( httpMock.calls.length ).toBe( 1 ); deferred.resolve(); $rootScope.$digest(); expect( httpMock.calls.length ).toBe( 2 ); } ); ///////////////////////////////////////////////////////////////////////////////////////////////////// it( 'only starts the next request if the previous was rejected (ATP-9539)', function() { $rootScope.$digest(); expect( httpMock.calls.length ).toBe( 1 ); deferred.reject(); $rootScope.$digest(); expect( httpMock.calls.length ).toBe( 2 ); } ); } ); } ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// function addMatchers( jasmineContext ) { jasmineContext.addMatchers( { toHaveBeenCalledWithProperties: function( expectedProperties ) { var expectedKeys = Object.keys( expectedProperties ); var args = (this.actual.calls || []) .map( function( call ) { return call.args && call.args.length ? call.args[0] : {}; } ); var called = args.some( function( arg ) { return expectedKeys.every( function( key ) { return JSON.stringify( expectedProperties[ key ] ) === JSON.stringify( arg[ key ] ); } ); } ); this.message = function() { return 'Expected call with properties ' + jasmine.pp( expectedProperties ) + ' but was called with ' + jasmine.pp( args ); }; return called; } } ); } } ); <filename>miniprogram/pages/notification/notification.js // pages/notification/notification.js const app = getApp(); const toast = require("../../utils/message").toast; const getFormid = require("../../utils/formid").getFormid; const notify = require("../../utils/notification"); const formid = require("../../utils/formid"); import regeneratorRuntime, { async } from "../../utils/regenerator-runtime/runtime"; Page({ /** * 页面的初始数据 */ data: { bgImgUrl: "", nickName: "", fixTop: false, fixVeryTop: false, tabIndex: 0, hasReadArray: [], unReadArray: [], isEdit: false, selectedList: [], tabContent: ["未读消息", "已读消息"] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: async function () { let tmpUserInfo = wx.getStorageSync("curUserProfile"); let bgImgUrl = tmpUserInfo.bgImgUrl, nickname = tmpUserInfo.nickName; this.setData({ bgImgUrl, nickname }); formid.upload(); await notify.download(this); }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, tabHandler(e) { let index = parseInt(e.detail.index); this.setData({ tabIndex: index }) if (this.data.isEdit) { this.setData({ isEdit: false, selectedList: [] }) } }, onPageScroll: function(e) { if (e.scrollTop > 0) { this.setData({ fixVeryTop: true }) } if (e.scrollTop > 80) { this.setData({ fixTop: true }) } else { this.setData({ fixTop: false, fixVeryTop: false }) } }, getFormid(e) { getFormid(e.detail.formId); }, bindEdit() { this.setData({ isEdit: !this.data.isEdit }) }, bindChecked(e) { this.setData({ selectedList: e.detail.value }) }, changeStatus: async function() { let selectedList = this.data.selectedList; if (selectedList.length === 0) return; else if (selectedList.length > 20) { toast("暂不支持同时更改20条以上数据", "none"); return; } let status; switch(this.data.tabIndex) { case 0: status="has-read"; break; case 1: status="un-read"; break; } let res = await notify.changeStatus(selectedList, status); if (res.code === 1) { res = await notify.download(this); } }, delete: async function() { let selectedList = this.data.selectedList; if (selectedList.length === 0) return; else if (selectedList.length > 20) { toast("暂不支持同时更改20条以上数据", "none"); return; } let res = await notify.deleteItems(selectedList); if (res.code === 1) { res = await notify.download(this); } } })'use strict'; const { QueryTransformation } = require('./QueryTransformation'); class CompositeQueryTransformation extends QueryTransformation { constructor(transformations) { super(); this.transformations = transformations; } onConvertQueryBuilderBase(item, builder) { for (const transformation of this.transformations) { item = transformation.onConvertQueryBuilderBase(item, builder); } return item; } } module.exports = { CompositeQueryTransformation, }; const Discord = require("discord.js") const db = require("quick.db"); const config = require("../config.js"); module.exports.run = async (client, message, args, params) => { let embed = new Discord.MessageEmbed().setColor("RANDOM").setFooter("RK was here", message.author.avatarURL({dynamic: true})).setTimestamp().setAuthor(message.guild.name, message.guild.iconURL({dynamic: true})) let crews = db.get(`crews.${message.guild.id}`) || []; let crewPage = crews.length > 0 ? crews.map((value) => ` Ekip Adı: \`${value.EkipAdı}\` Ekip Tagları: (\`${value.EkipAdı}\` - \`${value.Sayısı}\`) Ekip Yöneticisi: <@!${value.Yöneticisi}> Katılım Tarihi: \`${new Date(value.KatılmaTarihi).tarihgetir()}\` Ekip Rolü: <@&${value.EkipRolu}> `).join("\n") : `Sunucumuzda ekip bulunmuyor.`; let secim = args[0]; if (!secim) return message.channel.send(embed.setDescription(` **ekip** \`-\` Yardım menüsünü gösterir. **ekip ekle** \`-\` Yeni bir ekip eklersiniz. **ekip liste** \`-\` Ekipleri listelersiniz. **ekip bilgi** \`-\` Ekip bilgileri. **ekip kontrol** \`-\` Ekip kontrol. **ekip sil** \`-\` Mevcut bir ekibi silersiniz. `)).then(x => x.delete({ timeout: 15000 }));; let tag = args[1]; let sayitagi = args[2]; let yönetici = message.mentions.members.first() || message.guild.members.cache.get(args[3]); let veriTabani = db.fetch(`ekipler.${message.guild.id}`) if (secim === "ekle") { if (!tag) return message.channel.send(embed.setDescription(`Geçerli bir tag belirtmelisin. (kullanım; \`ekip ekle tag sayıtagı yönetici\`!)`)).then(x => x.delete({ timeout: 7500 })); if (!sayitagi || isNaN(sayitagi)) return message.channel.send(embed.setDescription(`Geçerli bir sayı tagı belirtmelisin.`)).then(x => x.delete({ timeout: 5000 })); if (!yönetici) return message.channel.send(embed.setDescription(`Ekibin yöneticisini etiketlemelisin. (kullanım; \`ekip ekle tag sayıtagı yönetici\`!)`)).then(x => x.delete({ timeout: 5000 })); message.guild.roles.create({ data: { name: `${tag} #${sayitagi}`, color: "RANDOM", mentionable: false }, reason: "Ekip Rolü Kuruldu!" }).then(role => { db.push(`crews.${message.guild.id}`, {EkipAdı: tag, Sayısı: sayitagi || "Yok!", Yöneticisi: yönetici.id, KatılmaTarihi: Date.now(), EkipRolu: role.id}) db.set(`ekipler.${tag}.${message.guild.id}`, {EkipAdı: tag, Sayısı: sayitagi || "Yok!", Yöneticisi: yönetici.id, KatılmaTarihi: Date.now(), EkipRolu: role.id}) message.channel.send(embed.setDescription(` **${tag}** adında bir ekip oluşturuldu! **Detaylı bilgiler:** \`Ekip Tagı:\` ${tag} \`Ekip Tagı(Sayı):\` ${sayitagi} \`Ekip Yöneticisi:\` ${yönetici} \`Ekibin sunucuya katılma tarihi:\` ${new Date(Date.now()).tarihgetir()} \`Ekip Rolü:\` <@&${role.id}> **Ekip Tagındaki Kişi Sayısı:** \`Yazılı(${tag}):\` ${message.guild.members.cache.filter(m => m.user.username.toLowerCase().includes(tag)).size} \`Sayı(${sayitagi}):\` ${message.guild.members.cache.filter(m => m.user.discriminator.includes(sayitagi)).size} Toplamda ${message.guild.members.cache.filter(m => m.user.discriminator.includes(sayitagi)).size + message.guild.members.cache.filter(m => m.user.username.toLowerCase().includes(tag)).size} kişiye <@&${role.id}> rolü dağıtılıyor! `)) message.guild.members.cache.forEach(qwe => { if (qwe.user.username.includes(tag)) { qwe.roles.add(role.id) } }) message.guild.members.cache.forEach(qwe => { if (qwe.user.discriminator.includes(sayitagi)) { qwe.roles.add(role.id) } }) }) } if (secim === "liste") { message.channel.send(embed.setDescription(` Sunucumuzda Toplam \`${crews.length || "0"}\` adet ekip var! ${crewPage} `)) } if (secim === "bilgi") { if(!tag) return message.channel.send(embed.setDescription("Bir tag belirtmelisin.")).then(x => x.delete({ timeout: 3500 })); let ekipler = db.fetch(`ekipler.${tag}.${message.guild.id}`) if(!ekipler) return message.channel.send(embed.setDescription("Geçerli bir ekip belirtmelisin.")).then(x => x.delete({ timeout: 3500 })); message.channel.send(embed.setDescription(` **${ekipler.EkipAdı}** ekibinin bilgileri gösteriliyor! \`Ekip Tagı:\` ${ekipler.EkipAdı} \`Sayı Tagı:\` ${ekipler.Sayısı} \`Yöneticisi:\` ${message.guild.members.cache.get(ekipler.Yöneticisi) || message.guild.members.cache.get(ekipler.Yöneticisi).user.tag} \`Katılım Tarihi:\` \`${new Date(ekipler.KatılmaTarihi).tarihgetir()}\` \`Ekibin Rolü:\` <@&${ekipler.EkipRolu}> `)) } if (secim === "kontrol") { if(!tag) return message.channel.send(embed.setDescription("Bir tag belirtmelisin.")) let ekipler = db.fetch(`ekipler.${tag}.${message.guild.id}`) if(!ekipler) return message.channel.send(embed.setDescription("Geçerli bir ekip belirtmelisin.")).then(x => x.delete({ timeout: 3500 })); message.channel.send(embed.setDescription(` **${ekipler.EkipAdı}** kontrol ediliyor.. Yöneticisi: ${message.guild.members.cache.get(ekipler.Yöneticisi) || message.guild.members.cache.get(ekipler.Yöneticisi).user.tag} Yönetici: ${message.guild.members.cache.get(ekipler.Yöneticisi).voice.channelID ? "Ekip yöneticisi seste!":"Ekip yöneticisi seste değil!"} \`Seste Olan Kişi Sayısı(Yazılı Tag):\` ${message.guild.members.cache.filter(s => s.user.username.toLowerCase().includes(ekipler.EkipAdı)).filter(s => s.voice.channel).size || "0"} \`Seste Olan Kişi Sayısı(Sayılı Tag):\` ${message.guild.members.cache.filter(s => s.user.discriminator.includes(ekipler.Sayısı)).filter(s => s.voice.channel).size || "0"} \`Seste Olan Kişi Sayısı(Toplam):\` ${message.guild.members.cache.filter(s => s.user.discriminator.includes(ekipler.Sayısı)).filter(s => s.voice.channel).size + message.guild.members.cache.filter(s => s.user.username.includes(ekipler.EkipAdı)).filter(s => s.voice.channel).size || 0} `)) } if (secim === "sil") { if(!tag) return message.channel.send(embed.setDescription("Bir tag belirtmelisin.")) let ekipler = db.fetch(`ekipler.${tag}.${message.guild.id}`) if(!ekipler) return message.channel.send(embed.setDescription("Geçerli bir ekip belirtmelisin.")).then(x => x.delete({ timeout: 3500 })); message.channel.send(embed.setDescription(` **${ekipler.EkipAdı}** isimli ekip silindi. **${message.guild.roles.cache.get(ekipler.EkipRolu).name || "Silinen Rol"}** isimli rol silindi. ${message.guild.members.cache.get(ekipler.Yöneticisi) || "Ekip Yöneticisine"} ekibinin sunucumuzdan ayrıldığı bildirildi. `)) message.guild.members.cache.get(ekipler.Yöneticisi).send(embed.setDescription(` **${ekipler.EkipAdı}** isimli ekibin **${message.guild.name}** isimli sunucudan ayrıldı! `)) message.guild.roles.cache.get(ekipler.EkipRolu).delete({reason: "Ekip Ayrıldı!"}); db.delete(`ekipler.${tag}.${message.guild.id}`) } }; exports.conf = { enabled: true, guildOnly: false, aliases: ["ekip"], permLevel: 0 }; exports.help = { name: "ekip", description: "[Admin Komutu]", usage: "ekip" }; <reponame>krackerman/lambda-rollbar const zlib = require('zlib'); const get = require('lodash.get'); const ensureString = require('../util/ensure-string'); module.exports = (event) => { const raw = get(event, 'awslogs.data'); let content = null; try { content = JSON.parse(String(zlib.gunzipSync(Buffer.from(raw, 'base64')))); } catch (error) { return { body: { error: error.message, raw } }; } const logGroup = get(content, 'logGroup', '???'); const logStream = get(content, 'logStream', '???'); return { body: ensureString(content), url: `https://console.aws.amazon.com/cloudwatch/home#logEventViewer:group=${logGroup};stream=${logStream}` }; }; var greetings = function(controller) { controller.hears(['kk', 'jovie', 'viejo'], ['ambient', 'direct_mention', 'mention'], function(bot, message) { var userID = message.user; var user = '<@'+userID+'>'; var reply = user + ' qué pasó? Ahora no puedo, ando en calls.'; bot.reply(message, reply); }); controller.hears(['Adios', 'Bye', 'Nos vemos', 'Chau'], ['ambient', 'direct_mention', 'mention'], function(bot, message) { var userID = message.user; var user = '<@'+userID+'>'; var reply = user + ' chau! Saludos.'; bot.reply(message, reply); }); controller.middleware.receive.use(function(bot, message, next) { if (message.text == 'Hola' || message.text == 'Holis' || message.text == 'Que haces' || message.text == 'Hey') { message.intent = 'Hi'; } next(); }); controller.middleware.send.use(function(bot, message, next) { next(); }); function hear_intent(patterns, message) { for (var p = 0; p < patterns.length; p++) { if (message.intent == patterns[p]) { return true; } } return false; } controller.hears(['Hola'], ['direct_mention', 'mention', hear_intent], function(bot, message) { bot.api.reactions.add({ timestamp: message.ts, channel: message.channel, name: 'wink' },function(err, res) { if (err) { bot.botkit.log('Failed to add emoji reaction :(',err); } }); controller.storage.users.get(message.user,function(err, user) { if (user && user.name) { bot.reply(message, 'Ehhh Quien es ? Ahhh, ' + user.name + ' Cómo le va!?'); } else { bot.reply(message, 'Buenas buenas, Hola, gente...'); } }); }); controller.hears(['Llamame (.*)','Me dicen (.*)'], ['direct_mention', 'mention'], function(bot, message) { var name = message.match[1]; controller.storage.users.get(message.user,function(err, user) { if (!user) { user = { id: message.user, }; } user.name = name; controller.storage.users.save(user,function(err, id) { bot.reply(message,'Ssscelente para mí te llamas ' + user.name + ' desde ahora.'); }); }); }); controller.hears(['Quien soy','Como me llamo'], ['direct_mention', 'mention'], function(bot, message) { controller.storage.users.get(message.user,function(err, user) { if (user && user.name) { bot.reply(message,'Te dicen ' + user.name); } else { bot.reply(message,'Ehh ehh **Glup** Fernando?'); } }); }); }; module.exports = greetings;<filename>webpack.config.js var path = require('path'); var config = require('./config'); var webpack = require("webpack"); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var vueConfig = require('./vue-loader.config'); var env = process.argv[2]; var fs = require('fs'); var entries = { 'vendor': config.vendor }; // 支持驼峰 var fistLetterUpper = function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }; var buildEntryPoint = function(entryPoint) { if (env !== 'hot-reload') { return entryPoint; } return [ 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true', entryPoint ] } // 动态生成entry fs.readdirSync(config.entryDir).filter(function(folder) { var path = config.entryDir + folder; var stat = fs.lstatSync(path); if (stat.isDirectory()) { fs.readdirSync(path).filter(function(name) { var c_path = path + '/' + name; var c_stat = fs.lstatSync(c_path); if (c_stat.isDirectory()) { entries[folder + fistLetterUpper(name)] = buildEntryPoint(c_path + '/' + name + '.js'); } }); } }); // 定义plugin var plugins = [ new ExtractTextPlugin({ filename: "css/[name].css", allChunks: true }), new webpack.optimize.CommonsChunkPlugin({ name: "vendor", filename: "js/vendor.js", minChunks: Infinity }), new webpack.DefinePlugin({ '__DEV__': process.env.NODE_ENV === 'production' ? false : true }) ]; if (env === 'hot-reload') { var arr = [ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ] plugins = arr.concat(plugins); console.log('hot reload listening……') } module.exports = { entry: entries, output: { path: path.join(__dirname, config.distDir), filename: 'js/[name].js', publicPath: '/wuji/dist/' //方便定位到CDN静态资源,配合url-loader }, //引入第三方库 externals: { 'calendar': 'calendar', 'particlesJS': 'particlesJS' }, module: { rules: [{ test: /\.vue$/, loader: 'vue-loader', options: vueConfig }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { //需要有相应的css-loader,因为element-ui css在node_moudle test: /\.css$/, loader: ExtractTextPlugin.extract({ use: "css-loader", fallback: 'style-loader' }) }, { test: /\.(scss|sass)$/, loader: ExtractTextPlugin.extract({ use: "css-loader!sass-loader", fallback: 'style-loader' }) }, { //同上 test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/, loader: 'file-loader' }, { test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=8192' }] }, resolve: { // require时省略的扩展名,不再需要强制转入一个空字符串,如:require('module') 不需要module.js extensions: [".js", ".json", ".vue", ".scss", ".css"], //require路径简化 alias: { //Vue 最早会打包生成三个文件,一个是 runtime only 的文件 vue.common.js,一个是 compiler only 的文件 compiler.js,一个是 runtime + compiler 的文件 vue.js。 //vue.js = vue.common.js + compiler.js,默认package.json的main是指向vue.common.js,而template 属性的使用一定要用compiler.js,因此需要在alias改变vue指向 vue: 'vue/dist/vue', config: path.resolve(__dirname, config.srcDir + '/config'), filter: path.resolve(__dirname, config.srcDir + '/filters'), utils: path.resolve(__dirname, config.srcDir + '/utils'), stores: path.resolve(__dirname, config.srcDir + '/stores'), routers: path.resolve(__dirname, config.srcDir + '/routers'), modules: path.resolve(__dirname, config.srcDir + '/modules'), component: path.resolve(__dirname, config.srcDir + '/component') } }, plugins: plugins, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' vueConfig.loaders = { sass: ExtractTextPlugin.extract({ use: 'css-loader!sass-loader', fallback: 'vue-style-loader' }) } //是否压缩 if(config.isGzip){ var CompressionWebpackPlugin = require('compression-webpack-plugin'); module.exports.plugins.push(new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: /\.js$|\.html$|\.css$/, threshold: 10240, minRatio: 0.8 })) } module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true }), new webpack.LoaderOptionsPlugin({ minimize: true }) ]) }import { clearOpenMenuAction } from '../actions/clearOpenMenuAction'; export const resetHeaderAccordionsSequence = [clearOpenMenuAction]; <reponame>sundersc/cloudform "use strict"; /* Generated from: * ap-northeast-1 (https://d33vqc0rt9ld30.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * ap-northeast-2 (https://d1ane3fvebulky.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * ap-northeast-3 (https://d2zq80gdmjim8k.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * ap-south-1 (https://d2senuesg1djtx.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * ap-southeast-1 (https://doigdx0kgq9el.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * ap-southeast-2 (https://d2stg8d246z9di.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * ca-central-1 (https://d2s8ygphhesbe7.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * eu-central-1 (https://d1mta8qj7i28i2.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * eu-west-1 (https://d3teyb21fexa9r.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * eu-west-2 (https://d1742qcu2c1ncx.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * eu-west-3 (https://d2d0mfegowb3wk.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * sa-east-1 (https://d3c9jyj3w509b0.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * us-east-1 (https://d1uauaxba7bl26.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * us-east-2 (https://dnwj8swjjbsbt.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * us-west-1 (https://d68hl49wbnanq.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0, * us-west-2 (https://d201a2mn26r7lk.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 39.2.0 */ Object.defineProperty(exports, "__esModule", { value: true }); const assetModel_1 = require("./assetModel"); const asset_1 = require("./asset"); const dashboard_1 = require("./dashboard"); const portal_1 = require("./portal"); const accessPolicy_1 = require("./accessPolicy"); const gateway_1 = require("./gateway"); const project_1 = require("./project"); var IoTSiteWise; (function (IoTSiteWise) { IoTSiteWise.AssetModel = assetModel_1.default; IoTSiteWise.Asset = asset_1.default; IoTSiteWise.Dashboard = dashboard_1.default; IoTSiteWise.Portal = portal_1.default; IoTSiteWise.AccessPolicy = accessPolicy_1.default; IoTSiteWise.Gateway = gateway_1.default; IoTSiteWise.Project = project_1.default; })(IoTSiteWise = exports.IoTSiteWise || (exports.IoTSiteWise = {})); <gh_stars>10-100 import guest from './before/guest'; import auth from './before/auth'; export default (to, from, next, store) => { if (store.state.auth.isAuth) { auth(to, from, next, store); } else { guest(to, from, next, store); } }; module.exports = { /** * Function is designed to update categories current value and generate state information for the relationship between a Transaction and a Category * @param {Object} data Data object that is used by the the */ category: async function({nodeA, nodeB, newCategory } ) { // Generate Relationship Properties const relationshipProperties = { delta: nodeA.change ? nodeA.change : nodeA.current_value, current_value: nodeB._properties.get('current_value'), createdAt: new Date().toISOString() }; // Update category node with new value if (!newCategory) { nodeB.update({ id: nodeB._properties.get('id'), name: nodeB._properties.get('name'), current_value: nodeB._properties.get('current_value') + nodeA.change }); } // Return properties to be applied to relationship return relationshipProperties; } };/** * 给出一颗二叉树的根节点以及其中两个节点,求两个节点最近的公共节点 * 公共节点有两种情况,第一是其中一个节点为另一个节点的子节点 * 第二是公共节点的左右子树分别有一个节点,所以当遍历到一个节点时,分别去左右子树找其中一个点, * @param {TreeNode} root * @param {TreeNode} node1 * @param {TreeNode} node2 */ function findCloestPublicRoot(root,node1,node2){ if (root === null || root === node1 || root === node2){ return root; } const left = findCloestPublicRoot(root.left,node1,node2); const right = findCloestPublicRoot(root.right,node1,node2); if (!left){ return right; } else if(!right){ return left; } return root; }<filename>test/Server.test.js const {join} = require('path'); const {writeFileSync, realpathSync} = require('fs-extra'); const temp = require('temp'); const portscanner = require('portscanner'); const fetch = require('node-fetch'); const {expect, stub, restore, writeTabrisProject} = require('./test'); const Server = require('../src/services/Server'); const proc = require('../src/helpers/proc'); const TerminalMock = require('./TerminalMock.js'); const htmllint = require('htmllint'); describe('Server', function() { let server, path; beforeEach(function() { path = realpathSync(temp.mkdirSync('foo')); server = new Server({terminal: new TerminalMock()}); stub(proc, 'spawnSync'); stub(proc, 'spawn').returns({stdout: {on: stub()}, stderr: {on: stub()}}); }); afterEach(function() { restore(); }); describe('externalAddresses', function() { it('returns an array of IP addresses', function() { expect(Server.externalAddresses).to.be.an('array'); expect(Server.externalAddresses[0]).to.match(/\d+.\d+.\d+.\d+/); }); }); describe('port', function() { it('defaults to `null`', function() { expect(server.port).to.be.null; }); it('returns port number when started', async function() { writeTabrisProject(path); await server.serve(path); expect(server.port).to.be.a('number'); expect(server.port).to.be.at.least(8080); }); }); describe('serve', function() { it('fails without path argument', async function() { try { await server.serve(); expectFail(); } catch(e) { expect(e.message).to.equal('path missing'); } }); it('fails with non-existent path', async function() { try { await server.serve('foobar.js'); expectFail(); } catch(e) { expect(e.message).to.equal('No such file or directory: foobar.js'); } }); it('fails with a directory that is missing a package.json', async function() { try { await server.serve(path); expectFail(); } catch(e) { expect(e.message).to.equal('Directory must contain package.json'); } }); it('fails with package.json that is missing a `main` field', async function() { writeTabrisProject(path, '{}'); try { await server.serve(path); expectFail(); } catch(e) { expect(e.message).to.equal('package.json must contain a "main" field'); } }); it('fails if tabris module is not installed', async function() { writeTabrisProject(path, null, false); try { await server.serve(path); expectFail(); } catch(e) { expect(e.message).to.equal('No tabris module installed; did you run npm install?'); } }); it('fails with interactive flag if tabris version is not supported', async function() { writeTabrisProject(path, null, '{"version": "2.0.0"}'); server = new Server({watch: true, terminal: new TerminalMock(), interactive: true}); try { await server.serve(path); expectFail(); } catch(e) { expect(e.message).to.equal('Interactive console (-i, --interactive) feature requires a Tabris.js 3.x project'); } }); it('fails with autoReload flag if tabris version is not supported', async function() { writeTabrisProject(path, null, '{"version": "2.0.0"}'); server = new Server({watch: true, terminal: new TerminalMock(), autoReload: true}); try { await server.serve(path); expectFail(); } catch(e) { expect(e.message).to.equal('Auto reload (-a, --auto-reload) feature requires a Tabris.js 3.x project'); } }); it('runs build script', async function() { writeTabrisProject(path); await server.serve(path); expect(proc.spawnSync).to.have.been.calledWith('npm', ['run', '--if-present', 'build'], {cwd: path}); }); it('runs watch script when watch option given', async function() { server = new Server({watch: true, terminal: new TerminalMock()}); writeTabrisProject(path); await server.serve(path); expect(proc.spawnSync).to.have.been.calledWith('npm', ['run', '--if-present', 'prewatch'], {cwd: path}); expect(proc.spawn).to.have.been.calledWith('npm', ['run', '--if-present', 'watch'], { cwd: path, stdio: 'pipe' }); }); it('starts a server', async function() { writeTabrisProject(path); await server.serve(path); const status = await getPortStatus(server.port); expect(status).to.equal('open'); }); it('uses next unused port', async function() { writeTabrisProject(path); const server2 = new Server({terminal: new TerminalMock()}); await server.serve(path); await server2.serve(path); expect(server.port).to.be.ok; expect(server2.port).to.be.ok; expect(server2.port).to.not.equal(server.port); }); it('delivers directory contents', async function() { writeTabrisProject(path); writeFileSync(join(path, 'foo.js'), 'content'); await server.serve(path); const response = await fetch(`http://127.0.0.1:${server.port}/foo.js`); const text = await response.text(); expect(text).to.equal('content'); }); it('shows a dynamic message on the default route', async function() { writeTabrisProject(path); writeFileSync(join(path, 'package.json'), '{"main": "unused.js"}'); await server.serve(path); const response = await fetch(`http://127.0.0.1:${server.port}/`); const text = await response.text(); expect(text).to.match(/Tabris\.js CLI is running/); expect(text).to.match(/src="data:image\/png;base64/); expect(text).to.match(/URL/); expect(text).to.match(/Scan the QR Code below/); expect(text).to.match(/href="https:\/\/docs.tabris.com\/latest\/developer-app.html"/); expect(await htmllint(text, { 'attr-bans': [], 'indent-style': 'spaces', 'indent-width': 2, 'img-req-alt': false, 'tag-close': false })).to.deep.equal([]); }); }); }); function getPortStatus(port) { return portscanner.checkPortStatus(port, '127.0.0.1'); } function expectFail() { throw new Error('expected to fail'); } // When the user clicks anywhere outside of the modal, close it document.getElementById('id01').onclick='block'; // onclick="document.getElementById('id01').style.display='block'" style="width:auto;" $(document).ready(function(){ $('[data-toggle="popover"]').popover(); });// Karma configuration // Generated on Thu Dec 24 2015 08:21:54 GMT+0200 (IST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ // Angular 'node_modules/angular/angular.min.js', 'node_modules/angular-mocks/angular-mocks.js', // Firebase 'node_modules/firebase/lib/firebase-web.js', // OnFire 'node_modules/onfire/dist/onfire.min.js', // ngOnFire 'dist/ng-onfire.min.js', // Test specs 'test/**/*test.js', // Test data { pattern: 'test/**/*.json', watched: true, served: true, included: false } ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'verbose-summary'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultanous concurrency: Infinity }) } <reponame>wakayamadesu/Aesthete module.exports = { colors: { default: '#5e81ac', error: 'bf616a' } }; import React, {useState, useCallback, useEffect} from 'react' import Router from 'next/router' import {debounce} from 'lodash' import {search} from '../../lib/explore/api' import {useInput} from '../../hooks/input' import SearchInput from '../search-input' import Notification from '../notification' import renderAddok from '../search-input/render-addok' const ExploreSearch = () => { const [input, setInput] = useInput('') const [results, setResults] = useState([]) const [orderResults, setOrderResults] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const handleSelect = feature => { const {id, type, citycode, housenumber} = feature.properties const codeCommune = citycode const idVoie = id.split('_').slice(0, 2).join('_') let href = '' let as = '' if (type === 'municipality') { href = `/explore/commune?codeCommune=${codeCommune}` as = `/explore/commune/${codeCommune}` } else if (type === 'street') { href = `/commune/voie?idVoie=${idVoie}` as = `/explore/commune/${codeCommune}/voie/${idVoie}` } else if (type === 'housenumber') { const [numero, suffixe] = housenumber.split(' ') const numeroComplet = `${numero}${suffixe || ''}` href = `/explore/commune/voie?codeCommune=${codeCommune}&idVoie=${idVoie}&numero=${numeroComplet}` as = `/explore/commune/${codeCommune}/voie/${idVoie}/numero/${numeroComplet}` } Router.push(href, as) } const handleSearch = useCallback(debounce(async input => { try { const results = await search(input) setResults( results.features.filter(f => f.properties.type !== 'locality').splice(0, 5) || [] ) } catch (err) { setError(err) } setLoading(false) }, 300), []) const getFeatureValue = feature => { return feature.header ? feature.header : feature.properties.name } useEffect(() => { if (results && results.length > 0) { const orderResults = [] results.map(feature => { if (!orderResults.find(item => item.header === feature.properties.type)) { orderResults.push({ header: feature.properties.type }) } return orderResults.push(feature) }) setOrderResults(orderResults) } }, [results]) useEffect(() => { if (input) { setResults([]) setLoading(true) setError(null) handleSearch(input) } }, [handleSearch, input]) return ( <> <SearchInput value={input} results={orderResults} loading={loading} placeholder='20 avenue de Ségur, Paris' onSelect={handleSelect} onSearch={setInput} renderItem={renderAddok} getItemValue={getFeatureValue} /> {error && <div className='error'> <Notification message={error.message} type='error' /> </div>} <style jsx>{` .error { margin: 1em 0; } `}</style> </> ) } export default ExploreSearch (function () { 'use strict'; angular.module('starterApp') .service('serviceClient', function ($mdDialog,$resource) { var client; this.getClient = function () { return client; } this.setClient = function (pClient) { client = pClient; } this.getCep = function(cep){ var rest = $resource('https://viacep.com.br/ws/:cep/json/',{'cep': cep}) return rest; } return this; }); })(); import { css } from 'styled-components'; const breakpoints = { desktop: 1170, laptop: 992, tablet: 768, phone: 376, }; // iterate through the sizes and create a media template export const media = Object.keys(breakpoints).reduce((accumulator, label) => { // use em in breakpoints to work properly cross-browser and support users // changing their browsers font-size: https://zellwk.com/blog/media-query-units/ const emSize = breakpoints[label] / 16; accumulator[label] = (...args) => css` @media (max-width: ${emSize}em) { ${css(...args)}; } `; return accumulator; }, {}); const theme = { breakpoints, media, }; export default theme; "use: strinct;"; (function(g){ const BIT_SUN = 1; const BIT_MON = 2; const BIT_TUE = 4; const BIT_WED = 8; const BIT_THU = 16; const BIT_FRI = 32; const BIT_SAT = 64; const state = { visible: false, toggle: true, original: null, at: null, yobi_sun: null, yobi_mon: null, yobi_tue: null, yobi_wed: null, yobi_thu: null, yobi_fri: null, yobi_sat: null, device: null, content: null, }; const component = { template: ` <popup :visible="visible"> <div class="field is-grouped"> <p class="control"> <input class="input" type="time" v-model="at"> </p> <p class="control is-expanded"> <label class="checkbox"><input type="checkbox" v-model="yobi_sun" value="1" />日</label> <label class="checkbox"><input type="checkbox" v-model="yobi_mon" value="1" />月</label> <label class="checkbox"><input type="checkbox" v-model="yobi_tue" value="1" />火</label> <label class="checkbox"><input type="checkbox" v-model="yobi_wed" value="1" />水</label> <label class="checkbox"><input type="checkbox" v-model="yobi_thu" value="1" />木</label> <label class="checkbox"><input type="checkbox" v-model="yobi_fri" value="1" />金</label> <label class="checkbox"><input type="checkbox" v-model="yobi_sat" value="1" />土</label> </p> <p class="control"> <button class="button" @click="click_toggle"> <span class="icon" v-if="toggle"><i class="fa fa-check-square-o"></i></span> <span class="icon" v-if="!toggle"><i class="fa fa-square-o"></i></span> </button> </p> </div> <div class="field is-grouped"> <p class="control"> <input class="input" type="text" v-model="device" placeholder="GoogleHome名: 空のとき全部"> </p> <p class="control is-expanded"> <input class="input" type="text" v-model="content" placeholder="文書 or MP3のURL"> </p> </div> <div class="field is-grouped"> <p class="control is-expanded"> <button class="button" @click="click_test">Test</button> </p> <p class="control"> <button class="button" @click="click_cancel">Cancel</button> <button class="button is-primary" @click="click_ok">OK</button> </p> </div> </popup> `, data: function(){ return state; }, computed: {}, beforeMount: function(){}, mounted: function(){}, methods: { click_toggle: function(){ state.yobi_sun = state.yobi_mon = state.yobi_tue = state.yobi_wed = state.yobi_thu = state.yobi_fri = state.yobi_sat = this.toggle; this.toggle = !this.toggle; }, click_cancel: function(){ state.visible = false; }, click_ok: function(){ if(false){ return; }//TODO: check const yobi = [ state.yobi_sun ? "日" : "", state.yobi_mon ? "月" : "", state.yobi_tue ? "火" : "", state.yobi_wed ? "水" : "", state.yobi_thu ? "木" : "", state.yobi_fri ? "金" : "", state.yobi_sat ? "土" : "", ].join(""); param = { original: state.original, item: { at: state.at, yobi: yobi, device: state.device, content: state.content, } }; if(!yobi || !state.content){ alert("曜日とコンテンツは必須です"); }else{ state.visible = false; this.$emit("ok", param); } }, click_test: function(){ const device = state.device; const content = state.content; if(content){ const param = { device: device, content: content, } this.$emit("test", param); } }, }, }; g.Vue.component('modal', component); const func = function(){}; func.prototype.show = function(item){ if(state.visible){ throw new Error("Modal is shown."); } const original = !!Object.keys(item).length ? item : null; const yobi = item.yobi || ""; state.original = item; state.at = item.at || "00:00"; state.yobi_sun = (yobi.indexOf("日") >= 0), state.yobi_mon = (yobi.indexOf("月") >= 0), state.yobi_tue = (yobi.indexOf("火") >= 0), state.yobi_wed = (yobi.indexOf("水") >= 0), state.yobi_thu = (yobi.indexOf("木") >= 0), state.yobi_fri = (yobi.indexOf("金") >= 0), state.yobi_sat = (yobi.indexOf("土") >= 0), state.device = item.device || ""; state.content = item.content || ""; state.visible = true; }; g.Modal = new func(); })(this);/* * Copyright (c) 2016 airbug Inc. http://airbug.com * * bugcore may be freely distributed under the MIT license. */ //------------------------------------------------------------------------------- // Annotations //------------------------------------------------------------------------------- //@Export('DependencyGraph') //@Require('Class') //@Require('Graph') //@Require('GraphEdge') //@Require('GraphNode') //@Require('List') //@Require('Map') //@Require('Obj') //@Require('Set') //------------------------------------------------------------------------------- // Context //------------------------------------------------------------------------------- require('bugpack').context("*", function(bugpack) { //------------------------------------------------------------------------------- // BugPack //------------------------------------------------------------------------------- var Class = bugpack.require('Class'); var Graph = bugpack.require('Graph'); var GraphEdge = bugpack.require('GraphEdge'); var GraphNode = bugpack.require('GraphNode'); var List = bugpack.require('List'); var Map = bugpack.require('Map'); var Obj = bugpack.require('Obj'); var Set = bugpack.require('Set'); //------------------------------------------------------------------------------- // Declare Class //------------------------------------------------------------------------------- /** * @class * @extends {Graph} */ var DependencyGraph = Class.extend(Graph, { _name: "DependencyGraph", //------------------------------------------------------------------------------- // Public Methods //------------------------------------------------------------------------------- /** * @param {*} ofValue * @param {*} onValue */ addDependency: function(ofValue, onValue) { if (!this.containsNodeForValue(ofValue)) { this.addNodeForValue(ofValue); } if (!this.containsNodeForValue(onValue)) { this.addNodeForValue(onValue); } this.addEdgeFromValueToValue(ofValue, onValue); }, /** * @return {List<*>} */ getValuesInDependentOrder: function() { var _this = this; var processedNodeSet = new Set(); var valuesInDependentOrderList = new List(); this.nodeSet.forEach(function(graphNode) { _this.processDependentOrder(graphNode, processedNodeSet, valuesInDependentOrderList); }); return valuesInDependentOrderList; }, //------------------------------------------------------------------------------- // Private Methods //------------------------------------------------------------------------------- /** * @private * @param {GraphNode} graphNode * @param {Set<GraphNode>} processedNodeSet * @param {List<*>} valuesInDependentOrderList */ processDependentOrder: function(graphNode, processedNodeSet, valuesInDependentOrderList) { var currentNodePathSet = new Set(); this.processDependentOrderRecursive(graphNode, processedNodeSet, valuesInDependentOrderList, currentNodePathSet); }, /** * @private * @param {GraphNode} graphNode * @param {Set<GraphNode>} processedNodeSet * @param {List<*>} valuesInDependentOrderList * @param {Set<GraphNode>} currentNodePathSet */ processDependentOrderRecursive: function(graphNode, processedNodeSet, valuesInDependentOrderList, currentNodePathSet) { var _this = this; // TODO BRN: We can find the chain of the circular dependency by trickling back out of the recursive stack. if (currentNodePathSet.contains(graphNode)) { throw new Error("Cannot compute dependency order. Circular reference found."); } else { currentNodePathSet.add(graphNode); } if (!processedNodeSet.contains(graphNode)) { var nodeFromSet = this.getNodesFrom(graphNode); nodeFromSet.forEach(function(nodeFrom) { _this.processDependentOrderRecursive(nodeFrom, processedNodeSet, valuesInDependentOrderList, currentNodePathSet); }); valuesInDependentOrderList.add(graphNode.getValue()); processedNodeSet.add(graphNode); } // NOTE BRN: We remove this node from the visited node set. Otherwise we will think this is a circular // reference when A -> B, A -> C, B -> C since through A we have already visited C and then we currentNodePathSet.remove(graphNode); } }); //------------------------------------------------------------------------------- // Exports //------------------------------------------------------------------------------- bugpack.export('DependencyGraph', DependencyGraph); }); <filename>src/consts.js //ProductInfo module.exports.DEVICETYPES = [ 'sense', 'vulcan', 'kone' ] // Khan const KHAN_PRODUCT_IDS = [14800]; const KHAN_LED_INTERFACE = 3; const KHAN_LED_USAGEPAGE = 12; // Kone const KONE_PRODUCT_IDS = [11815]; const KONE_LED_INTERFACE = 0; const KONE_LED_USAGEPAGE = 11; // Sense const SENSE_PRODUCT_IDS = [13371]; const SENSE_LED_INTERFACE = 0; const SENSE_LED_USAGEPAGE = 65281; // Vulcan const VULCAN_PRODUCT_IDS = [ 12410, /*Vulcan 100*/ 12440 /*Vulcan 120*/ ] const VULCAN_LED_INTERFACE = 3; const VULCAN_CTRL_INTERFACE = 1; const VULCAN_CTRL_USAGEPAGE = 10; //Animation interval for animateKeys() module.exports.ANIMATIONINTERVAL = 10; //Space between keys in marquee() module.exports.SPACEBETWEENCHARS = 2; //No Key Key module.exports.NOKEY = -1; //Number of Keys module.exports.NUMKEYS = 144; module.exports.getProductIDs = function (type) { switch (type) { case 'sense': return SENSE_PRODUCT_IDS; case 'vulcan': return VULCAN_PRODUCT_IDS; case 'kone': return KONE_PRODUCT_IDS; case 'khan': return KHAN_PRODUCT_IDS; default: throw new Error("specified device type not found. possible device types are: " + String.join(", ", this.DEVICETYPES)); } } module.exports.getLedInterface = function (type) { switch (type) { case 'sense': return SENSE_LED_INTERFACE; case 'vulcan': return VULCAN_LED_INTERFACE; case 'kone': return KONE_LED_INTERFACE; case 'khan': return KHAN_LED_INTERFACE; default: throw new Error("specified device type not found. possible device types are: " + String.join(", ", this.DEVICETYPES)); } } module.exports.getCtrlInterface = function (type) { switch (type) { case 'sense': case 'kone': case 'khan': throw new Error("specified device does has no implemented controls"); case 'vulcan': return VULCAN_CTRL_INTERFACE; default: throw new Error("specified device type not found. possible device types are: " + String.join(", ", this.DEVICETYPES)); } } module.exports.getLedUsagePage = function (type) { switch (type) { case 'sense': return SENSE_LED_USAGEPAGE; case 'kone': return KONE_LED_USAGEPAGE; case 'khan': return KHAN_LED_USAGEPAGE; case 'vulcan': return null; default: throw new Error("specified device type not found. possible device types are: " + String.join(", ", this.DEVICETYPES)); } } module.exports.getCtrlUsagePage = function (type) { switch (type) { case 'sense': case 'kone': case 'khan': return null; case 'vulcan': return VULCAN_CTRL_USAGEPAGE; default: throw new Error("specified device type not found. possible device types are: " + String.join(", ", this.DEVICETYPES)); } } <reponame>ICT4H/dcs-web $(document).ready(function(){ $('#tabs').tabs(); var selectedIndex = parseInt($('#page-state').html()); $('#tabs').tabs('select', selectedIndex); }); /* jshint node:true */ 'use strict'; console.log('starting'); var express = require('express'), app = express(), api = require('grasshopper-api'), PORT = process.env.PORT || 3000; api = api(require('./ghapi.json')); app.use(api.router); app.use(express.static(__dirname + '/public/admin')); app.get('/admin*?', function(request, response) { response.sendFile(__dirname + '/public/admin/index.html'); }); app.listen(PORT, function(){ console.log('Listening on: ' + PORT); }); <reponame>sdawood/json-prism<gh_stars>0 const jp = require('jsonpath/jsonpath.min'); const F = require('functional-pipelines'); const {get, set} = require('json-atom'); const {MultiWriter} = require('./SentientBatch'); const uuidV4 = require('uuid/v4'); const {stringify} = require('../../utils/json-path'); const {show, aLine} = require('../../utils/trace'); const Shredder_Mode_Actors = { // @TODO NOTICE having the parameter called toString had some unusual behavior with jest test, toString was invoked by some other piece of code!!! nodes: ({toStringFn = stringify} = {}) => ({path, value}) => ({path: toStringFn(path), value}), pairs: ({toStringFn = stringify} = {}) => ({path, value}) => [toStringFn(path), value], paths: ({toStringFn = stringify} = {}) => x => toStringFn(x.path), values: () => x => x.value }; const orderBy = (key, order, {xf = x => x} = {}) => { let compareFunction; if (['asc', 'node-leaf-groups'].includes(order)) { compareFunction = (a, b) => +(xf(a[key]) > xf(b[key])) || +(xf(a[key]) === xf(b[key])) - 1; } else if (['desc', 'leaf-node-groups'].includes(order)) { compareFunction = (a, b) => +(xf(b[key]) > xf(a[key])) || +(xf(b[key]) === xf(a[key])) - 1 } return compareFunction; // undefined triggers built-int array sort, which is idea for stringified paths or natural values }; const shredder = (document, {modes = ['nodes'], order = 'node-leaf-groups'} = {}) => { let nodes = jp.nodes(document, '$..*'); show(nodes); nodes = nodes .sort(orderBy('path', order, {xf: ps => ps.join('.')})); show(nodes); nodes = nodes .map(Shredder_Mode_Actors['nodes']()); show(nodes); // @TODO: investigate other sorting semantics, like bfs and dfs return modes.reduce((acc, mode) => { const compareFunction = Unshredder_Mode_Atom_Actors[mode] !== undefined ? orderBy(Unshredder_Mode_Atom_Actors[mode].orderKey, order) : undefined; acc[mode] = nodes.map(Shredder_Mode_Actors[mode]()); //.sort(compareFunction); return acc; }, {}); }; const Unshredder_Mode_Atom_Actors = { nodes: { unit: () => ({}), reducer: (acc, {path, value}) => { show(path, ':=', value); acc = set(path)(value)(acc); return acc; }, orderKey: 'path' }, pairs: { unit: () => ({}), reducer: (acc, [path, value]) => { show(path, ':=', value); acc = set(path)(value)(acc); return acc; }, orderKey: 0 } }; const Unshredder_Mode_SentientBatch_Actors = { nodes: { unit: () => ({}), reducer: (acc, {path, value}) => { show(path, ':=', value); acc = set(path)(value)(acc); return acc; }, orderKey: 'path', keyFrom: ({path}) => path, valueFrom: ({value}) => value }, pairs: { unit: () => ({}), reducer: (acc, [path, value]) => { show(path, ':=', value); acc = set(path)(value)(acc); return acc; }, orderKey: 0, keyFrom: ([path]) => path, valueFrom: ([_, value]) => value } }; const unshredder = ({nodes, pairs} = {}) => { const {entries, mode} = nodes ? {entries: nodes, mode: 'nodes'} : {entries: pairs, mode: 'pairs'}; // give priority to nodes if both are passed in const {unit: initFn, reducer: reducingFn} = Unshredder_Mode_Atom_Actors[mode]; show(mode, Unshredder_Mode_Atom_Actors[mode]); show(initFn, reducingFn); return F.reduce(reducingFn, initFn, entries.slice().sort(orderBy(Unshredder_Mode_Atom_Actors[mode].orderKey, 'node-leaf-groups'))); }; const Unprism = (subject, {labels = [uuidV4()]} = {}) => ({nodes, pairs, withoutKeys = [], sortUpdates = true} = {}) => { const {entries, mode} = nodes ? {entries: nodes, mode: 'nodes'} : {entries: pairs, mode: 'pairs'}; // give priority to nodes if both are passed in const sortedEntries = sortUpdates ? entries.slice().sort(orderBy(Unshredder_Mode_SentientBatch_Actors[mode].orderKey, 'node-leaf-groups')) : entries.slice(); const sortedKeys = sortedEntries.map(Unshredder_Mode_SentientBatch_Actors[mode].keyFrom); const sortedValues = sortedEntries.map(Unshredder_Mode_SentientBatch_Actors[mode].valueFrom); const multiWriter = MultiWriter(subject, {labels})(sortedKeys); return {value: multiWriter.updates(sortedValues).value, multiWriter}; }; module.exports = { shredder, Shredder_Mode_Actors, unshredder, Unshredder_Mode_Atom_Actors, Unprism };import getTabFeatureImage from '../helpers/getTabFeatureImage'; export class TabsManager { getAll() { return new Promise((resolve, reject) => { chrome.tabs.query({}, async function (tabs) { resolve( await Promise.all( tabs.map(async (tab) => ({ id: tab.id, label: tab.title, url: tab.url, image_url: await getTabFeatureImage(tab), })) ) ); }); }); } get(tab_id) { return new Promise((resolve, reject) => { chrome.tabs.get(tab_id, async function (tab) { resolve({ label: tab.title, url: tab.url, image_url: await getTabFeatureImage(tab), }); }); }); } openNew(url) { chrome.tabs.create({ url }); } openInActiveTab(url) { chrome.tabs.getSelected(null, function (tab) { chrome.tabs.update(tab.id, { url }); }); } getActive() { return new Promise((resolve) => { chrome.tabs.getSelected(null, async function (tab) { resolve({ label: tab.title, url: tab.url, image_url: await getTabFeatureImage(tab), }); }); }); } } import {ethers} from "ethers"; import sdk from "./1-initialize-sdk.js"; // Initalizing the variable with the address of the $BRANU token const tokenModule = sdk.getTokenModule("0x08c057C40474cDaF82a321535C530721A6E44adb"); (async () => { try { const amount = 1_000_000; // Convert uint into a string with 18 decimal places - enables users to send extremely small units of our token const amountWith18Decimals = ethers.utils.parseUnits(amount.toString(),18); await tokenModule.mint(amountWith18Decimals); const totalSupply = await tokenModule.totalSupply(); // Printing out token information console.log( "There are", ethers.utils.formatUnits(totalSupply,18), "$BRANU in circulation", ); } catch (error) { console.log('Failed to mint $BRANU tokens', error); } })();var v0 = (function (v1, v2, v3){ "use strict"; var v4 = v3(64), v5 = v3(184), v6 = v3(47); (v1.exports) = (function (v1){ for(var v2 = v4(this), v3 = v6(v2.length), v7 = arguments.length, v9 = v5(((v7) > (1)) ? (arguments[1]) : (void 0), v3), v10 = ((v7) > (2)) ? (arguments[2]) : (void 0), v11 = ((void 0) === (v10)) ? (v3) : (v5(v10, v3));(v11) > (v9);){ (v2[v9++]) = v1; } return v2; }); }); (v0.PATH) = "path"; var v1 = (function (v1){ return (v1.ui.escapeSelector) = (function (){ var v2 = /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g; return (function (v3){ return v3.replace(v2, "\\$1"); }); })(); }); var v2 = (function (v1, v2, v3){ var v4 = v3(2229), v5 = v3(2195), v6 = v3(690); (v1.exports) = (function (v1){ var v2 = v5(v1); return (((1) == (v2.length)) && (v2[0][2])) ? (v6(v2[0][0], v2[0][1])) : ((function (v3){ return ((v3) === (v1)) || (v4(v3, v1, v2)); })); }); }); v1("jeans"); (v0.warnings) = []; v1(v2, v0); (v1.UTC) = v2.UTC; // @flow import React from 'react'; import { render } from '@testing-library/react'; import { isDragging } from '../../util/helpers'; import App from '../../util/app'; import { forEachSensor, type Control, simpleLift } from '../../util/controls'; forEachSensor((control: Control) => { it('should be able to start a drag if default sensors is disabled', () => { const { getByText } = render(<App enableDefaultSensors={false} />); const handle: HTMLElement = getByText('item: 0'); simpleLift(control, handle); expect(isDragging(handle)).toBe(false); }); }); //function Apply JOb $("#frmVacancyApply").validate({ submitHandler: function (form) { var vacancy_id = $('#vacancy_id').val(); var candidate_id = $('#candidate_id').val(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); jQuery.ajax({ url: "/user/applyJob/" + vacancy_id +'/' + candidate_id, method: 'POST', data: { "company_id" : $('#company_id_appy_job').val(), "admin_id" : $('#admin_poster_id').val(), }, // beforeSend:function() // { // $.LoadingOverlay("show"); // }, success: function (result) { console.log(result); if(result == "error") { toastr.error('Please update Your Resume Before You Apply !'); var delay = 3000; URL = "http://127.0.0.1:8000/user/profile/" + candidate_id; setTimeout(function() { window.location = URL; }, delay); }else { toastr.success('this Vacancy has been applied !'); var delay = 3000; setTimeout(function() { $.LoadingOverlay("hide"); $('#UserLogin').modal('hide'); location.reload(); }, delay); } },error : function(err){ console.log(err); } }); } }); function ApplyJob(vacancy_id) { // alert('ok'); $('#vacancy_id').val(vacancy_id); var candidate_id = $('#candidate_id').val(); $.ajax({ type: "GET", url: "/checkUserLogin/" + vacancy_id +'/'+ candidate_id , success: function(result) { // console.log(result); // $.LoadingOverlay("hide"); $('#UserLogin').modal('show'); // $('#category_name_edit').val(result.name); },error : function(err){ console.log(err); } }); } //User Upate $('#user_name').prop('disabled', true); $('#user_email').prop('disabled',true); $('#user_phone').prop('disabled',true); $('#user_zip').prop('disabled',true); $('#user_zip').prop('disabled',true); $('#user_zip').prop('disabled',true); $('#user_date').prop('disabled',true); $('#user_nationality').prop('disabled',true); $('#user_sex').prop('disabled',true); $('#user_address').prop('disabled',true); $('#user_first_name').prop('disabled',true); $('#user_last_name').prop('disabled',true); $('#save_profile').prop('disabled',true); function EnableProfile() { $('#user_name').prop('disabled', false); $('#user_email').prop('disabled',false); $('#user_phone').prop('disabled',false); $('#user_zip').prop('disabled',false); $('#user_zip').prop('disabled',false); $('#user_zip').prop('disabled',false); $('#user_date').prop('disabled',false); $('#user_nationality').prop('disabled',false); $('#user_sex').prop('disabled',false); $('#user_address').prop('disabled',false); $('#user_first_name').prop('disabled',false); $('#user_last_name').prop('disabled',false); $('#save_profile').prop('disabled',false); } $('#btn_save_profile').click(function() { EnableProfile(); }); $(document).ready(function () { $('#frmEditResume').validate({ rules : { file_name_edit : { required : true, } } ,submitHandler : function (e) { var id = $('#user_resume_id_edit').val(); var extension = $('#file_name_edit').val().split('.').pop().toLowerCase(); if ($.inArray(extension, ['pdf', 'doc', 'docx']) == -1) { toastr.error('Please Select Valid File... !'); // $('#errormessage').html('Please Select Valid File... '); } else { var file_data = $('#file_name_edit').prop('files')[0]; var form_data = new FormData(); form_data.append('file_name', file_data); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url: "/user/attachment/update/" + id, // point to server-side PHP script data: form_data, type: 'POST', dataType:"json", contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData: false, success: function(result) { console.log(result); $('#ModalEditUserCv').modal('hide'); toastr.success('Success', 'item has been Updated !'); var resume = '<tr id="tr_userCV' + result.id + '"><td>' + result.file_name + '</td><td>' + result.file_size + '</td><td>' + result.attachment_type + '</td>'; resume += '<th><a onclick="EditUserCv('+ result.id + ');" data-toggle="modal"><i class="fa fa-edit" aria-hidden="true"></i> | </a><a onclick="DeleteUserCv(' + result.id + ');"><i style="color:red;" class="fa fa-trash" aria-hidden="true"></i></a></th></tr>'; $("#tr_userCv"+result.id).replaceWith(resume); },error:function(err){ console.log(err); } }); } } }); }); function EditUserCv(id) { $('#frmEditResume').trigger('reset'); $('#user_resume_id_edit').val(id); $.ajax({ type: "GET", url: "/user/attachment/edit" + "/" + id , success: function(result) { // console.log(result); $('#ModalEditUserCv').modal('show'); $('#resume_edit').val(result.file_name); },error : function(err){ console.log(err); } }); } function DeleteUserCv(id) { $('#ModalDeleteUserCv').modal('show'); $('#user_resume_id').val(id); // console.log(id); } $('#frmDeleteResume').validate({ submitHandler: function (form) { var id = $('#user_resume_id').val(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); jQuery.ajax({ url: "/user/attachment/delete" + '/' + id, method: 'Delete', success: function (response) { $('#ModalDeleteUserCv').modal('hide'); $('#tr_userCv'+response.id).remove(); toastr.success('Success', 'item has been deleted !'); }, error: function (err) { console.log(err); } }); } }); function UploadResume(){ $('#UserUploadResume').modal('show'); $('#frmUploadResume').trigger('reset'); } $(document).ready(function () { $('#frmUploadResume').validate({ rules : { file_name : { required : true, } } ,submitHandler : function (e) { var id = $('#user_resume_id').val(); var extension = $('#file_name').val().split('.').pop().toLowerCase(); if ($.inArray(extension, ['docx','pdf', 'doc', 'xlsx']) == -1) { toastr.warning('Please Select Valid File !'); // $('#errormessage').html('Please Select Valid File... '); } else { var file_data = $('#file_name').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url: "/user/attachment/" + id, // point to server-side PHP script data: form_data, type: 'POST', dataType:"json", contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData: false, success: function(result) { $('#UserUploadResume').modal('hide'); toastr.success('Success', 'item has been deleted !'); var resume = '<tr id="tr_userCV' + result.id + '"><td>' + result.file_name + '</td><td>' + result.file_size + '</td><td>' + result.attachment_type + '</td>'; var resume = '<tr id="tr_userCV' + result.id + '"><td>' + result.file_name + '</td><td>' + result.file_size + '</td><td>' + result.attachment_type + '</td>'; resume += '<th><a onclick="EditUserCv('+ result.id + ');" data-toggle="modal"><i class="fa fa-edit" aria-hidden="true"></i> | </a><a onclick="DeleteUserCv(' + result.id + ');"><i style="color:red;" class="fa fa-trash" aria-hidden="true"></i></a></th></tr>'; $('#tbl_resume').append(resume); },error:function(err){ console.log(err); } }); } } }); }); function NotLogin() { $.ajax({ type: "GET", url: "/check/user/login" , success: function(result) { console.log(result); toastr.warning('The user is not logined in the system !'); // $('#UserNotLogin').modal('show'); // $('#category_name_edit').val(result.name); },error : function(err){ console.log(err); } }); }<gh_stars>1-10 // @flow import fs from 'mz/fs'; import {Account, Connection, BpfLoader, PublicKey} from '@solana/web3.js'; import semver from 'semver'; import {Token, TokenAmount} from '../client/token'; import {url} from '../url'; import {newAccountWithLamports} from '../client/util/new-account-with-lamports'; import {sleep} from '../client/util/sleep'; import {Store} from '../client/util/store'; // Loaded token program's program id let programId: PublicKey; // A token created by the next test and used by all subsequent tests let mintOwner: Account; let testToken: Token; // Initial token account let testAccountOwner: Account; let testAccount: PublicKey; function assert(condition, message) { if (!condition) { console.log(Error().stack + ':token-test.js'); throw message || 'Assertion failed'; } } async function didThrow(func, args): Promise<boolean> { try { await func.apply(args); } catch (e) { return true; } return false; } let connection; export async function getConnection(): Promise<Connection> { if (connection) return connection; let newConnection = new Connection(url, 'recent', ); console.log("get version"); var version = null; for (var i = 0; i < 20; i++) { try { version = await newConnection.getVersion(); break; } catch (e) { console.log("error: " + e); await sleep(200); } } console.log("done"); // commitment params are only supported >= 0.21.0 const solanaCoreVersion = version['solana-core'].split(' ')[0]; if (semver.gte(solanaCoreVersion, '0.21.0')) { newConnection = new Connection(url, 'recent'); } // eslint-disable-next-line require-atomic-updates connection = newConnection; console.log('Connection to cluster established:', url, version); return connection; } async function loadProgram(connection: Connection, payer, path: string): Promise<PublicKey> { const NUM_RETRIES = 500; /* allow some number of retries */ const data = await fs.readFile(path ); const { feeCalculator } = await connection.getRecentBlockhash(); const balanceNeeded = feeCalculator.lamportsPerSignature * (BpfLoader.getMinNumSignatures(data.length) + NUM_RETRIES) + (await connection.getMinimumBalanceForRentExemption(data.length)); const program_account = new Account(); console.log('Loading program:', path); for (var i = 0; i < 10; i++) { try { await BpfLoader.load(connection, payer, program_account, data); break; } catch (e) { } } console.log("done"); return program_account.publicKey; } async function GetPrograms(connection: Connection, payer: Account, verbose: boolean = false): Promise<PublicKey> { const store = new Store(); let tokenProgramId = null; try { const config = await store.load('config.json'); console.log('Using pre-loaded Token program'); console.log(' Note: To reload program remove client/util/store/config.json'); tokenProgramId = new PublicKey(config.tokenProgramId); console.log("Checking that account exists.."); const info = await connection.getAccountInfo(tokenProgramId); if (verbose) { console.log(".. got account info: "); console.dir(info); } if (info === null) { console.log("account doesn't exist..creating new"); throw new Error('failed to find account'); } } catch (err) { tokenProgramId = await loadProgram(connection, payer, '../target/bpfel-unknown-unknown/release/spl_token.so'); await store.save('config.json', { tokenProgramId: tokenProgramId.toString(), }); } return tokenProgramId; } export async function loadTokenProgram(connection, payer): Promise<void> { programId = await GetPrograms(connection, payer); console.log('Token Program ID', programId.toString()); } export async function loadOrCreateAccount(file, connection, verbose: boolean = false): Account { var account: Account; try { if (verbose) { console.log("Loading account from " + file); } var buffer = fs.readFileSync(file); account = new Account(Uint8Array.from(buffer)); if (verbose) { console.log("loaded " + account.publicKey); } /*const info = await connection.getAccountInfo(account.publicKey); if (info) { console.log(" using account with " + info.lamports + " lamports."); } else { console.log(" account not loaded yet."); }*/ } catch (err) { if (verbose) { console.log("account doesn't exist. " + err); } var account = new Account(); fs.writeFileSync(file, account.secretKey); /*const info = await connection.getAccountInfo(account.publicKey); console.dir(info); if (info) { console.log(" using payer with " + info.lamports + " lamports."); } else { console.log(" account not loaded yet."); }*/ } return account; } export async function createMint(connection, payer, id, amount, verbose): Promise<Account> { mintOwner = await loadOrCreateAccount("accounts/mint_owner_" + id + ".json", connection); var mintAccount = await loadOrCreateAccount("accounts/mint_" + id + ".json", connection); testAccountOwner = await loadOrCreateAccount("accounts/test_owner_" + id + ".json", connection); var initialTokenAccount = await loadOrCreateAccount("accounts/first_token_account_" + id + ".json", connection); console.log("creating mint.."); [testToken, testAccount] = await Token.createMint( connection, payer, mintAccount, mintOwner.publicKey, testAccountOwner.publicKey, initialTokenAccount, new TokenAmount(amount), 2, programId, true, ); console.log("done."); const mintInfo = await testToken.getMintInfo(); if (verbose) { console.dir(mintInfo); } assert(mintInfo.decimals == 2); //assert(mintInfo.owner == null); const accountInfo = await testToken.getAccountInfo(testAccount); assert(accountInfo.mint.equals(testToken.publicKey)); assert(accountInfo.owner.equals(testAccountOwner.publicKey)); if (accountInfo.amount.toNumber() < amount) { console.log("minting to testToken"); await testToken.mintTo(testAccount, mintOwner, [], amount); } console.log("mint amount: " + accountInfo.amount.toNumber()); //assert(accountInfo.amount.toNumber() == amount); assert(accountInfo.delegate == null); assert(accountInfo.delegatedAmount.toNumber() == 0); } export async function createAccounts(numAccounts, id, verbose): Promise<void> { const balanceNeeded = await Token.getMinBalanceRentForExemptAccount( connection, ); console.log("balance needed: " + balanceNeeded); var destOwners = []; var num_success = 0; const chunkSize = 10; var numChunks = numAccounts / chunkSize; var total = 0; var accounts = []; for (var i = 0; i < numChunks; i++) { var create_promises = []; for (var j = 0; j < chunkSize; j++) { if (total >= numAccounts) { break; } total += 1; const destOwner = await loadOrCreateAccount("accounts/account_owner_" + id + "_" + total + ".json", connection); const newAccount = await loadOrCreateAccount("accounts/account_" + id + "_" + total + ".json", connection); create_promises.push( testToken.createAccount(destOwner.publicKey, newAccount, balanceNeeded / 8) .then((account) => { num_success += 1; return account; }) .catch(e => { console.log("error: ", e); }) ); destOwners.push(destOwner); } var new_accounts = await Promise.all(create_promises); accounts.push(...new_accounts); console.log("created: " + num_success); } assert(accounts.length > 0); for (var i = 0; i < accounts.length; i++) { let account = accounts[i]; let destOwner = destOwners[i]; if (verbose) { console.log("Getting info for " + account); } const accountInfo = await testToken.getAccountInfo(account); assert(accountInfo.mint.equals(testToken.publicKey)); assert(accountInfo.owner.equals(destOwner.publicKey)); if (verbose) { console.log(account + " has " + accountInfo.amount); } //assert(accountInfo.amount.toNumber() == 0); assert(accountInfo.delegate == null); } return [accounts, destOwners]; } // 100,000 transfers export async function token_transfer(numTransfer, accounts, owners, payers, amount, verbose): Promise<void> { if (verbose) { console.log("accounts: " + accounts.length); } var dests = new Map(); var num_success = 0; var num_error = 0; const accountInfo = await testToken.getAccountInfo(testAccount); //console.log("account info: "); //console.dir(accountInfo); if (accountInfo.amount.toNumber() < numTransfer * amount) { assert("not enough tokens!"); } var chunkSize = 10; var numChunks = accounts.length / chunkSize; var total = 0; for (var i = 0; i < accounts.length; i++) { let initial_balance = await testToken.getAccountInfo(accounts[i]); if (initial_balance) { dests.set(accounts[i], initial_balance.amount.toNumber()); } } // Fund accounts from mint var start = Date.now(); for (var i = 0; i < numChunks; i++) { var transfer_promises = []; for (var j = 0; j < chunkSize; j++) { if (total >= accounts.length) { break; } total += 1; const dest = accounts[total % accounts.length]; //console.log("transfer to " + dest); const payer = payers[total % payers.length]; transfer_promises.push(testToken.transfer(testAccount, dest, testAccountOwner, [], amount, payer) .then(() => { num_success += 1; }) .catch(e => { console.log(dest + " error: " + e + " " + dests.get(dest)); dests.set(dest, dests.get(dest) - amount); num_error += 1; }) ); if (dests.has(dest)) { dests.set(dest, dests.get(dest) + amount); } else { dests.set(dest, amount); } } await Promise.all(transfer_promises); if ((Date.now() - start) > 2000) { console.log("transfers: num_success: " + num_success + " error: " + num_error); start = Date.now(); } } const NUM_POLL = 10; for (var i = 0; i < NUM_POLL; i++) { for (let [dest, amount] of dests) { let destAccountInfo = await testToken.getAccountInfo(dest); if (verbose) { console.log(dest + " has " + destAccountInfo.amount + " expected: " + amount); } if (destAccountInfo.amount.toNumber() === amount) { dests.delete(dest); } } if (verbose) { console.log("accounts left: " + dests.size); } if (dests.size == 0) { break; } //assert(destAccountInfo.amount.toNumber() == 1); await sleep(200); } assert(dests.size == 0); console.log("starting inter-account transfers " + accounts.length); // Do some transfers between accounts. num_success = 0; num_error = 0; if (accounts.length > 2) { var chunkSize = 10; var numChunks = numTransfer / chunkSize; var total = 0; var start = Date.now(); for (var i = 0; i < numChunks; i++) { var transfer_promises = []; for (var j = 0; j < chunkSize; j++) { if (total >= numTransfer) { break; } const payer = payers[total % payers.length]; const src_idx = (total * 2) % accounts.length; const dst_idx = (total * 2 + 1) % accounts.length; const src = accounts[src_idx]; const srcOwner = owners[src_idx]; const dest = accounts[dst_idx]; //console.log("transferring " + src_idx + " to " + dst_idx); total += 1; transfer_promises.push( testToken.transfer(src, dest, srcOwner, [], 1, payer) .then((x) => { num_success += 1; }) .catch(e => { num_error += 1; console.log("transfer error: " + e); }) ); } if ((Date.now() - start) > 10000) { console.log("transfers: num_success: " + num_success + " error: " + num_error); start = Date.now(); } await Promise.all(transfer_promises); } } console.log("done.. success: " + num_success + " error: " + num_error); } // 100,000 mint export async function mintTo(accounts, num_mint): Promise<void> { const connection = await getConnection(); var num_success = 0; var num_error = 0; const chunkSize = 10; const numChunks = num_mint / chunkSize; var total = 0; var start = Date.now(); for (var i = 0; i < numChunks; i++) { var mint_promises = []; for (var j = 0; j < chunkSize; j++) { if (total > num_mint) { break; } total += 1; var dest = accounts[total % accounts.length]; mint_promises.push( testToken.mintTo(dest, mintOwner, [], 42) .then(() => { num_success += 1; }) .catch(e => { console.log(" " + dest + " mint error: " + e); num_error += 1; }) ); } await Promise.all(mint_promises); if ((Date.now() - start) > 10000) { console.log(" mint success: " + num_success + " error: " + num_error + " " + (Date.now() - start) + " ms"); start = Date.now(); } } } // 75,000 burns export async function burn(accounts, owners, numBurn, payers): Promise<void> { var burnPromises = []; var chunkSize = 10; var numChunks = numBurn / chunkSize; var numBurned = 0; var num_success = 0; var num_fail = 0; var total = 0; var start = Date.now(); for (var i = 0; i < numChunks; i++) { for (var j = 0; j < chunkSize; j++) { if (total >= numBurn) { break; } total += 1; var dest = accounts[total % accounts.length]; var destOwner = owners[total % accounts.length]; var payer = payers[total % payers.length]; numBurned += 1; burnPromises.push( testToken.burn(dest, destOwner, [], 1, payer) .then((account) => { num_success += 1; }) .catch(e => { console.log("burn error: " + e); num_fail += 1; })); } await Promise.all(burnPromises); if ((Date.now() - start) > 2000) { console.log("burned " + numBurned + " success: " + num_success + " num_fail: " + num_fail + " " + (Date.now() - start) + " ms"); start = Date.now(); } } console.log("Done burning."); /*for (var j = 0; j < 100; j++) { accountInfo = await testToken.getAccountInfo(testAccount); if (accountInfo.amount.toNumber() == amount - 1) { break; } await sleep(100); }*/ } import { createAction, handleAction, handleActions } from 'redux-actions' import { createSelector } from 'reselect' import { byIdSelectorCreator } from './selectorCreators' import { getFilteredList } from './filter' import { getCurrentDatasetMeta } from './dataset' import immutableUpdate from 'immutable-update'; import deep from 'deep-get-set' import store from '../store' import { addRecords, selectNone, getSelectedRecordsAsObject } from './select' export function selectAll() { return dispatch => { let state = store.getState() let meta = getCurrentDatasetMeta(state) let all = getFilteredList(state) dispatch(addRecords(all)) } } export function invertSelection() { return dispatch => { let state = store.getState() let meta = getCurrentDatasetMeta(state) // let all = getFilteredList(state) let current = getSelectedRecordsAsObject(state) let all = [] let rev = [] for (let i = 0; i < meta.records; i++){ if (!current[i]){ rev.push(i) } else { all.push(i) } } dispatch(selectNone()) dispatch(addRecords(rev)) } } export function selectInverse() { return dispatch => { let state = store.getState() let meta = getCurrentDatasetMeta(state) let all = [] for (let i = 0; i < meta.records; i++){ all.push(i) } dispatch(addRecords(all)) } } const express = require("express"); const Food = require("../food/foodModel"); const checkToken = require("../middleware/checkToken"); const validateFood = require("../middleware/validateFood"); const router = express(); // GET all food items router.get("/", checkToken, (req, res) => { Food.findAll() .then((foodItems) => { res.status(200).json({ foodItems }); }) .catch((error) => { res.status(500).json({ error: error.message }); }); }); // POST new food item router.post("/", checkToken, validateFood, (req, res) => { const food = req.body; Food.insert(food) .then((newFood) => { res.status(201).json(newFood); }) .catch((error) => { res.status(500).json({ error: "Failed to create a new food item." }); }); }); // GET food item by id router.get("/:id", checkToken, (req, res) => { const id = req.params.id; Food.findByID(id) .then((foodItem) => { if (foodItem) { res.status(200).json(foodItem); } else { res.status(404).json({ message: "That food item wasn't found." }); } }) .catch((error) => { res.status(500).json({ error: error.message }); }); }); // Update (PUT) food item by id router.put("/:id", checkToken, (req, res) => { const id = req.params.id; const updates = req.body; Food.findByID(id) .then((found) => { if (found) { Food.update(id, updates) .then((foodItem) => { res.status(200).json(foodItem); }) .catch((error) => { res .status(500) .json({ error: "Sorry, the food item couldn't be updated." }); }); } else { res .status(404) .json({ message: "Sorry, that food item doesn't exist." }); } }) .catch((error) => { res.status(500).json({ error: "There was an error finding that food item. Please try again.", }); }); }); // Delete food item by id router.delete("/:id", checkToken, (req, res) => { const id = req.params.id; Food.findByID(id) .then((found) => { if (found) { Food.removeFood(id) .then((response) => { res.status(204).end(); }) .catch((error) => { res .status(500) .json({ error: "Sorry, the food item couldn't be deleted." }); }); } else { res .status(404) .json({ message: "Sorry, that food item doesn't exist." }); } }) .catch((error) => { res.status(500).json({ error: error.message, }); }); }); module.exports = router; <reponame>kardiachain/nifty-wallet<gh_stars>1-10 import React, {Component} from 'react' import { connect } from 'react-redux' import Identicon from '../identicon' import { addressSummary } from '../../util' import EthBalance from '../eth-balance' import TokenBalance from '../token-balance' import { getMetaMaskAccounts } from '../../../../ui/app/selectors' import PropTypes from 'prop-types' class SendProfile extends Component { static propTypes = { address: PropTypes.string, account: PropTypes.object, identity: PropTypes.object, network: PropTypes.string, conversionRate: PropTypes.number, currentCurrency: PropTypes.string, isToken: PropTypes.bool, token: PropTypes.any, } render () { const props = this.props const { address, account, identity, network, conversionRate, currentCurrency, isToken, token, } = props return ( <div className="account-data-subsection" style={{ // background: 'linear-gradient(rgb(84, 36, 147), rgb(104, 45, 182))', background: 'transparent', paddingLeft: '14px', paddingRight: '14px' }} > {/* header - identicon + nav */} <div className="flex-row"> <div className="flex-column flex-center" style={{marginRight: 12}}> {/* large identicon*/} <div className="identicon-wrapper flex-column flex-center select-none" style={{ display: 'inline-block' }} > <Identicon diameter={44} address={address} /> </div> {/* invisible place holder */} {/* <i className="fa fa-users fa-lg invisible" style={{ marginTop: '28px' }} /> */} </div> {/* account label */} <div className="flex-column" style={{ alignItems: 'flex-start' }} > <h2 className="send-profile-identity-name font-medium flex-center" style={{ // color: '#ffffff', paddingTop: '8px', marginBottom: '8px', fontWeight: '600' }} >{identity && identity.name}</h2> {/* address and getter actions */} <div className="flex-row flex-center" style={{ color: 'rgba(28, 28, 40, 0.26)', // marginBottom: '30px', }} > <div className="send-profile-address" style={{ lineHeight: '16px', fontSize: '14px' }}> {addressSummary(network, address)} </div> </div> </div> </div> {/* balance */} <div className="flex-row flex-start" style={{ background: 'rgb(255, 255, 255)', boxShadow: 'rgb(40 41 61 / 4%) 0px 0px 2px, rgb(96 97 112 / 16%) 0px 4px 8px', borderRadius: 8, padding: 12, marginTop: 8 }} > {isToken ? <TokenBalance token={token} /> : <EthBalance {...{ value: account && account.balance, conversionRate, currentCurrency, network, showFiat: false }} />} </div> </div> ) } } function mapStateToProps (state) { const accounts = getMetaMaskAccounts(state) const result = { address: state.metamask.selectedAddress, accounts, identities: state.metamask.identities, network: state.metamask.network, conversionRate: state.metamask.conversionRate, currentCurrency: state.metamask.currentCurrency, } result.account = result.accounts[result.address] result.identity = result.identities[result.address] return result } module.exports = connect(mapStateToProps)(SendProfile) import 'react-native'; import {createTestDriver} from 'rehabjs'; import FetchModule from 'rehabjs/modules/fetch'; import ReactNativeModule from 'rehabjs/modules/react-native'; const TODOS = [1, 2].map((id) => ({ userId: 1, id: id, title: 'todo' + id, completed: id % 2 === 0, })); const fetchModule = new FetchModule(); const RNModule = new ReactNativeModule(); const screenDriver = createTestDriver({ componentGenerator: () => require('./index').default, modules: [fetchModule, RNModule], mockedData: { [fetchModule.getMockKey()]: { 'https://jsonplaceholder.typicode.com/todos': TODOS.slice(), 'https://jsonplaceholder.typicode.com/todos/1': {...TODOS[0]}, 'https://jsonplaceholder.typicode.com/todos/2': {...TODOS[1]}, } } }); describe('TodoList', () => { it('fetches', async () => { const driver = screenDriver({passProps: {componentId: 'test'}}); await driver.run().validate({ '[fetch]': [ { body: undefined, url: 'https://jsonplaceholder.typicode.com/todos', }, ], }); }); }); <reponame>UnifiedFactory/ejs-rendered-loader const util = require("util"); const webpack = util.promisify(require("webpack")); const chalk = require("chalk"); async function build() { console.log(`Creating test build...`); try { const config = require(`./webpack.config`); console.log("Compiling app..."); const stats = await webpack(config); if (stats.compilation && stats.compilation.errors && stats.compilation.errors.length) { console.log(chalk.red("Failed to compile.\n")); stats.compilation.errors.forEach(error => { console.log(chalk.red(`${error.message}\n`)); }); process.exit(1); return; } console.log(chalk.green("Compiled successfully.\n")); } catch (e) { console.log(chalk.red("Failed to compile.\n")); console.log(e + "\n"); process.exit(1); } } build(); <filename>test_nodejs/server.js /** * server.js * * Purpose: * * Description: * * History: * 2019/11/20, Created by jumperchen * * Copyright (C) 2019 Potix Corporation. All Rights Reserved. */ 'use strict'; var http = require('http').createServer(); var io = require('socket.io')(http); io.on('connection', function(socket){ console.log('connection default namespace'); socket.on('msg', function (data, ack) { if (ack != null) { ack(1, 2, 3); } console.log(`data from default => ${data}`); socket.emit('fromServer', `${data}`); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); import React from "react"; import styled from "@emotion/styled"; import { Input, Button } from "./shared/Form"; const SearchForm = styled.div` display: flex; align-items: center; > button { margin-left: 1rem; } `; const Search = ({ inputVal, onChange, onSearch }) => { return ( <SearchForm> <Input value={inputVal} onChange={onChange} /> <Button onClick={onSearch}>Search</Button> </SearchForm> ); }; export default Search; <reponame>slowerthanlightspeed/infer_combinations var availablePuzzles = [ [ [1,2,0,"rw3"], [2,0,1,"rw3"] ], [ [1,2,0,"rw3"], [3,1,2,"rr2"] ], [ [1,2,0,"rw3"], [0,3,2,"rr2"] ], [ [1,2,0,"rw3"], [0,1,3,"rr2"] ], [ [2,0,1,"rw3"], [3,1,2,"rr2"] ], [ [2,0,1,"rw3"], [0,3,2,"rr2"] ], [ [2,0,1,"rw3"], [0,1,3,"rr2"] ], [ [1,2,0,"rw3"], [3,1,0,"rr1rw1"] ], [ [1,2,0,"rw3"], [1,3,2,"rr1rw1"] ], [ [1,2,0,"rw3"], [0,2,3,"rr1rw1"] ], [ [2,0,1,"rw3"], [3,0,2,"rr1rw1"] ], [ [2,0,1,"rw3"], [0,3,1,"rr1rw1"] ], [ [2,0,1,"rw3"], [2,1,3,"rr1rw1"] ], [ [1,2,0,"rw3"], [0,3,4,"rr1"] ], [ [1,2,0,"rw3"], [3,1,4,"rr1"] ], [ [1,2,0,"rw3"], [3,4,2,"rr1"] ], [ [2,0,1,"rw3"], [0,3,4,"rr1"] ], [ [2,0,1,"rw3"], [3,1,4,"rr1"] ], [ [2,0,1,"rw3"], [3,4,2,"rr1"] ], [ [1,2,0,"rw3"], [3,0,4,"rw1"] ], [ [1,2,0,"rw3"], [3,4,1,"rw1"] ], [ [1,2,0,"rw3"], [2,3,4,"rw1"] ], [ [2,0,1,"rw3"], [3,4,0,"rw1"] ], [ [2,0,1,"rw3"], [1,3,4,"rw1"] ], [ [2,0,1,"rw3"], [3,2,4,"rw1"] ], [ [0,2,1,"rr1rw2"], [3,1,2,"rr2"] ], [ [0,2,1,"rr1rw2"], [0,3,2,"rr2"] ], [ [0,2,1,"rr1rw2"], [0,1,3,"rr2"] ], [ [1,0,2,"rr1rw2"], [3,1,2,"rr2"] ], [ [1,0,2,"rr1rw2"], [0,3,2,"rr2"] ], [ [1,0,2,"rr1rw2"], [0,1,3,"rr2"] ], [ [2,1,0,"rr1rw2"], [3,1,2,"rr2"] ], [ [2,1,0,"rr1rw2"], [0,3,2,"rr2"] ], [ [2,1,0,"rr1rw2"], [0,1,3,"rr2"] ], [ [0,2,1,"rr1rw2"], [0,3,4,"rr1"] ], [ [0,2,1,"rr1rw2"], [3,1,4,"rr1"] ], [ [0,2,1,"rr1rw2"], [3,4,2,"rr1"] ], [ [1,0,2,"rr1rw2"], [0,3,4,"rr1"] ], [ [1,0,2,"rr1rw2"], [3,1,4,"rr1"] ], [ [1,0,2,"rr1rw2"], [3,4,2,"rr1"] ], [ [2,1,0,"rr1rw2"], [3,1,4,"rr1"] ], [ [2,1,0,"rr1rw2"], [0,3,4,"rr1"] ], [ [2,1,0,"rr1rw2"], [3,4,2,"rr1"] ], [ [3,1,2,"rr2"], [0,3,2,"rr2"] ], [ [3,1,2,"rr2"], [0,1,3,"rr2"] ], [ [0,3,2,"rr2"], [0,1,3,"rr2"] ], [ [3,0,1,"rw2"], [3,1,2,"rr2"] ], [ [3,2,1,"rw2"], [0,3,2,"rr2"] ], [ [3,2,1,"rw2"], [0,1,3,"rr2"] ], [ [2,3,0,"rw2"], [0,1,3,"rr2"] ], [ [3,1,2,"rr2"], [3,2,0,"rw2"] ], [ [3,1,2,"rr2"], [2,3,0,"rw2"] ], [ [3,1,2,"rr2"], [1,0,3,"rw2"] ], [ [0,3,2,"rr2"], [1,3,0,"rw2"] ], [ [0,3,2,"rr2"], [2,3,1,"rw2"] ], [ [0,3,2,"rr2"], [1,0,3,"rw2"] ], [ [0,1,3,"rr2"], [1,2,3,"rw2"] ], [ [0,1,3,"rr2"], [2,0,3,"rw2"] ], [ [3,1,2,"rr2"], [0,3,1,"rr1rw1"] ], [ [3,1,2,"rr2"], [0,2,3,"rr1rw1"] ], [ [0,3,2,"rr2"], [2,1,3,"rr1rw1"] ], [ [3,0,2,"rr1rw1"], [0,1,3,"rr2"] ], [ [3,1,0,"rr1rw1"], [0,3,2,"rr2"] ], [ [1,3,2,"rr1rw1"], [0,1,3,"rr2"] ], [ [3,1,2,"rr2"], [0,3,4,"rr1"] ], [ [3,1,2,"rr2"], [0,4,3,"rr1"] ], [ [0,3,2,"rr2"], [3,1,4,"rr1"] ], [ [0,3,2,"rr2"], [4,1,3,"rr1"] ], [ [0,1,3,"rr2"], [3,4,2,"rr1"] ], [ [0,1,3,"rr2"], [4,3,2,"rr1"] ], [ [3,1,2,"rr2"], [4,0,3,"rw1"] ], [ [3,1,2,"rr2"], [4,3,0,"rw1"] ], [ [0,3,2,"rr2"], [1,4,3,"rw1"] ], [ [0,3,2,"rr2"], [3,4,1,"rw1"] ], [ [0,1,3,"rr2"], [2,3,4,"rw1"] ], [ [0,1,3,"rr2"], [3,2,4,"rw1"] ], [ [3,0,2,"rr1rw1"], [4,1,3,"rr1"] ], [ [3,1,0,"rr1rw1"], [4,3,2,"rr1"] ], [ [0,3,1,"rr1rw1"], [3,4,2,"rr1"] ], [ [1,3,2,"rr1rw1"], [0,4,3,"rr1"] ], [ [0,2,3,"rr1rw1"], [3,1,4,"rr1"] ], [ [2,1,3,"rr1rw1"], [0,3,4,"rr1"] ] ]; var currentPuzzle = JSON.parse(JSON.stringify(availablePuzzles[0])); function shallowClonePrimitives(oldObject){ // needs fallback && singletonish var newObject = { ... oldObject }; return newObject; } var initTimer = 0; var theReplacements = [ [ "letter", ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] ], [ "number", [0,1,2,3,4,5,6,7,8,9] ], [ "pic", [ "<img class='choiceButton' src='circle.jpg' alt='circle'>", "<img class='choiceButton' src='square.jpg' alt='square'>", "<img class='choiceButton' src='star.jpg' alt='star'>", "<img class='choiceButton' src='triangle.jpg' alt='triangle'>", "<img class='choiceButton' src='diamond.jpg' alt='diamond'>", "<img class='choiceButton' src='gear.jpg' alt='gear'>" ] ] ]; var replacementType = ""; function makeButtons(){ // updates current puzzle at the same time if(initTimer){clearInterval(initTimer);} // var valueType = generateNewPuzzle(); // buttonAndInputHTML = generateHTML(valueType); // return buttonAndInputHTML; // BUILD A SET OF RANDOMIZED REPLACEMENT VALUES OR ITEMS var replacementReference = theReplacements[ Math.floor( Math.random()*theReplacements.length ) ]; replacementType = replacementReference[0]; var whichReplacements = JSON.parse(JSON.stringify(replacementReference[1])); var theseReplacements = []; for(var i=0; i<6; i++){ theseReplacements.push( (whichReplacements.splice( Math.floor(Math.random() * whichReplacements.length), 1 ))[0]); } console.log(theseReplacements); // MAKE A COPY OF A RANDOMLY CHOSEN PUZZLE var randomPuzzlePosition = Math.floor( Math.random()*availablePuzzles.length ); currentPuzzle = JSON.parse(JSON.stringify(availablePuzzles[randomPuzzlePosition])); // currentPuzzle = [ [1,0,2,"rw3"],[0,3,4,"rr1"] ]; // APPLY RANDOMIZED REPLACEMENTS TO CHOSEN PUZZLE COPY currentPuzzle[0][0] = theseReplacements[ currentPuzzle[0][0] ]; currentPuzzle[0][1] = theseReplacements[ currentPuzzle[0][1] ]; currentPuzzle[0][2] = theseReplacements[ currentPuzzle[0][2] ]; currentPuzzle[1][0] = theseReplacements[ currentPuzzle[1][0] ]; currentPuzzle[1][1] = theseReplacements[ currentPuzzle[1][1] ]; currentPuzzle[1][2] = theseReplacements[ currentPuzzle[1][2] ]; // BUILD INTERFACE HTML var hintHTML, hintHTML0, hintHTML1; if(replacementType !== "pic"){ hintRows.style.width="275px;"; hintHTML0 = '<div class="hintWrapper clearfix">'; hintHTML0 += '<button class="onTheBoard">' + currentPuzzle[0][0] + '</button>'; hintHTML0 += '<button class="onTheBoard">' + currentPuzzle[0][1] + '</button>'; hintHTML0 += '<button class="onTheBoard">' + currentPuzzle[0][2] + '</button>'; hintHTML0 += (currentPuzzle[0][3] ? '<img src="' + currentPuzzle[0][3] + '.png" alt="' + currentPuzzle[0][3] + '">' : '' ); hintHTML0 += '</div>'; hintHTML1 = '<div class="hintWrapper clearfix">'; hintHTML1 += '<button class="onTheBoard">' + currentPuzzle[1][0] + '</button>'; hintHTML1 += '<button class="onTheBoard">' + currentPuzzle[1][1] + '</button>'; hintHTML1 += '<button class="onTheBoard">' + currentPuzzle[1][2] + '</button>'; hintHTML1 += (currentPuzzle[1][3] ? '<img src="' + currentPuzzle[1][3] + '.png" alt="' + currentPuzzle[1][3] + '">' : '' ); hintHTML1 += '</div>'; } else{ hintRows.style.width="320px;"; hintHTML0 = '<div class="hintWrapper clearfix" style="height:80px; width:320px;">'; hintHTML0 += currentPuzzle[0][0]; hintHTML0 += currentPuzzle[0][1]; hintHTML0 += currentPuzzle[0][2]; hintHTML0 += (currentPuzzle[0][3] ? '<img src="' + currentPuzzle[0][3] + '.png" alt="' + currentPuzzle[0][3] + '">' : '' ); hintHTML0 += '</div>'; hintHTML1 = '<div class="hintWrapper clearfix" style="height:80px; width:320px;">'; hintHTML1 += currentPuzzle[1][0]; hintHTML1 += currentPuzzle[1][1]; hintHTML1 += currentPuzzle[1][2]; hintHTML1 += (currentPuzzle[1][3] ? '<img src="' + currentPuzzle[1][3] + '.png" alt="' + currentPuzzle[1][3] + '">' : '' ); hintHTML1 += '</div>'; } if(Math.round(Math.random())){ hintHTML = hintHTML0 + hintHTML1; } else{ hintHTML = hintHTML1 + hintHTML0; } // RESET THE TIMER var handOff = setTimeout(function(){ document.getElementById("liveMinutes").innerHTML = "0:"; document.getElementById("liveSeconds").innerHTML = "00"; s = 0; initTimer = setInterval(function(){incrementTimer()},1000); },1000); // RETURN THE INTERFACE HTML return hintHTML; } var s = 0; function incrementTimer(){ s++; var correctedSeconds = s%60 < 10 ? "0" + s%60 : s%60; document.getElementById("liveMinutes").innerHTML = Math.floor(s/60) + ":"; document.getElementById("liveSeconds").innerHTML = correctedSeconds; } hintRows.innerHTML = makeButtons(); var textInputs = document.getElementsByTagName("INPUT"); var imageInputs = document.getElementsByTagName("IMG"); textInputs[0].focus(); hintRows.addEventListener("click",doStuff,false); // clearPartialAnswer.addEventListener("click",clearStuff,false); for(var i=0, imax=textInputs.length;i<imax; i++){ textInputs[i].addEventListener("keyup",doOtherStuff,false); } function doStuff(e){ if(e.target.tagName === "BUTTON" && e.target.className === "onTheBoard"){ var replacementTypeElements = { number:textInputs, letter:textInputs, pic:imageInputs }; var replacementTypeBools = { number: function(j){return textInputs[j].value == "";}, letter: function(j){return textInputs[j].value == "";}, pic: function(j){return imageInputs[j].src === "blank.png";} }; var replacementTypeInput = { // mutates input number: function(thisElement){thisElement.value = e.target.innerHTML;}, letter: function(thisElement){thisElement.value = e.target.innerHTML;}, pic: function(thisElement){thisElement.src = e.target.src;} }; for(var i=0, imax=replacementTypeElements[replacementType].length; i<imax; i++){ if(replacementTypeElements[replacementType][i].value == e.target.innerHTML){ // possibly do an animation on the input to show that it already exists in the answer break; } else if(replacementTypeBools[replacementType](i)){ replacementTypeInput[replacementType](replacementTypeElements[replacementType][i]); break; } } var howManyFull = 0; for(i=0, imax=replacementTypeElements[replacementType].length; i<imax; i++){ if(!replacementTypeBools[replacementType](i)){ howManyFull++; } } if(howManyFull === 3){ var handoff = setTimeout(function(){alert( checkAnswer() );},20); } } } function doOtherStuff(e){ var thisInput = e.target; var whichKey = e.which; if(whichKey === 13){ var handoff = setTimeout(function(){alert( checkAnswer() );},20); } else if(whichKey > 47 && !e.metaKey && !e.altKey && !e.ctrlKey ){ var howManyFull = 0; for(var i=0, imax=textInputs.length; i<imax; i++){ if(textInputs[i].value !== ""){ howManyFull++; } } if(howManyFull === 3){ var handoff = setTimeout(function(){alert( checkAnswer() );},20); } else{ if(thisInput.id === "tinput1"){document.getElementById("tinput2").focus();} else if(thisInput.id === "tinput2"){document.getElementById("tinput3").focus();} else{document.getElementById("tinput1").focus();} } } } function clearStuff(){ for(var i=0, imax=textInputs.length; i<imax; i++){ textInputs[i].value = ""; } } var patterns = { rr1: function rr1(iArr){ return [ [ iArr[0],null,null, [ iArr[1],iArr[2] ] ], [ null,iArr[1],null, [ iArr[0],iArr[2] ] ], [ null,null,iArr[2], [ iArr[0],iArr[1] ] ] ]; }, rr2: function rr2(iArr){ return [ [ iArr[0],iArr[1],null, [iArr[2]] ], [ iArr[0],null,iArr[2], [iArr[1]] ], [ null,iArr[1],iArr[2], [iArr[0]] ] ]; }, rr3: function rr3(iArr){ return [ [ iArr[0],iArr[1],iArr[2], [] ] ]; }, rw1: function rw1(iArr){ return [ [ null,iArr[0],null, [ iArr[1],iArr[2] ] ], [ null,null,iArr[0], [ iArr[1],iArr[2] ] ], [ iArr[1],null,null, [ iArr[0],iArr[2] ] ], [ null,null,iArr[1], [ iArr[0],iArr[2] ] ], [ iArr[2],null,null, [ iArr[0],iArr[1] ] ], [ null,iArr[2],null, [ iArr[0],iArr[1] ] ] ]; }, rw2: function rw2(iArr){ return [ [ null,iArr[0],iArr[1], [iArr[2]] ], [ null,iArr[2],iArr[0], [iArr[1]] ], [ null,iArr[2],iArr[1], [iArr[0]] ], [ iArr[1],null,iArr[0], [iArr[2]] ], [ iArr[1],iArr[0],null, [iArr[2]] ], [ iArr[1],iArr[2],null, [iArr[0]] ], [ iArr[2],null,iArr[0], [iArr[1]] ], [ iArr[2],null,iArr[1], [iArr[0]] ], [ iArr[2],iArr[0],null, [iArr[1]] ] ]; }, rw3: function rw3(iArr){ return [ [ iArr[2],iArr[0],iArr[1], [] ], [ iArr[1],iArr[2],iArr[0], [] ] ]; }, rr1rw1: function rr1rw1(iArr){ return [ [ iArr[0],null,iArr[1], [iArr[2]] ], [ iArr[0],iArr[2],null, [iArr[1]] ], [ null,iArr[1],iArr[0], [iArr[2]] ], [ iArr[2],iArr[1],null, [iArr[0]] ], [ null,iArr[0],iArr[2], [iArr[1]] ], [ iArr[1],null,iArr[2], [iArr[0]] ] ]; }, rr1rw2: function rr1rw2(iArr){ return [ [ iArr[0],iArr[2],iArr[1], [] ], [ iArr[2],iArr[1],iArr[0], [] ], [ iArr[1],iArr[0],iArr[2], [] ] ]; } }; /* MY CURRENTLY SUGGESTED ORDERING OF CALLS TO THE ABOVE PATTERNS: rr3 (1 combo, with 3 known values and unknown values), rw3 (2 combos, with 3 known values and 0 unknown values), rr1rw2 (3 combos, with 3 known values and 0 unknown values), rr2 (3 combos, with 2 known values and one known not-value), rr1 (3 combos, with 1 known value and two known not-values), rr1rw1 (6 combos, with 2 known values and 1 unknown value), rw1 (6 combos, with 1 known value and 2 unknown values), rw2 (9 combos, with 2 known values and one known not-value) */ var testOrder = {rr3:0, rw3:1, rr1rw2:2, rr2:3, rr1:4, rr1rw1:5, rw1:6, rw2:7}; function preOrderComparisons(arrays){ // determine the order in which to compare the arrays to one another var tempSearchOrder = [], searchOrder = [], whichSO = 0; for(var i=0, imax=arrays.length; i<imax; i++){ whichSO = testOrder[ arrays[i][ arrays[i].length-1 ] ]; // console.log("whichSO: " + whichSO); (tempSearchOrder[ whichSO ] ? tempSearchOrder[ whichSO ].push(arrays[i]) : tempSearchOrder[ whichSO ] = [arrays[i]] ); } for(var j=0; j<tempSearchOrder.length; j++){ if(tempSearchOrder[j]){ while(tempSearchOrder[j].length){ searchOrder.push( tempSearchOrder[j].pop() ); } } } // create a test array from the first row var whichPattern = searchOrder[0][ searchOrder[0].length-1 ]; // avoid mutations; make a copy of the first array in the searchOrder var copyOfFirstArr = JSON.parse( JSON.stringify( searchOrder[0] ) ); //candidate for shallowClonePrimitives // remove the type data from the end of the copy of the first array in the searchOrder copyOfFirstArr.pop(); // create a workingArr (a set of arrays) from that trimmed copyOfFirstArr var workingArr = patterns[whichPattern](copyOfFirstArr); // remove the first array from the searchOrder (because we've used it to make a workingArr and don't want to compare itself to its own workingArr!) searchOrder.shift(); // then call the compare function using the current workingArr and the remaining set of arrays return compare(workingArr, searchOrder); } function preOrderComparisons2(arrays){ // determine the order in which to compare the arrays to one another var tempSearchOrder = [], searchOrder = [], whichSO = 0; for(var i=0, imax=arrays.length; i<imax; i++){ whichSO = testOrder[ arrays[i][ arrays[i].length-1 ] ]; (tempSearchOrder[ whichSO ] ? tempSearchOrder[ whichSO ].push(arrays[i]) : tempSearchOrder[ whichSO ] = [arrays[i]] ); } for(var j=0; j<tempSearchOrder.length; j++){ if(tempSearchOrder[j]){ while(tempSearchOrder[j].length){ searchOrder.push( tempSearchOrder[j].pop() ); } } } // create a test array from the first row var whichPattern = searchOrder[0][ searchOrder[0].length-1 ]; // avoid mutations; make a copy of the first array in the searchOrder var copyOfFirstArr = JSON.parse( JSON.stringify( searchOrder[0] ) ); //candidate for shallowClonePrimitives // remove the type data from the end of the copy of the first array in the searchOrder copyOfFirstArr.pop(); // create a workingArr (a set of arrays) from that trimmed copyOfFirstArr var workingArr = patterns[whichPattern](copyOfFirstArr); // remove the first array from the searchOrder (because we've used it to make a workingArr and don't want to compare itself to its own workingArr!) searchOrder.shift(); // then call the compare function using the current workingArr and the remaining set of arrays return compare2(workingArr, searchOrder); } function compare(workingArr, compArrs){ // workingArr is an array of arrays (its arrays represent combinations built from the initial preOrderComparisons determined array [which may have subsequently been trimmed during recursive compares]) var i=0, j=0, k=0, m=0, n=0, p=0, imax=workingArr.length, jmax=0, kmax=0, mmax=0, nmax=0, pmax=0; var workingArrRemovals = []; var copyOfCompArr0, compArr0pattern; var newWorkingArr = [], intermediateWorkingArr = [], intermediateRemovals; var copyOfCurrentWArow = [], combinedArray = []; // loop through the workingArr for(;i<imax;i++){ // get the type of the row from the first comparison array compArr0pattern = compArrs[0][ compArrs[0].length-1 ]; // then make a copy of the first of the compArrs copyOfCompArr0 = JSON.parse( JSON.stringify( compArrs[0] ) ); //candidate for shallowClonePrimitives // trim the type element out of the copyOfCompArr0 copyOfCompArr0.pop(); // update the workingArrRemovals variable workingArrRemovals = workingArr[i][ workingArr[i].length-1 ]; // if there are any workingArrRemovals, replace them with null wherever they appear in the copyOfCompArr0 j=0, jmax = workingArrRemovals.length; for(;j<jmax;j++){ k=0, kmax=copyOfCompArr0.length; for(;k<kmax;k++){ if(copyOfCompArr0[k]===workingArrRemovals[j]){ copyOfCompArr0[k] = null; } } } // then, send the remaining copyOfCompArr0 to its patterns function (use and strip its type) intermediateWorkingArr = patterns[compArr0pattern](copyOfCompArr0); // then, loop through the response from the patterns function m=0, mmax = intermediateWorkingArr.length; for(;m<mmax;m++){ // make a copy of the current row from the initial workingArr copyOfCurrentWArow = JSON.parse( JSON.stringify( workingArr[i] ) ); //candidate for shallowClonePrimitives copyOfCurrentWArow.pop(); // do the first of a set of tests for validity, which, if all passed, will then place a newly combined array into into the newWorkingArr p=0, pmax = copyOfCurrentWArow.length, combinedArray = [null,null,null]; for(;p<pmax;p++){ if(copyOfCurrentWArow[p] === intermediateWorkingArr[m][p]){ combinedArray[p] = copyOfCurrentWArow[p]; } else if( copyOfCurrentWArow[p] !== null && intermediateWorkingArr[m][p] === null ){ combinedArray[p] = copyOfCurrentWArow[p]; } else if( copyOfCurrentWArow[p] === null && intermediateWorkingArr[m][p] !== null ){ combinedArray[p] = intermediateWorkingArr[m][p]; } else{ combinedArray[p] = null; } } // continue testing the validity of the combined array if(combinedArray[0]!==null){ if(combinedArray[1]!==null && combinedArray[0]!==combinedArray[1]){ if(combinedArray[2]!==null && combinedArray[0]!==combinedArray[2] && combinedArray[1]!==combinedArray[2]){ newWorkingArr.push(combinedArray); } } } } } if(newWorkingArr.length){ if(newWorkingArr.length === 1){ return newWorkingArr; } else{ return false; } } return false; } function compare2(workingArr, compArrs){ var i=0, j=0, k=0, m=0, n=0, p=0, imax=workingArr.length, jmax=0, kmax=0, mmax=0, nmax=0, pmax=0; var workingArrRemovals = []; var copyOfCompArr0, compArr0pattern; var newWorkingArr = [], intermediateWorkingArr = [], intermediateRemovals; var copyOfCurrentWArow = [], combinedArray = []; // loop through the workingArr for(;i<imax;i++){ // get the type of the row from the first comparison array compArr0pattern = compArrs[0][ compArrs[0].length-1 ]; // thisPre.innerHTML += "compArr0pattern: " + compArr0pattern + "<br>";// // then make a copy of the first of the compArrs copyOfCompArr0 = JSON.parse( JSON.stringify( compArrs[0] ) ); //candidate for shallowClonePrimitives // trim the type element out of the copyOfCompArr0 copyOfCompArr0.pop(); // update the workingArrRemovals variable workingArrRemovals = workingArr[i][ workingArr[i].length-1 ]; // if there are any workingArrRemovals, replace them with null wherever they appear in the copyOfCompArr0 j=0, jmax = workingArrRemovals.length; for(;j<jmax;j++){ k=0, kmax=copyOfCompArr0.length; for(;k<kmax;k++){ if(copyOfCompArr0[k]===workingArrRemovals[j]){ copyOfCompArr0[k] = null; } } } // then, send the remaining copyOfCompArr0 to its patterns function (use and strip its type) intermediateWorkingArr = patterns[compArr0pattern](copyOfCompArr0); // then, loop through the response from the patterns function m=0, mmax = intermediateWorkingArr.length; for(;m<mmax;m++){ // make a copy of the current row from the initial workingArr copyOfCurrentWArow = JSON.parse( JSON.stringify( workingArr[i] ) ); //candidate for shallowClonePrimitives copyOfCurrentWArow.pop(); // grab the intermediate removals from the current row of intermediateWorkingArr intermediateRemovals = intermediateWorkingArr[m][ intermediateWorkingArr[m].length-1 ]; // if there are any intermediateRemovals, then replace them with null wherever they appear in the copyOfCurrentWArow n=0, nmax = intermediateRemovals.length; for(;n<nmax;n++){ p=0, pmax=copyOfCurrentWArow.length; for(;p<pmax;p++){ if(copyOfCurrentWArow[p]===intermediateRemovals[n]){ copyOfCurrentWArow[p] = null; } } } // do the first of a set of tests for validity, which, if all passed, will then place a newly combined array into into the newWorkingArr p=0, pmax = copyOfCurrentWArow.length, combinedArray = [null,null,null]; for(;p<pmax;p++){ if(copyOfCurrentWArow[p] === intermediateWorkingArr[m][p]){ combinedArray[p] = copyOfCurrentWArow[p]; } else if( copyOfCurrentWArow[p] !== null && intermediateWorkingArr[m][p] === null ){ combinedArray[p] = copyOfCurrentWArow[p]; } else if( copyOfCurrentWArow[p] === null && intermediateWorkingArr[m][p] !== null ){ combinedArray[p] = intermediateWorkingArr[m][p]; } else{combinedArray[p] = null;} // this catches the case where copyOfCurrentWArow[p] !== intermediateWorkingArr[p] } // continue testing the validity of the combined array if(combinedArray[0]!==null){ if(combinedArray[1]!==null && combinedArray[0]!==combinedArray[1]){ if(combinedArray[2]!==null && combinedArray[0]!==combinedArray[2] && combinedArray[1]!==combinedArray[2]){ newWorkingArr.push(combinedArray); } } } } } if(newWorkingArr.length){ if(newWorkingArr.length === 1){ return newWorkingArr; } else{ return false;} } return false; } var correctCount = 0, wrongCount= 0, bestStreak = 0, currentStreak = 0, avgTime, bestTime, worstTime; function checkAnswer(){ var correctAnswer = preOrderComparisons([ currentPuzzle[0], currentPuzzle[1] ])[0]; if(!correctAnswer){ var correctAnswer = preOrderComparisons2([ currentPuzzle[0], currentPuzzle[1] ])[0]; } if(!correctAnswer){alert("something is amiss, my apologies.");} console.log("correctAnswer"); console.log(correctAnswer); var replacementTypeBools = { number: function(j){return textInputs[j].value*1 !== correctAnswer[j]*1;}, letter: function(j){return textInputs[j].value.toUpperCase() !== correctAnswer[j];}, pic: function(j){return imageInputs[j].src !== correctAnswer[j];} }; var replacementTypeElements = { number:textInputs, letter:textInputs, pic:imageInputs }; for(var i=0, imax=replacementTypeElements[replacementType].length; i<imax; i++){ if(replacementTypeBools[replacementType](i)){ var handoff = setTimeout(function(){ clearStuff(); },20); var handoff2 = setTimeout(function(){ wrongCount++; document.getElementById("wrongCount").innerHTML = wrongCount; },20); replacementTypeElements[replacementType][0].focus(); currentStreak = 0; document.getElementById("currentStreak").innerHTML = currentStreak; return "fail!"; } } var handoff = setTimeout(function(){ clearStuff() ;},20); var handoff2 = setTimeout(function(){ correctCount++; document.getElementById("correctCount").innerHTML = correctCount; },20); if(avgTime){ avgTime[1]++; avgTime[0] = Math.round( (avgTime[0]*(avgTime[1]-1) + s)/avgTime[1] ); } else { avgTime = [s,1]; } bestTime = bestTime ? Math.min(bestTime, s) : s; worstTime = worstTime ? Math.max(worstTime, s) : s; hintRows.innerHTML = makeButtons(); replacementTypeElements[replacementType][0].focus(); currentStreak++; bestStreak = Math.max(currentStreak, bestStreak); var handoff2 = setTimeout(function(){ document.getElementById("currentStreak").innerHTML = currentStreak; document.getElementById("bestStreak").innerHTML = bestStreak; document.getElementById("avgTime").innerHTML = avgTime[0] + " seconds"/*, after " + avgTime[1] + (avgTime[1] === 1 ? " attempt." : " attempts.") */; document.getElementById("bestTime").innerHTML = bestTime + " seconds"; document.getElementById("worstTime").innerHTML = worstTime + " seconds"; },20); return "Success!!"; }<filename>test/unit/cookie.test.js const $cookie = require('../../packages/cookie'); const $console = console; $console.log( Object.keys($cookie).map( (name) => (`../../packages/cookie/${name}`), ).join('\n'), ); describe('cookie.cookie', () => { const Cookie = $cookie.cookie; test('cookie 以 URI 编码形式存值', () => { Cookie.set('key1', 'a b', { expires: 1, }); expect(document.cookie).toBe('key1=a%20b'); Cookie.remove('key1'); }); test('cookie 以 URI 编码形式取值', () => { document.cookie = 'key2=a%20b'; const val = Cookie.get('key2'); expect(val).toBe('a b'); Cookie.remove('key2'); }); }); // 从测试中可以看到 js-cookie 默认已经实现了默认字符编码 // 因此之后的版本可以移除这个工具方法 // 当前仓库保留该方法以实现对旧代码兼容 describe('cookie.origin', () => { const Cookie = $cookie.origin; test('cookie 默认形式存值', () => { Cookie.set('key3', 'a b', { expires: 1, }); expect(document.cookie).toBe('key3=a%20b'); Cookie.remove('key3'); }); test('cookie 默认形式取值', () => { document.cookie = 'key4=a%20b'; const val = Cookie.get('key4'); expect(val).toBe('a b'); Cookie.remove('key4'); }); }); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { FILTER_CHANGED, PAGE_CHANGED, PAGE_SIZE_CHANGED, SORT_CHANGED } from '../action_types'; export const filterChanged = ({ filter }) => dispatch => { dispatch({ type: FILTER_CHANGED, payload: { filter }, }); }; export const pageChanged = ({ pageNumber }) => dispatch => { dispatch({ type: PAGE_CHANGED, payload: { pageNumber }, }); }; export const pageSizeChanged = ({ pageSize }) => dispatch => { dispatch({ type: PAGE_SIZE_CHANGED, payload: { pageSize }, }); }; export const sortChanged = ({ sortField, isSortAscending }) => dispatch => { dispatch({ type: SORT_CHANGED, payload: { sortField, isSortAscending }, }); }; <gh_stars>0 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDefaultOptions = undefined; var _sessionStorage = require('./session-storage'); var _request = require('./request'); var getDefaultOptions = exports.getDefaultOptions = function getDefaultOptions() { return { key: 'userTimingConfigurations', isAutoReset: false, isTrackingEnabled: true, storageApi: { getItem: _sessionStorage.getSessionItem, setItem: _sessionStorage.setSessionItem }, configApi: { get: _request.get }, googleAnalyticsApi: window.gtag }; };<reponame>thinkful-cohort-16/blog-app-Robert /* global jQuery, handle, $, api */ 'use strict'; const ITEMS_URL = '/api/v1/stories/'; const renderPage = function (store) { if (store.demo) { $('.view').css('background-color', 'gray'); $('#' + store.view).css('background-color', 'white'); } else { $('.view').hide(); $('#' + store.view).show(); } }; const renderResults = function (store) { const listItems = store.list.map((item) => { return `<li id="${item.id}"> <a href="${item.url}" class="detail">${item.title}</a> </li>`; }); $('#result').empty().append('<ul>').find('ul').append(listItems.sort()); }; const renderEdit = function (store) { const el = $('#edit'); const item = store.item; el.find('[name=title]').val(item.title); el.find('[name=content]').val(item.content); }; const renderDetail = function (store) { const el = $('#detail'); const item = store.item; el.find('.title').text(item.title); console.log(item.content); if(item.content===undefined){ el.find('.content').html(item.content); } else{ el.find('.content').html(item.content.replace(RegExp('\n','g'), '<br>')); } }; const handleSearch = function (event) { event.preventDefault(); const store = event.data; const el = $(event.target); const title = el.find('[name=title]').val(); var query; if (title) { query = { title: el.find('[name=title]').val() }; } api.search(query) .then(response => { store.list = response; renderResults(store); store.view = 'search'; renderPage(store); }).catch(err => { console.error(err); }); }; const handleCreate = function (event) { event.preventDefault(); const store = event.data; const el = $(event.target); const document = { title: el.find('[name=title]').val(), content: el.find('[name=content]').val() }; api.create(document) .then(response => { store.item = response; store.list = null; //invalidate cached list results handleViewList; renderDetail(store); store.view = 'detail'; renderPage(store); }).catch(err => { console.error(err); }); }; const handleUpdate = function (event) { event.preventDefault(); const store = event.data; const el = $(event.target); const document = { id: store.item.id, title: el.find('[name=title]').val(), content: el.find('[name=content]').val() }; api.update(document, store.token) .then(response => { store.item = response; store.list = null; //invalidate cached list results renderDetail(store); store.view = 'detail'; renderPage(store); }).catch(err => { console.error(err); }); }; const handleDetails = function (event) { event.preventDefault(); const store = event.data; const el = $(event.target); const id = el.closest('li').attr('id'); api.details(id) .then(response => { store.item = response; renderDetail(store); store.view = 'detail'; renderPage(store); }).catch(err => { store.error = err; }); }; const handleRemove = function (event) { event.preventDefault(); const store = event.data; const id = store.item.id; api.remove(id, store.token) .then(() => { store.list = null; //invalidate cached list results return handleSearch(event); }).catch(err => { console.error(err); }); }; const handleViewCreate = function (event) { event.preventDefault(); const store = event.data; store.view = 'create'; renderPage(store); }; const handleViewList = function (event) { event.preventDefault(); const store = event.data; if (!store.list) { handleSearch(event); return; } store.view = 'search'; renderPage(store); }; const handleViewEdit = function (event) { event.preventDefault(); const store = event.data; renderEdit(store); store.view = 'edit'; renderPage(store); }; //on document ready bind events jQuery(function ($) { const STORE = { demo: false, // display in demo mode true | false view: 'list', // current view: list | details | create | edit query: {}, // search query values list: null, // search result - array of objects (documents) item: null, // currently selected document }; $('#create').on('submit', STORE, handleCreate); $('#search').on('submit', STORE, handleSearch); $('#edit').on('submit', STORE, handleUpdate); $('#result').on('click', '.detail', STORE, handleDetails); $('#detail').on('click', '.remove', STORE, handleRemove); $('#detail').on('click', '.edit', STORE, handleViewEdit); $(document).on('click', '.viewCreate', STORE, handleViewCreate); $(document).on('click', '.viewList', STORE, handleViewList); // start app by triggering a search $('#search').trigger('submit'); }); var Mothership = (function() { var pos = { x: 0, y: 0, }; var vector = { x: 0, y: 0, }; var offset = 37.5; var maximum_shooters = 8; var angles = [0, 0.25 * Math.PI, 0.5 * Math.PI, 0.75 * Math.PI, Math.PI, 1.25 * Math.PI, 1.5 * Math.PI, 1.75 * Math.PI, 2 * Math.PI]; var speed = 0.25; return { init: function() { pos.x = window.innerWidth * 0.5; pos.y = window.innerHeight * 0.5; }, get_new_position: function(lapse) { vector.x = 0; vector.y = 0; //reset the vector vector.y += (this.directions.up ? -1 : 0); vector.y += (this.directions.down ? 1 : 0); vector.x += (this.directions.left ? -1 : 0); vector.x += (this.directions.right ? 1 : 0); pos.x += vector.x * lapse * speed; pos.y += vector.y * lapse * speed; //limit the mothership at the edges of the screen pos.x = Math.min(Engine.game_area_x - offset, Math.max(offset, pos.x)); pos.y = Math.min(Engine.game_area_y - offset, Math.max(offset, pos.y)); }, has_room: function(num) { return (num < maximum_shooters); }, directions: { up: false, down: false, left: false, right: false, }, collision: function() { if (!Engine.invincibility) { Engine.end_game(); } }, draw: function(context) { var sprite = Engine.invincibility ? Assets.invincible_mothership : Assets.mothership; context.drawImage(sprite, pos.x - offset, pos.y - offset); }, get x() { return pos.x - offset;}, get y() { return pos.y - offset;}, get offset() {return offset;}, get orbit_radius() { return 100; }, //how far the shooters orbit the mothership }; })(); export const GET_MIA_ANNOS = 'GET_MIA_ANNOS' export const GET_MIA_IMAGE = 'GET_MIA_IMAGE' export const MIA_ZOOM = 'MIA_ZOOM' export const MIA_AMOUNT = 'MIA_AMOUNT' export const MIA_TOGGLE_ACTIVE = 'MIA_TOGGLE_ACTIVE' export const GET_MIA_LABEL = 'GET_MIA_LABEL' export const MIA_SELECT_LABEL = 'MIA_SELECT_LABEL'import { load } from "@shopify/theme-sections"; import "../components/landing-page-modal"; import "../components/landing-page-steps-nav"; import "../components/landing-page-steps"; import "../../styles/page.landing-page.scss"; load("*"); <reponame>media-ambassador/front-abstract<gh_stars>0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var MaAccordionItemContentComponent = /** @class */ (function () { function MaAccordionItemContentComponent() { this.isOpen = false; } MaAccordionItemContentComponent.prototype.show = function () { this.isOpen = true; }; MaAccordionItemContentComponent.prototype.hide = function () { this.isOpen = false; }; MaAccordionItemContentComponent.decorators = [ { type: core_1.Component, args: [{ selector: 'ma-accordion-item-content', template: "\n <div [ngClass]=\"{ 'open': isOpen }\">\n <ng-content></ng-content>\n </div>\n ", styles: ["\n :host div {\n height: 0;\n opacity: 0;\n overflow: hidden;\n transition: all 0.3s ease-in-out; }\n\n :host div.open {\n height: initial;\n opacity: 1; }\n "] },] }, ]; /** @nocollapse */ MaAccordionItemContentComponent.ctorParameters = function () { return []; }; return MaAccordionItemContentComponent; }()); exports.MaAccordionItemContentComponent = MaAccordionItemContentComponent; //# sourceMappingURL=accordion-item-content.component.js.mapimport React, { Component, Fragment } from 'react'; import styled from 'styled-components'; const Widget = styled.div` padding: 0.5rem 1rem; background-color: ${p => p.theme.color.white}; color: ${p => p.theme.color.dark}; user-select: none; font-family: monospace; `; class DatePicker extends Component { render() { const { date, onClick } = this.props; return ( <Fragment> <Widget onClick={onClick}> { date || '--.--.----' } </Widget> </Fragment> ); } } export default DatePicker;<reponame>manuelg139/UTA-AUS-FSF-PT-12-2020-U-C<gh_stars>0 /* class Letter { //non letters and non digits are visible constructor(character) { this.character = character; this.visible = true; this.digitArray = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]; this.letterArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; this.Uppercase = this.letterArray.map(function (element) { return element.toUpperCase(); }) if (this.letterArray.includes(character) || this.digitArray.includes (character) || this.Uppercase.includes(character)) { this.visible = false; } else { return "_"; } //converts characters to a string character.toString(); //converts letters to an empty string "_"; } } */ class Letter{ constructor (char){ this.char = char; const validChars = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z","0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]; if (validChars.includes(char) || validChars.includes(char.toLowercase())){ this.visible = false; } else { this.visible = true; } } } module.exports = Letter;/* ========================================================================== Sidebar Toggle Initialize: cargobay.sidebarToggle.init(); Support: Latest Chrome Latest FireFox Latest Safari IE9 and up ========================================================================== */ var cargobay = cargobay || {}; cargobay.sidebarToggle = (function($, window, undefined) { var activeSidebarClass = 'sidebar-toggle__sidebar--active', activeButtonClass = 'sidebar-toggle__toggle-btn--active'; var init, toggle; var aniSidebarOpen = {}, aniSidebarClose = {}, aniContainerOpen = {}, aniContainerClose = {}; var sidebarWidth, sidebarHeight; var $btn, $container, $content, $sidebar, position = '', preventOverflow, duration = 0; // Init init = function() { $('.js-sidebar-toggle__toggle-btn').on('click', function(e) { e.preventDefault(); e.stopPropagation(); $btn = $(this), $container = $($btn.data('container')), $content = $($btn.data('content')), $sidebar = $($btn.data('sidebar')), position = $btn.data('position'), preventOverflow = $btn.data('prevent-overflow'), duration = $btn.data('duration'); // Set direction variables if(position === 'left') { sidebarWidth = $sidebar.outerWidth(); aniSidebarOpen.translateX = ['0', '-100%']; aniSidebarClose.translateX = ['-100%', '0']; aniContainerOpen.translateX = [sidebarWidth, '0']; aniContainerClose.translateX = ['0', sidebarWidth]; } if(position === 'right') { sidebarWidth = $sidebar.outerWidth(); aniSidebarOpen.translateX = ['0', '100%']; aniSidebarClose.translateX = ['100%', '0']; aniContainerOpen.translateX = ['-' + sidebarWidth, '0']; aniContainerClose.translateX = ['0', '-' + sidebarWidth]; } if(position === 'top') { sidebarHeight = $sidebar.outerHeight(); aniSidebarOpen.translateY = ['0', '-100%']; aniSidebarClose.translateY = ['-100%', '0']; aniContainerOpen.translateY = [sidebarHeight, '0']; aniContainerClose.translateY = ['0', sidebarHeight]; } if(position === 'bottom') { sidebarHeight = $sidebar.outerHeight(); aniSidebarOpen.translateY = ['0', '100%']; aniSidebarClose.translateY = ['100%', '0']; aniContainerOpen.translateY = ['-' + sidebarHeight, '0']; aniContainerClose.translateY = ['0', '-' + sidebarHeight]; } // Animate toggle toggle(); }); }; // Toggle toggle = function() { if(!$sidebar.hasClass(activeSidebarClass)) { $sidebar.addClass(activeSidebarClass); $btn.addClass(activeButtonClass); $sidebar.velocity(aniSidebarOpen, { duration: duration, easing: 'ease' }); $content.velocity(aniContainerOpen, { duration: duration, easing: 'ease' }); if(preventOverflow) { $('.sidebar-toggle-container').addClass('sidebar-toggle-container--prevent-overflow'); } $content.one('click', toggle); } else { $sidebar.removeClass(activeSidebarClass); $btn.removeClass(activeButtonClass); $sidebar.velocity(aniSidebarClose, { duration: duration, easing: 'ease' }); $content.velocity(aniContainerClose, { duration: duration, easing: 'ease' }); if(preventOverflow) { $('.sidebar-toggle-container').removeClass('sidebar-toggle-container--prevent-overflow'); } $content.off('click', toggle); } }; return { init: init }; }(jQuery, window)); <filename>client/src/index.js import React from "react"; import ReactDOM from "react-dom"; import { ApolloProvider } from "react-apollo"; import { Provider } from 'react-redux'; import App from "./App"; import configureStore from './store/store'; import { checkLoggedIn } from './util/session'; import * as serviceWorker from "./serviceWorker"; import client from "./apollo/client"; const renderApp = preloadedState => { const store = configureStore(preloadedState); const ApolloApp = AppComponent => ( <ApolloProvider client={client}> <Provider store={store}> <AppComponent /> </Provider> </ApolloProvider> ); ReactDOM.render(ApolloApp(App), document.getElementById("root")); // FOR TESTING, remove before production window.getState = store.getState; } (async () => renderApp(await checkLoggedIn()))(); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); /* * superqs * https://github.com/chrisenytc/superqs * * Copyright (c) 2015, <NAME> * Licensed under the MIT license. */ 'use strict'; /** * Module Dependencies */ var sugar = require('sugar'); /** @class SuperQS */ /** * Private Methods */ function isset(object){ return (object != 'undefined' && object != undefined && object != null && object != "" && typeof(object) != 'undefined') ? true : false ; } function isDate(date) { return ( (new Date(date) !== 'Invalid Date' && !isNaN(new Date(date)) )); } function stringifyTraverse(subject, level, key) { var result = ''; for (var prop in subject) { var parent_appendix = key ? key : ''; var parent_appendix = level > 1 && level < 2 ? '['+key+']' : parent_appendix; var child_appendix = level > 0 ? '['+prop+']' : prop ; var appendix = parent_appendix + child_appendix; var value = subject[prop]; if (Object.isObject(value)) { result += stringifyTraverse(value, level + 1, appendix); } else if (Array.isArray(value)) { for(var i = 0; i < value.length; i++){ result += appendix+'='+stringifyValue(value[i])+'&'; } } else { result += appendix +'='+ stringifyValue(value) + '&'; } } return result; } function toValue(value) { if(value == 'true'){ value = true; // boolean true } else if (value == 'false') { value = false; // boolean false } else if (isset(value) && !isNaN(value)) { value = +value; // number } else if (isDate(value)) { value = new Date(value); } return value; } function stringifyValue(value) { if(value === true){ value = 'true'; // boolean true } else if (value === false) { value = 'false'; // boolean false } else if (value instanceof Date) { value = value.toISOString(); // iso date } else if (isset(value) && !isNaN(value)) { value = +value; // number } return value; } function traverse(subject, key, value) { if(key.indexOf('[') != -1){ var split = key.split('['); var INT_SUBJECT = subject; if(isNaN(split[1].split(']')[0])){ for(var i = 0; i < split.length; i++){ var section = split[i].indexOf(']') ? split[i].split(']')[0] : split[i] ; if(i < split.length-1){ if(!INT_SUBJECT[section]) INT_SUBJECT[section] = {}; } else { if(INT_SUBJECT[section]) { INT_SUBJECT[section] = [INT_SUBJECT[section]]; INT_SUBJECT[section].push(toValue(value)) } else { INT_SUBJECT[section] = toValue(value); } } INT_SUBJECT = INT_SUBJECT[section]; } subject = INT_SUBJECT; } else { var parent = split[0]; var section = split[1].indexOf(']') ? split[1].split(']')[0] : split[1] ; if(typeof INT_SUBJECT[parent] != 'object') INT_SUBJECT[parent] = []; INT_SUBJECT[parent].push(toValue(value)); subject = INT_SUBJECT; } } else if (subject[key]) { if(typeof subject[key] != 'object') subject[key] = [subject[key]]; subject[key].push(toValue(value)); } else { subject[key] = toValue(value); } return subject; } /* * Public Methods */ /** * Method responsible for parse a querystring * * @example * * superqs.parse('name=Christopher&username=chrisenytc'); * * @method parse * @param {String} body A querystring * @return {Mixed} Returns a object or array */ exports.parse = function(body) { var result = {}; body = body.toString().replace(/\+/gi,' '); var split = body.split(/\&/gi); split.forEach(function(string){ var split = string.split('='); var key = decodeURIComponent(split[0]); var value = decodeURIComponent(split[1]); traverse(result, key, value, split.length); }); return result; }; /** * Method responsible for stringify a array or object * * @example * * superqs.stringify({ name: 'Christopher', username: 'chrisenytc' }); * * @method parse * @param {Mixed} query A array or object * @return {Mixed} Returns a object or array */ exports.stringify = function(query) { var result = stringifyTraverse(query, 0); result = result.substr(0, result.length-1); return result; }; class ScoreKeeper { constructor(playball, game, settings) { this.playball = playball; this.game = game; this.settings = settings; this.player1 = {}; this.player2 = {}; this.player1.score = 0; this.player2.score = 0; this.player1.text = this.game.add.text(0, 0, this.player1.score, this.settings.scoreTextStyle); this.player1.text.setTextBounds(0, 25, 150, 50); this.player2.text = this.game.add.text(0, 0, this.player2.score, this.settings.scoreTextStyle); this.player2.text.setTextBounds(this.game.world.width - 150, 25, 150, 50); } update() { if (this.playball.sprite.bottom > (this.game.world.height - 1)) { if (this.playball.sprite.body.x < this.game.world.centerX) { this.player2.score += 1; this.player2.text.text = this.player2.score; this.player2.text.update(); this.game.state.states.Game.resetPositions(); } if (this.playball.sprite.body.x > this.game.world.centerX) { this.player1.score += 1; this.player1.text.text = this.player1.score; this.player1.text.update(); this.game.state.states.Game.resetPositions(); } } } }const countdown = document.querySelector('.countdown'); // Set launch date (ms) const launchDate = new Date('Jan 1, 2019 13:00:00').getTime(); // Update every second // Using arrow function const intvl = setInterval(() => { // Get todays date and time (ms) const now = new Date ().getTime(); // Get distance from now to launch date (ms) const distance = launchDate - now; // time calculations days, hrs, minutes const days = Math.floor(distance/ (1000 * 60 * 60 * 24)); const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const mins = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display result // Using ES6/ES2015 Template String, these are NOT single quotes but back marks // Users variables with template strings countdown.innerHTML = ` <div>${days}<span> Days</span></div> <div>${hours}<span>Hours</span></div> <div>${mins}<span>Minutes</span></div> <div>${seconds}<span>Seconds</span></div> `; // Has the time/launch date already past? if (distance <0 ) { // stop countdown clearInterval(intvl); // style and output text countdown.style.color = "#17a2b8"; countdown.innerHTML = "Launched!"; } }, 1000); <gh_stars>0 import {runBash} from "./run.bash.js"; /*********************** reload tab contents and inner-tabs ***********************/ import {LoadEditTab, loadMe} from "./editwp.js"; //loadMe("options","list"); /*********************** search / filter option name ***********************/ $(document).on("keyup", "#filter-option-table", function(e){ var ne=$(e.target); var VaL=ne.val(); switch(e.which){ case 13: $(e.target).blur(); break; case 27: $(e.target).blur().val(""); $("#table-options-all tbody tr").show(); break; default: if(VaL.length>2){ $("#table-options-all tbody tr").hide(); $("#table-options-all tbody tr:contains('"+VaL+"')").show(); } break; } }); /*********************** on dbl click option ***********************/ $(document).on("dblclick","#table-options-all tr", function(e){ var TR = $(e.target).closest('tr'); var option_name=TR.find("td:eq(0)").text(); var option_value=TR.find("td:eq(1)").text(); swal( option_name, option_value ) }); /*********************** update options ***********************/ $(document).on("click","table[id^='table-options-'] button", function(e){ var option=$(e.target).closest("tr").find("td:eq(0)").text().trim(); var VaL=$(e.target).closest("tr").find("input").val(); var cmd="wp option update " + option + " '" + VaL + "' --path=" + $(".update-tabs tr:eq(0) td:eq(1)").text(); $(e.target).toggleClass('fa-spin fa-2x'); var status=runBash(cmd); $(e.target).toggleClass('fa-spin fa-2x'); if(status){ swal({ title:"updated", timer:2000, icon:"success", text: option + ": \n" + VaL, buttons:false }); } }); /*********************** dblclik default value of options ***********************/ $(document).on("dblclick","table[id^='table-options-'] tbody a", function(e){ var option=$(e.target).closest("tr").find("td:eq(0)").text().trim(); var defVal=$(e.target).attr("data-default"); var inp=$(e.target).closest("tr").find("input"); inp.val(defVal); inp.focus(); }); /*********************** goto settings page ***********************/ $(document).on("click", "#btn-goto-settings", function(e){ window.location=$(e.target).attr("data-location"); }); /*********************** update all option with default values ***********************/ $(document).on("click", "#btn-update-all-default-options", function(e){ var TR=$(document).find("#table-update-all-default-options tbody tr"); $(e.target).toggleClass("fa-spin"); $.each(TR, function(i,v){ var cmd="wp option update "; cmd+=$(v).find("td").eq(0).text().trim(); cmd+=" '"; cmd+=$(v).find("td").eq(1).text().trim(); cmd+="' "; cmd+="--path=" + $(".update-tabs tr:eq(0) td:eq(1)").text(); var status=runBash(cmd); if(status){ $(v).find("td").eq(2).removeClass('fa-minus').addClass('fa-check').css("color", "green"); } else { $(v).find("td").eq(2).removeClass('fa-minus').addClass('fa-times').css("color", "red"); } }); $(e.target).toggleClass("fa-spin"); }); <gh_stars>10-100 /** @type {import("@types/tailwindcss/tailwind-config").TailwindConfig} */ module.exports = { content: { files: ['src/**/*.{vue,js,ts}'] }, darkMode: false, theme: { extend: {} }, variants: { extend: {} }, plugins: [] } <reponame>marat-gainullin/platypus-js<filename>platypus-js-tests/src/main/webapp/app/JS inheritance/Rabbit.js /** * * @author mg * @name Rabbit */ function Rabbit() { var self = this; var o1 = arguments[0]; var o2 = arguments[1]; Animal();// won't work because of resource nature of Rabbit; }<filename>utils/index.js import FormatPercent from './FormatPercent'; import GenerateAttack from './GenerateAttack'; import GenerateCombination from './GenerateCombination'; import GenerateMessage from './GenerateMessage'; export { FormatPercent, GenerateAttack, GenerateCombination, GenerateMessage };<reponame>hlex/dubtitles import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import Root from './containers/Root' import './style/style.scss' const rootEl = document.getElementById('app') render(<Root />, rootEl) var path = require("path"); var lowdb = require("lowdb"); const FileSync = require("lowdb/adapters/FileSync"); var fileURLToPath = require("url"); var sign = require("crypto"); // Use JSON file for storage const init_db = () => { const file = path.join(__dirname, "db.json"); const adapter = new FileSync(file); return new lowdb(adapter); } const set_default_data = () => { console.log("set default data"); console.log(`current user data: ${init_db().get("users").value()}`); init_db() .set("users", init_db().get("users").value() || [] ) .write(); } const read_all = () => { return [...init_db().get("users").value() ]; }; async function write(item) { console.log(`writing item ${{...item}}`); let new_users = [...init_db().get("users").value(), item] console.log(`new users: ${{...new_users}}`) await init_db() .set("users", new_users) .write(); return true; } async function erase(item_id) { if (!exists(item_id)) return false; await init_db().get("users").remove({ name: item_id }).write(); return true; } async function exists(item_id) { if (item_id === undefined) return false; let searched = init_db() .get("users") .value() .filter((data) => data.name === item_id); if (searched.length >= 1) return true; return false; } function search(item_id) { if (item_id === undefined) return false; if (exists(item_id)) { console.log(`${item_id} exists!!!`); let result = init_db() .get("users") .value() .filter((data) => { console.log(`data: ${data}`); if (data.name === item_id) { console.log("found"); return data; } }); console.log(`${JSON.stringify(result[0])} is a good result`); return result[0]; } else { return {}; } } async function modify(item) { console.log(`modify with this: ${item}`); if (exists(item.name)) await erase(item.name); await write(item); } console.log("Loading simple storage") set_default_data() exports.modify = modify; exports.search = search; exports.exists = exists; exports.erase = erase; exports.write = write; exports.read_all = read_all; exports.init_db = init_db; var searchData= [ ['host_5fconnection_5fchecked',['host_connection_checked',['../classcom_1_1android_1_1ui_1_1DistanceVolumeActivity.html#a682bf48e8a34f18c8d71226e995cc22d',1,'com::android::ui::DistanceVolumeActivity']]] ]; <filename>node_modules/@progress/kendo-angular-gauges/dist/npm/base-components/settings.component.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @hidden */ var SettingsComponent = /** @class */ (function () { function SettingsComponent(key, configurationService) { this.key = key; this.configurationService = configurationService; } SettingsComponent.prototype.ngOnChanges = function (changes) { this.configurationService.copyChanges(this.key, changes); }; SettingsComponent.prototype.ngOnDestroy = function () { this.configurationService.set(this.key, null); }; return SettingsComponent; }()); exports.SettingsComponent = SettingsComponent; const videoUrlLink = require("../../video-url-link") var pageMetadataParser = require("page-metadata-parser") var fetch = require('node-fetch'); var domino = require('domino'); module.exports = async (req, res) => { if (!req.query.postId) { res.json({ error: "Intagram Post Id not supplied" }); } else { const igURL = `https://www.instagram.com/p/${req.query.postId}`; videoUrlLink.instagram.getInfo(igURL, async (error, info) => { if (error) { if (error === {}) { res.json({ error: "Invalid Post ID" }); } else { res.json({ error: error }); } } else { const resp = await fetch(igURL); const html = await resp.text(); const doc = domino.createWindow(html).document; const metadata = pageMetadataParser.getMetadata(doc, igURL); const title = metadata.title ? metadata.title : "Untitled"; const description = metadata.description ? metadata.description : "No Description"; res.json({title: title, description: description, media: info.list}); } }); } }; var classpteros_1_1XYZ__file = [ [ "XYZ_file", "classpteros_1_1XYZ__file.html#a670c2eb834f38d8c6c7b6647b9beb23d", null ], [ "get_content_type", "classpteros_1_1XYZ__file.html#a632841e97f4ba42794955d2b3c382b95", null ] ];<reponame>Fixeg/jsAsteroids import KeyCodes from 'Input/keyCodes.js'; import Render from 'Graphics/render.js'; import GameState from 'Game/gameState.js'; /** * @description Occurs when the user pushes a key (on the keyboard) * @param {object} evt Keyboard event */ function onKeyDown(evt) { var key = evt.keyCode; var ship = GameState.getShip(); if (key === KeyCodes.up) { ship.startThrusting(); } else if (key === KeyCodes.left) { ship.startTurningLeft(); } else if (key === KeyCodes.right) { ship.startTurningRight(); } else if (key === KeyCodes.space) { ship.startShooting(); } } /** * @description Occurs when the user releases a key (on the keyboard) * @param {object} evt Keyboard event */ function onKeyUp(evt) { var key = evt.keyCode; var ship = GameState.getShip(); if (key === KeyCodes.up) { ship.stopThrusting(); } else if (key === KeyCodes.left || key === KeyCodes.right) { ship.stopTurning(); } else if (key === KeyCodes.space) { ship.stopShooting(); } } /** * @description Occurs when user performs a mouse-click on window */ function onClick() { if (GameState.isGameOver()){ GameState.restartGame(); } } /** * @description Occurs when user resizes window * @param {object} evt A "resize" event */ function onResize(evt) { Render.resize(evt.target.innerWidth, evt.target.innerHeight); } export default { onKeyDown, onKeyUp, onClick, onResize };<reponame>lquanyang/vue2-vite-demo<gh_stars>100-1000 import path from "path"; import { defineConfig } from "vite"; import { createVuePlugin } from "vite-plugin-vue2"; import WindiCSS from "vite-plugin-windicss"; import Components from "unplugin-vue-components/vite"; import Icons from "unplugin-icons/vite"; import IconsResolver from "unplugin-icons/resolver"; const config = defineConfig({ resolve: { alias: { "@": `${path.resolve(__dirname, "src")}`, }, dedupe: ["vue-demi"], }, build: { minify: true, }, plugins: [ createVuePlugin(), WindiCSS(), Components({ resolvers: [ IconsResolver({ componentPrefix: "", }), ], }), Icons(), ], server: { port: 8080, }, }); export default config; import * as actions from "../actions/axsVenues" const initialState = { axsVenues: { axsVenues: {}, searchAxsVenue: [], eventsByAxsVenue: {}, skyBoxAxsVenueDup: [] } } const axsVenues = (state = initialState, action) => { switch (action.type) { case actions.FETCH_AXS_VENUE_SUCCESS: return { ...state, axsVenues: { ...state.axsVenues, axsVenues: action.payload } } case actions.SEARCH_SKYBOX_AXS_VENUE_FAILED: return { ...state, axsVenues: { ...state.axsVenues, searchAxsVenue: [action.payload] } } case actions.SEARCH_SKYBOX_AXS_VENUE_MODAL_CLOSE: return { ...state, axsVenues: { ...state.axsVenues, searchAxsVenue: [] } } case actions.OPEN_SKYBOX_AXS_VENUE_DUP_MODAL: return { ...state, axsVenues: { ...state.axsVenues, skyBoxAxsVenueDup: action.payload } } case actions.SELECT_MODAL_SKYBOX_AXS_VENUE: return { ...state, axsVenues: { ...state.axsVenues, skyBoxAxsVenueDup: [] } } case actions.CLOSE_MODAL_SKYBOX_AXS_VENUE: return { ...state, axsVenues: { ...state.axsVenues, skyBoxAxsVenueDup: [] } } case actions.FETCH_AXS_VENUE_PAGING_SUCCESS: return { ...state, axsVenues: { ...state.axsVenues, axsVenues: action.payload } } case actions.CLEAR_AXS_VENUES: return { ...state, axsVenues: { ...state.axsVenues, axsVenues: { axsVenueInfo: [] } } } case actions.FETCH_AXS_VENUE_SEARCH_SUCCESS: return { ...state, axsVenues: { ...state.axsVenues, axsVenues: action.payload } } default: return state } } export default axsVenues export const getAxsVenues = state => state.axsVenues["axsVenues"] export const getSearchAxsVenueData = state => state.axsVenues["searchAxsVenue"] export const getSkyBoxAxsVenuesDup = state => state.axsVenues["skyBoxAxsVenueDup"] <filename>src/api/ccUtil.js 'use strict' const WebSocket = require('ws'); const wanUtil = require("wanchain-util"); const ethUtil = require("ethereumjs-util"); const ethTx = require('ethereumjs-tx'); const wanchainTx = wanUtil.wanchainTx; const btcUtil = require('./btcUtil.js'); const hdUtil = require('./hdUtil.js'); const keythereum = require("keythereum"); const crypto = require('crypto'); const secp256k1 = require('secp256k1'); const createKeccakHash = require('keccak'); keythereum.constants.quiet = true; const net = require('net'); const utils = require('../util/util'); const web3utils = require('../util/web3util'); const crossChainAccount = require('../util/encrypt/crossAccountEncrypt'); let KeystoreDir = require('../keystore').KeystoreDir; let errorHandle = require('../trans/transUtil').errorHandle; let retResult = require('../trans/transUtil').retResult; const { Decimal } = require("decimal.js"); const Eos = require('eosjs'); const ecc = require('eosjs-ecc'); const wif = require("wif"); const floatRegex = /[^\d.-]/g function toFloat(str) { return parseFloat(str.replace(floatRegex, ''));} // For checkWanPassword const fs = require('fs'); const path = require('path'); //let config = utils.getConfigSetting('sdk.config', {}); const logger = utils.getLogger('ccUtil.js'); const networkTimeout = utils.getConfigSetting("network:timeout", 300000); /** * ccUtil */ const ccUtil = { /** * --------------------------------------------------------------------------- * encode/decode chain account with encrypt, the id can refer to slip-0044 * --------------------------------------------------------------------------- */ decodeAccount(chain, account) { let crossAccount = new crossChainAccount(chain.toLowerCase()); return crossAccount.decodeAccount(account).account; }, encodeAccount(chain, account) { let crossAccount = new crossChainAccount(chain.toLowerCase()); return crossAccount.encodeAccount(account); }, /** * --------------------------------------------------------------------------- * Transaction utility * --------------------------------------------------------------------------- */ deserializeWanTx(data) { let tx = new wanUtil.wanchainTx(data); return tx.toJSON(true); }, /** * Should be used to encode plain param to topic * * @method encodeTopic * @param {String} type * @param {Object} param * @return {String} encoded plain param */ encodeTopic(type, param) { return web3utils.encodeParam(type, param); }, hexTrip0x(hexs) { if (0 == hexs.indexOf('0x')) { return hexs.slice(2); } return hexs; }, hexAdd0x(hexs) { if (0 != hexs.indexOf('0x')) { return '0x' + hexs; } return hexs; }, /** * generate private key, in sdk , it is named x * @function generatePrivateKey * @returns {string} */ generatePrivateKey() { let randomBuf; do { randomBuf = crypto.randomBytes(32); } while (!secp256k1.privateKeyVerify(randomBuf)); return '0x' + randomBuf.toString('hex'); }, /** * Build hashKey,in sdk it is named hashX * @function getHashKey * @param {string} key - result of {@link ccUtil#generatePrivateKey ccUtil#generatePrivateKey} * @returns {string} - in sdk ,it is named hashX */ getHashKey(key) { //return BigNumber.random().toString(16); let kBuf = new Buffer(key.slice(2), 'hex'); // let hashKey = '0x' + util.sha256(kBuf); let h = createKeccakHash('keccak256'); h.update(kBuf); let hashKey = '0x' + h.digest('hex'); // logDebug.debug('input key:', key); // logDebug.debug('input hash key:', hashKey); return hashKey; }, getSha256HashKey(key){ let kBuf = new Buffer(key.slice(2), 'hex'); let h = crypto.createHash("sha256"); h.update(kBuf); let hashKey = '0x' + h.digest('hex'); return hashKey; }, /** * Create Eth address * @function createEthAddr * @param {string} keyPassword - key password * @returns {string} - eth address */ createEthAddr(keyPassword) { let params = { keyBytes: 32, ivBytes: 16 }; let dk = keythereum.create(params); let options = { kdf: "scrypt", cipher: "aes-128-ctr", kdfparams: { n: 8192, dklen: 32, prf: "hmac-sha256" } }; let keyObject = keythereum.dump(keyPassword, dk.privateKey, dk.salt, dk.iv, options); let config = utils.getConfigSetting('sdk:config', undefined); keythereum.exportToFile(keyObject, config.ethKeyStorePath); return keyObject.address; }, /** * Create Wan address * @function createWanAddr * @param {string} keyPassword - key password * @returns {string} - eth address */ createWanAddr(keyPassword) { let params = { keyBytes: 32, ivBytes: 16 }; let options = { kdf: "scrypt", cipher: "aes-128-ctr", kdfparams: { n: 8192, dklen: 32, prf: "hmac-sha256" } }; let dk = keythereum.create(params); let keyObject = keythereum.dump(keyPassword, dk.privateKey, dk.salt, dk.iv, options); let dk2 = keythereum.create(params); let keyObject2 = keythereum.dump(keyPassword, dk2.privateKey, dk2.salt, dk2.iv, options); keyObject.crypto2 = keyObject2.crypto; let config = utils.getConfigSetting('sdk:config', undefined); keyObject.waddress = wanUtil.generateWaddrFromPriv(dk.privateKey, dk2.privateKey).slice(2); keythereum.exportToFile(keyObject, config.wanKeyStorePath); return keyObject.address; }, /** * Create EOS randomKey * @function createEosKey * @returns {string} - eos private key */ async createEosKey() { return await ecc.randomKey(); }, /** * getEosPubKey * @function getEosPubKey * @param {string} key - Eos private key * @returns {string} */ getEosPubKey(key){ return ecc.privateToPublic(key); }, importEosAccountByRawKey(privateKey, account, password) { let eosChainID = 194; let eosBip44PathForm = "m/44'/194'/0'/0/"; let eosWalletID = 6; let config = utils.getConfigSetting('sdk:config', undefined); let index = hdUtil.getRawKeyCount(eosChainID); let path = eosBip44PathForm + index; let rawPriv = wif.decode(privateKey).privateKey; let pubKey = this.getEosPubKey(privateKey); hdUtil.importPrivateKey(path, rawPriv, password); hdUtil.importUserAccount(config.network, eosWalletID, path, account, pubKey, 'active'); // hdUtil.createUserAccount(eosWalletID, path, {"account" : account}); }, /** * isEthAddress * @function isEthAddress * @param {string} address - Eth address * @returns {boolean} * true: Eth address * false: Non Eth address */ isEthAddress(address) { let validate; if (/^0x[0-9a-f]{40}$/i.test(address)) { validate = true; } else if (/^0x[0-9A-F]{40}$/i.test(address)) { validate = true; } else { validate = ethUtil.isValidChecksumAddress(address); } return validate; }, /** * isWanAddress * @function isWanAddress * @param {string} address - Eth address * @returns {boolean} * true: Wan address * false: Non Wan address */ isWanAddress(address) { let validate; if (/^0x[0-9a-f]{40}$/.test(address)) { validate = true; } else if (/^0x[0-9A-F]{40}$/.test(address)) { validate = true; } else { validate = wanUtil.isValidChecksumAddress(address); } return validate; }, /** * isEosAccount * @function isEosAccount * @param {string} account - Eos account 1-5a-z * @returns {boolean} * true: Valid Account * false: Invalid Account */ isEosAccount(account){ let validate; if (/^[1-5a-z]{1,12}$/.test(account)) { validate = true; } else { validate = false; } return validate; }, /** * checkEosAccountExists * @function checkEosAccountExists * @param {string} account - Eos account 1-5a-z * @returns {boolean} * true: Account Exist * false: Account not Exist */ async checkEosAccountExists(account){ try { await this.getAccountInfo('EOS', account); return true; } catch (err) { if (err.indexOf('unknown key') !== -1) { return false; } else { throw (new Error('checkEosAccountExists', err.toString())); } } }, /** * isEosPublicKey * @function isEosPublicKey * @param {string} key - Eos private key * @returns {boolean} * true: Valid key * false: Invalid key */ isEosPublicKey(key){ let validate; if (ecc.isValidPublic(key) || (key.startsWith('EOS') && key.length === 53)) { validate = true; } else { validate = false; } return validate; }, /** * isEosPrivateKey * @function isEosPrivateKey * @param {string} key - Eos private key * @returns {boolean} * true: Valid key * false: Invalid key */ isEosPrivateKey(key){ let validate; if (ecc.isValidPrivate(key) || (key.startsWith('5') && key.length === 51)) { validate = true; } else { validate = false; } return validate; }, /** * get all Eth accounts on local host * @function getEthAccounts * @returns {string[]} */ getEthAccounts() { let config = utils.getConfigSetting('sdk:config', undefined); let ethAddrs = Object.keys(new KeystoreDir(config.ethKeyStorePath).getAccounts()); return ethAddrs; }, /** * get all Wan accounts on local host * @function getWanAccounts * @returns {string[]} */ getWanAccounts() { let config = utils.getConfigSetting('sdk:config', undefined); let wanAddrs = Object.keys(new KeystoreDir(config.wanKeyStorePath).getAccounts()); return wanAddrs; }, /** * get all Eos accounts from hdwallet DB * @function getEosAccounts * @returns {string[]} */ getEosAccounts(){ let eosChainID = 194; let config = utils.getConfigSetting('sdk:config', undefined); let eosAddrs = hdUtil.getImportAccountsForChain(config.network, eosChainID).accounts; return eosAddrs; }, /** * get all Eos accounts from Pubkey * @function getEosAccountsByPubkey * @returns {string[]} */ async getEosAccountsByPubkey(chain, pubkey){ let eosAddrs = await this.getAccounts(chain, pubkey); return eosAddrs; }, /** * get all Eth accounts on local host * @function getEthAccountsInfo * @async * @returns {Promise<Array>} */ async getEthAccountsInfo() { let bs; let ethAddrs = this.getEthAccounts(); try { bs = await this.getMultiBalances(ethAddrs, 'ETH'); } catch (err) { // logger.error("getEthAccountsInfo", err); return []; } let infos = []; for (let i = 0; i < ethAddrs.length; i++) { let info = {}; info.balance = bs[ethAddrs[i]]; info.address = ethAddrs[i]; infos.push(info); } // logger.debug("Eth Accounts infor: ", infos); return infos; }, /** * get all Wan accounts on local host * @function getWanAccountsInfo * @async * @returns {Promise<Array>} */ async getWanAccountsInfo() { let wanAddrs = this.getWanAccounts(); let bs = await this.getMultiBalances(wanAddrs, 'WAN'); let infos = []; for (let i = 0; i < wanAddrs.length; i++) { let info = {}; info.address = wanAddrs[i]; info.balance = bs[wanAddrs[i]]; infos.push(info); } // logger.debug("Wan Accounts infor: ", infos); return infos; }, async getWanAccountsInfoByWeb3() { try { let wanAddrs = this.getWanAccounts(); let balance; let infos = []; let web3 = global.sendByWeb3.web3; for (let i = 0; i < wanAddrs.length; i++) { let info = {}; info.address = wanAddrs[i]; balance = await this.getWanBalanceByWeb3(wanAddrs[i]); info.balance = balance.toString(10); infos.push(info); } // logger.debug("Wan Accounts infor: ", infos); return infos; } catch (error) { console.log("Error getWanAccountsInfoByWeb3"); } }, async getWanBalanceByWeb3(addr) { return new Promise(function (resolve, reject) { let web3 = global.sendByWeb3.web3; web3.eth.getBalance(addr, function (err, result) { if (err) { reject(err); } else { resolve(result); } }) }); }, /** * get all Eos accounts Info on local host with balance info and permission * @function getEosAccountsInfo * @async * @returns {Promise<Array>} */ async getEosAccountsInfo() { let infos = []; try { let eosAccountList = await this.getEosAccounts(); for (var eosAddr in eosAccountList) { let info = await this.getEosAccountInfo(eosAddr); info.permission = eosAccountList[eosAddr]; infos.push(info); } } catch (err) { logger.error("getEOSAccountsInfo", err); return []; } logger.debug("EOS Accounts info: ", infos); return infos; }, /** * get Eos account Detail Info by account on local host * @function getEosAccountInfo * @async * @returns {Promise<>} */ async getEosAccountInfo(account) { let info = {}; try { let data = await this.getAccountInfo('EOS', account); if (data.core_liquid_balance) { info.balance = parseFloat(data.core_liquid_balance.slice(0, -4)); } info.netBalance = data.net_weight / 10000; info.cpuBalance = data.cpu_weight / 10000; info.ramAvailable = (data.ram_quota - data.ram_usage) / 1024; //unit KB info.ramTotal = data.ram_quota / 1024; // info.netAvailable = (data.net_limit.max - data.net_limit.used)/1024; //unit KB info.netAvailable = data.net_limit.available / 1024; //unit KB info.netTotal = data.net_limit.max/1024; // info.cpuAvailable = (data.cpu_limit.max - data.cpu_limit.used) / 1000; //unit ms info.cpuAvailable = data.cpu_limit.available / 1000; //unit ms info.cpuTotal = data.cpu_limit.max / 1000; info.address = account; let activeKeys= [], ownerKeys =[]; for (var permission of data.permissions) { if (permission.perm_name === 'active') { for (var index in permission.required_auth.keys) { activeKeys.push(permission.required_auth.keys[index].key); } } if (permission.perm_name === 'owner') { for (var index in permission.required_auth.keys) { ownerKeys.push(permission.required_auth.keys[index].key); } } } info.activeKeys = activeKeys; info.ownerKeys = ownerKeys; } catch (err) { logger.error("getEosAccountInfo", err); return {}; } logger.debug("EOS Account info: ", info); return info; }, /** * Get GWei to Wei , used for gas price. * @function getGWeiToWei * @param amount * @param exp * @returns {number} */ getGWeiToWei(amount, exp = 9) { // let amount1 = new BigNumber(amount); // let exp1 = new BigNumber(10); // let wei = amount1.times(exp1.pow(exp)); // return Number(wei); let wei = utils.toBigNumber(amount).times('1e' + exp).trunc(); return Number(wei); }, /** * weiToToken * @function weiToToken * @param {number} tokenWei * @param {number} decimals - Must change 18 to the decimals for the actual decimal of token. * @returns {string} */ weiToToken(tokenWei, decimals = 18) { return utils.toBigNumber(tokenWei).dividedBy('1e' + decimals).toString(10); }, /** * tokenToWei * @function tokenToWei * @param {number}token * @param {number} decimals * @returns {string} */ tokenToWei(token, decimals = 18) { let wei = utils.toBigNumber(token).times('1e' + decimals).trunc(); return wei.toString(10); }, /** * tokenToWeiHex * @function tokenToWeiHex * @param {number} token - amount of token * @param {number} decimals - the decimals of this token * @returns {string} */ tokenToWeiHex(token, decimals = 18) { let wei = utils.toBigNumber(token).times('1e' + decimals).trunc(); return '0x' + wei.toString(16); }, /** * get the decimal of the token * @function getDecimalByScAddr * @param {string} contractAddr - the token's contract address * @param {string} chainType - enum{'ETH', 'WAN','BTC'} * @returns {number} */ getDecimalByScAddr(contractAddr, chainType) { let chainName = this.getSrcChainNameByContractAddr(contractAddr, chainType); return chainName ? chainName[1].tokenDecimals : 18; }, /** * When users cross tokens from WAN to others chain, here called outbound</br> * sdk lock the return value, if users leave WAN chain, the return value </br> * should be cost same as gas. if users lock token on WAN, NOT redeem on </br> * destination chain, and revoke on WAN chain. It takes users a little part</br> * return value like gas to avoid malicious cross chain transaction. *@function calculateLocWanFee * @param {number} value * @param {number} coin2WanRatio * @param {number} ctxFeeRatio * @returns {string} */ calculateLocWanFee(value, coin2WanRatio, txFeeRatio) { let wei = web3utils.toWei(utils.toBigNumber(value)); return this.calculateLocWanFeeWei(wei, coin2WanRatio, txFeeRatio); }, calculateLocWanFeeWei(value, coin2WanRatio, txFeeRatio) { let wei = utils.toBigNumber(value); const DEFAULT_PRECISE = 10000; let fee = wei.mul(coin2WanRatio).mul(txFeeRatio).div(DEFAULT_PRECISE).div(DEFAULT_PRECISE).trunc(); return '0x' + fee.toString(16); }, sleep(time) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(); }, time); }); }, async lockMutex(mutex) { while (global.mutexNonce) { await this.sleep(3); } global.mutexNonce = true; }, async unlockMutex(mutex) { global.mutexNonce = false; }, getNonceByLocal(addr, chainType) { let self = this; return new Promise(async (resolve, reject) => { await self.lockMutex(global.mutexNonce); let retNonce; try { let noncePendingCurrent = Number(await self.getNonce(addr, chainType, true)); let mapAccountNonce = global.mapAccountNonce; if (mapAccountNonce.get(chainType).has(addr)) { // get usedPendingNonce let usedPendingNonce = mapAccountNonce.get(chainType).get(addr).usedPendingNonce; if (noncePendingCurrent >= (Number(usedPendingNonce) + 1)) { let nonce = noncePendingCurrent; // update Map; mapAccountNonce.get(chainType).get(addr).usedPendingNonce = nonce; // clear the hole list; mapAccountNonce.get(chainType).get(addr).nonceHoleList.length = 0; retNonce = nonce; await self.unlockMutex(global.mutexNonce); resolve(retNonce); } else { let nonceHoleList = mapAccountNonce.get(chainType).get(addr).nonceHoleList; if (nonceHoleList.length >= 1) { // get nonce object. let nonce = nonceHoleList[0]; // remove nonceHoleList[0]; nonceHoleList.splice(0, 1); retNonce = nonce; await self.unlockMutex(global.mutexNonce); resolve(retNonce); } else { let nonce = Number(usedPendingNonce) + 1; mapAccountNonce.get(chainType).get(addr).usedPendingNonce = nonce; retNonce = nonce; await self.unlockMutex(global.mutexNonce); resolve(retNonce); } } } else { let accountNonceObject = { key: addr, usedPendingNonce: noncePendingCurrent, nonceHoleList: [], }; mapAccountNonce.get(chainType).set(addr, accountNonceObject); let nonce = noncePendingCurrent; accountNonceObject.usedPendingNonce = nonce; retNonce = nonce; await self.unlockMutex(global.mutexNonce); resolve(retNonce); } } catch (err) { await self.unlockMutex(global.mutexNonce); reject(err); } }); }, addNonceHoleToList(addr, chainType, nonce) { let self = this; return new Promise(async function (resolve, reject) { try { await self.lockMutex(global.mutexNonce); //let accountNonceObject = global.mapAccountNonce.get(chainType).get(addr); if (global.mapAccountNonce.get(chainType).has(addr)) { let accountNonceObject = global.mapAccountNonce.get(chainType).get(addr); if (accountNonceObject.nonceHoleList.indexOf(Number(nonce)) === -1) { accountNonceObject.nonceHoleList.push(Number(nonce)); } } await self.unlockMutex(global.mutexNonce); resolve(nonce); } catch (err) { await self.unlockMutex(global.mutexNonce); reject(err); } }) }, /** * @function getNonceByWeb3 * @param addr, includePendingOrNot * @returns {Promise<any>} */ getNonceByWeb3(addr, includePendingOrNot = true) { let web3 = global.sendByWeb3.web3; let nonce; return new Promise(function (resolve, reject) { if (includePendingOrNot) { web3.eth.getTransactionCount(addr, 'pending', function (err, result) { if (!err) { nonce = '0x' + result.toString(16); resolve(nonce); } else { reject(err); } }) } else { web3.eth.getTransactionCount(addr, function (err, result) { if (!err) { nonce = '0x' + result.toString(16); resolve(nonce); } else { reject(err); } }) } }) }, /** * @function sendTransByWeb3 * @param signedData * @returns {Promise<any>} */ sendTransByWeb3(signedData) { return global.sendByWeb3.sendTrans(signedData); }, /** * Revoke */ getOutRevokeEvent(chainType, hashX, toAddr) { // Outbound revoke let config = utils.getConfigSetting('sdk:config', undefined); let topic = [ccUtil.getEventHash(config.outRevokeEvent, config.HtlcWANAbi), null, hashX]; return this.getHtlcEvent(topic, config.wanHtlcAddr, chainType); }, getInRevokeEvent(chainType, hashX, toAddr) { let config = utils.getConfigSetting('sdk:config', undefined); let topic = [ccUtil.getEventHash(config.inRevokeEvent, config.HtlcETHAbi), null, hashX]; return this.getHtlcEvent(topic, config.ethHtlcAddr, chainType); }, getOutErc20RevokeEvent(chainType, hashX, toAddr) { let config = utils.getConfigSetting('sdk:config', undefined); let topic = [ccUtil.getEventHash(config.outRevokeEventE20, config.wanAbiE20), null, hashX, null]; return this.getHtlcEvent(topic, config.wanHtlcAddrE20, chainType); }, getInErc20RevokeEvent(chainType, hashX, toAddr) { let config = utils.getConfigSetting('sdk:config', undefined); let topic = [ccUtil.getEventHash(config.inRevokeEventE20, config.ethAbiE20), null, hashX, null]; return this.getHtlcEvent(topic, config.ethHtlcAddrE20, chainType); }, getOutEosRevokeEvent(chainType, hashX, toAddr) { let config = utils.getConfigSetting('sdk:config', undefined); let topic = [ccUtil.getEventHash(config.outRevokeEventEos, config.wanHtlcAbiEos), null, hashX]; return this.getHtlcEvent(topic, config.wanHtlcAddrEos, chainType); }, getInEosRevokeEvent(chainType, hashX, toAddr) { let self = this; return new Promise(async function (resolve, reject) { try { let config = utils.getConfigSetting('sdk:config', undefined); let filter = action => ['inrevoke'].includes(action.action_trace.act.name) && action.action_trace.act.data.xHash === self.hexTrip0x(hashX); let result = await self.getActions(chainType, config.eosHtlcAddr); let actions = result.filter(filter); console.log(actions); resolve(actions); } catch (err) { reject(err); } }); }, /** * Redeem */ getOutRedeemEvent(chainType, hashX, toAddr) { let config = utils.getConfigSetting('sdk:config', undefined); // WETH --> ETH let topic = [ccUtil.getEventHash(config.outRedeemEvent, config.HtlcETHAbi), null, null, hashX]; return this.getHtlcEvent(topic, config.ethHtlcAddr, chainType); }, getInRedeemEvent(chainType, hashX, toAddr) { let config = utils.getConfigSetting('sdk:config', undefined); // ETH --> WETH let topic = [ccUtil.getEventHash(config.inRedeemEvent, config.HtlcWANAbi), null, null, hashX]; return this.getHtlcEvent(topic, config.wanHtlcAddr, chainType); }, getOutErc20RedeemEvent(chainType, hashX, toAddr) { let config = utils.getConfigSetting('sdk:config', undefined); // WERC20 --> ERC20 let topic = [ccUtil.getEventHash(config.outRedeemEventE20, config.ethAbiE20), null, null, hashX]; return this.getHtlcEvent(topic, config.ethHtlcAddrE20, chainType); }, getInErc20RedeemEvent(chainType, hashX, toAddr) { let config = utils.getConfigSetting('sdk:config', undefined); // ERC20 --> WERC20 let topic = [ccUtil.getEventHash(config.inRedeemEventE20, config.wanAbiE20), null, null, hashX]; return this.getHtlcEvent(topic, config.wanHtlcAddrE20, chainType); }, getOutEosRedeemEvent(chainType, hashX, toAddr) { let self = this; return new Promise(async function (resolve, reject) { try { let config = utils.getConfigSetting('sdk:config', undefined); let filter = action => ['outredeem'].includes(action.action_trace.act.name) && action.action_trace.act.data.xHash === self.hexTrip0x(hashX) && action.action_trace.act.data.user === toAddress; let result = await self.getActions(chainType, config.eosHtlcAddr); let actions = result.filter(filter); console.log(actions); resolve(actions); } catch (err) { reject(err); } }); }, getInEosRedeemEvent(chainType, hashX, toAddr) { let config = utils.getConfigSetting('sdk:config', undefined); let topic = [ccUtil.getEventHash(config.inRedeemEventEos, config.wanHtlcAbiEos), toAddr, hashX, null]; return this.getHtlcEvent(topic, config.wanHtlcAddrEos, chainType); }, /** * --------------------------------------------------------------------------- * BTC APIs * --------------------------------------------------------------------------- */ /** * Filter btc addresses by amount, return the addresses with sufficient amount. * @param addressList All the btc addresses. * @param amount The amount to fit. */ async filterBtcAddressByAmount(addressList, amount) { let addressWithBalance = []; let config = utils.getConfigSetting('sdk:config', undefined); for (let i = 0; i < addressList.length; i++) { let utxos = await this.getBtcUtxo(config.MIN_CONFIRM_BLKS, config.MAX_CONFIRM_BLKS, [addressList[i].address]); let result = await this.getUTXOSBalance(utxos); addressWithBalance.push({ 'address': addressList[i].address, 'balance': Number(utils.toBigNumber(result).div(100000000).toString()) }); } addressWithBalance = addressWithBalance.sort((a, b) => { return b.balance - a.balance; }); let addressListReturn = []; let totalBalance = 0; for (let i = 0; i < addressWithBalance.length; i++) { totalBalance += addressWithBalance[i].balance; addressListReturn.push(addressWithBalance[i].address); if (totalBalance > Number(amount)) { break; } } return addressListReturn; }, /** */ getUTXOSBalance(utxos) { let sum = 0 let i = 0 for (i = 0; i < utxos.length; i++) { sum += utxos[i].value } return sum }, /** */ async getBtcUtxo(minconf, maxconf, addresses) { let utxos = await this._getBtcUtxo(minconf, maxconf, addresses); let utxos2 = utxos.map(function (item, index) { let av = item.value ? item.value : item.amount; item.value = Number(utils.toBigNumber(av).mul(100000000)); item.amount = item.value; return item; }); return utxos2; }, btcGetTxSize(vin, vout) { return vin * 180 + vout * 34 + 10 + vin; }, keysort(key, sortType) { // TODO: this keysort doesn't work as expect, should change it some how return function (a, b) { return sortType ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]) } }, btcCoinSelect(utxos, value, feeRate, minConfParam) { let ninputs = 0; let availableSat = 0; let inputs = []; let outputs = []; let fee = 0; let minConfirm = 0; if (minConfParam) { minConfirm = minConfParam; } utxos = utxos.sort(this.keysort('value', true)); for (let i = 0; i < utxos.length; i++) { const utxo = utxos[i] if (utxo.confirmations >= minConfirm) { availableSat += Math.round(utxo.value) ninputs++ inputs.push(utxo) fee = this.btcGetTxSize(ninputs, 2) * feeRate if (availableSat >= value + fee) { break } } } fee = this.btcGetTxSize(ninputs, 2) * feeRate let change = availableSat - value - fee if (change < 0) { throw (new Error('balance can not offord fee and target tranfer value')); } return { inputs, change, fee } }, /** */ async btcBuildTransaction(utxos, keyPairArray, target, feeRate) { let addressArray = []; let addressKeyMap = {}; let i; for (i = 0; i < keyPairArray.length; i++) { let kp = keyPairArray[i]; let address = btcUtil.getAddressbyKeypair(kp); addressArray.push(address); addressKeyMap[address] = kp; } let balance = this.getUTXOSBalance(utxos); if (balance <= target.value) { throw (new Error('utxo balance is not enough')); } let { inputs, outputs, fee } = this.btcCoinSelect(utxos, target, feeRate); // .inputs and .outputs will be undefined if no solution was found if (!inputs || !outputs) { throw (new Error('utxo balance is not enough')); } logger.debug('fee', fee); let config = utils.getConfigSetting('sdk:config', undefined); let txb = new bitcoin.TransactionBuilder(config.bitcoinNetwork); for (i = 0; i < inputs.length; i++) { let inItem = inputs[i]; txb.addInput(inItem.txid, inItem.vout); } // put out at 0 position for (i = 0; i < outputs.length; i++) { let outItem = outputs[i]; if (!outItem.address) { txb.addOutput(addressArray[0], Math.round(outItem.value)); } else { txb.addOutput(outItem.address, Math.round(outItem.value)); } } let rawTx; for (i = 0; i < inputs.length; i++) { let inItem = inputs[i]; let from = inItem.address; let signer = addressKeyMap[from]; txb.sign(i, signer); } rawTx = txb.build().toHex() logger.debug('rawTx: ', rawTx) return { rawTx: rawTx, fee: fee }; }, getBtcWanTxHistory(option) { // NOTICE: BTC normal tx and cross tx use same collection !! let config = utils.getConfigSetting('sdk:config', undefined); let collection = config.crossCollectionBtc; return global.wanDb.getItemAll(collection, option); }, insertNormalTx(tx, status = 'Sent', source = "external", satellite = {}) { if (typeof tx !== 'object') { throw new error.InvalidParameter("Insert normal transaction got invalid tx!"); } let collection = utils.getConfigSetting('sdk:config:normalCollection', 'normalTrans'); if (!tx.hasOwnProperty('hashX')) { let x = this.generatePrivateKey(); tx.hashX = this.getHashKey(x); } let now = parseInt(Number(Date.now()) / 1000).toString(); let record = { "hashX": tx.hashX, "txHash": tx.txHash, "from": tx.from, "to": tx.to, "value": tx.value, "gasPrice": tx.gasPrice, "gasLimit": tx.gasLimit, "nonce": tx.nonce, "sendTime": tx.sendTime || now, "sentTime": tx.sentTime || now, "successTime": "", "chainAddr": tx.srcSCAddrKey, "chainType": tx.srcChainType, "tokenSymbol": tx.tokenSymbol, "status": status, "source": source } Object.assign(record, satellite); global.wanDb.insertItem(collection, record); }, getEventHash(eventName, contractAbi) { return '0x' + wanUtil.sha3(this.getcommandString(eventName, contractAbi)).toString('hex'); }, getcommandString(funcName, contractAbi) { for (var i = 0; i < contractAbi.length; ++i) { let item = contractAbi[i]; if (item.name == funcName) { let command = funcName + '('; for (var j = 0; j < item.inputs.length; ++j) { if (j != 0) { command = command + ','; } command = command + item.inputs[j].type; } command = command + ')'; return command; } } }, checkWanPassword(address, keyPassword) { if (address.indexOf('0x') == 0) { address = address.slice(2); } address = address.toLowerCase(); let filepath = this.getKsfullnamebyAddr(address); if (!filepath) { return false; } let keystoreStr = fs.readFileSync(filepath, "utf8"); let keystore = JSON.parse(keystoreStr); let keyBObj = { version: keystore.version, crypto: keystore.crypto2 }; try { keythereum.recover(keyPassword, keyBObj); return true; } catch (error) { return false; } }, // addr has no '0x' already. getKsfullnamebyAddr(addr) { let config = utils.getConfigSetting('sdk:config', undefined); let addrl = addr.toLowerCase(); let keystorePath = config.wanKeyStorePath; let files = fs.readdirSync(keystorePath); let i = 0; for (i = 0; i < files.length; i++) { if (files[i].toLowerCase().indexOf(addrl) != -1) { break; } } if (i == files.length) { return ""; } return path.join(keystorePath, files[i]); }, // Contract /** * Wrapper of stand web3 interface. * @function getDataByFuncInterface * @param abi * @param contractAddr * @param funcName * @param args * @returns {*} */ getDataByFuncInterface(abi, contractAddr, funcName, ...args) { return web3utils.getDataByFuncInterface(abi, contractAddr, funcName, ...args); }, /** * @function getPrivateKey * @param address * @param password * @param keystorePath * @returns {*} */ getPrivateKey(address, password, keystorePath) { let keystoreDir = new KeystoreDir(keystorePath); let account = keystoreDir.getAccount(address); let privateKey = account.getPrivateKey(password); return privateKey; }, /** * It is used to sign transaction. * @function signFunc * @param trans * @param privateKey * @param TxClass * @returns {string} */ signFunc(trans, privateKey, TxClass) { logger.debug("before singFunc: trans"); const tx = new TxClass(trans); tx.sign(privateKey); const serializedTx = tx.serialize(); return "0x" + serializedTx.toString('hex'); }, /** * @function signEthByPrivateKey * @param trans * @param privateKey * @returns {*|string} */ signEthByPrivateKey(trans, privateKey) { return this.signFunc(trans, privateKey, ethTx); }, /** * @function signWanByPrivateKey * @param trans * @param privateKey * @returns {*|string} */ signWanByPrivateKey(trans, privateKey) { return this.signFunc(trans, privateKey, wanchainTx); }, parseLogs(logs, abi) { if (logs === null || !Array.isArray(logs)) { return logs; } let evts = abi.filter(function (json) { return json.type === 'event'; }); return logs.map(function (log) { let e = evts.find(function (evt) { return (web3utils.signFunction(evt) === log.topics[0].replace("0x", "")); }); if (e) { return web3utils.decodeEventLog(e, log); } else { return log; } }); }, // Cross invoke /** * Get all the {@link CrossInvoker#tokenInfoMap token info} supported by system. * @function getSrcChainName * @returns {Promise<*>} */ getSrcChainName() { return global.crossInvoker.getSrcChainName(); }, /** * Get the left {@link CrossInvoker#tokenInfoMap token info} supported by system after users select source chain. * @function getDstChainName * @param selectedSrcChainName * @returns {Map<string, Map<string, Object>>|Map<any, any>} */ getDstChainName(selectedSrcChainName) { return global.crossInvoker.getDstChainName(selectedSrcChainName); }, /** * Get storeman group list for cross chain.(Source chain -> Destination chain) * @function getStoremanGroupList * @param {Object} srcChainName - {@link CrossInvoker#tokenInfoMap Token info. on source chain.} * @param {Object} dstChainName - {@link CrossInvoker#tokenInfoMap Token info. on destination chain.} * @returns {Promise<Array>} */ getStoremanGroupList(srcChainName, dstChainName) { return global.crossInvoker.getStoremanGroupList(srcChainName, dstChainName); }, /** * Get token info. in two layers {@link CrossInvoke#tokenInfoMap MAP} data structure. * @function getSrcChainNameByContractAddr * @param contractAddr * @param chainType * @returns {Object|null} */ getSrcChainNameByContractAddr(contractAddr, chainType) { return global.crossInvoker.getSrcChainNameByContractAddr(contractAddr, chainType); }, /** * getKeyStorePaths * @function getKeyStorePaths * @param srcChainName * @param dstChainName * @returns {Array} */ getKeyStorePaths(srcChainName, dstChainName) { return global.crossInvoker.getKeyStorePaths(srcChainName, dstChainName); }, /** * This function is used to finish cross chain. * @function invokeCrossChain * @param srcChainName - source {@link CrossInvoke#tokenInfoMap tokenInfo} * @param dstChainName - destination {@link CrossInvoke#tokenInfoMap tokenInfo} * @param {string} action - enum{APPROVE, LOCK, REDEEM, REVOKE} * @param {Object} input - users input, see {@link CrossChain#input input example} * @returns {Promise<*>} */ invokeCrossChain(srcChainName, dstChainName, action, input) { return global.crossInvoker.invoke(srcChainName, dstChainName, action, input); }, async scanOTA(wid, path, password) { return global.OTAbackend.startScan(wid, path, password); }, /** * This function is used to check whether the record(representing one transaction) can be redeemed or not.</br> <pre> 0:00 0:15(BuddyLocked) 1:15(BuddyLocked timeout) 2:15(destionation chain timeout) | | | | ------------------------------------------------------------------------------------------ destination chain |Not Redeem | Can Redeem | Not Redeem | Not Redeem |Not Revoke | Can Redeem | Not Revoke | Can Revoke 0:00(Locked) 1:00(Locked timeout) 2:00(source chain timeout) | | | -------------------------------------------------------------------------------------- source chain </pre> * @param {Object} record <pre> { "hashX": "0x33a80caf5902f11c55b91a8b385146cdecbbfc593d030b5b64f688ed3f9b8f95", "x": "0x5c5ddca6ddbf6c0fbc5049b89913e3c1f169ca3d13d12da4d1b58c1b5d1c3e22", "from": "0xf47a8bb5c9ff814d39509591281ae31c0c7c2f38", "to": "0x393e86756d8d4cf38493ce6881eb3a8f2966bb27", "storeman": "0x41623962c5d44565de623d53eb677e0f300467d2", "value": 0, "contractValue": "0x15d3ef79800", "lockedTime": "1540878845", "buddyLockedTime": "1540878909", "srcChainAddr": "0x00f58d6d585f84b2d7267940cede30ce2fe6eae8", "dstChainAddr": "WAN", "srcChainType": "ETH", "dstChainType": "WAN", "status": "BuddyLocked", "approveTxHash": "0x2731869b8e77828f6c386ad7e7eb167baeffceab0ffd0487abac2b8eaa8ab8f3", "lockTxHash": "0xd61a4f4c8a00613a9d4932aba79a6efa2e2414b044b173f75b464d8e276fa168", "redeemTxHash": "", "revokeTxHash": "", "buddyLockTxHash": "0xf1d00967401759436ece3bd987427f68e8766120f8e0db51ae75c22e55803958", "tokenSymbol": "ZRX", "tokenStand": "E20", "htlcTimeOut": "1541138045", "buddyLockedTimeOut": "1541008509" } </pre> * @returns {{code: boolean, result: null}|transUtil.retResult|{code, result}} */ canRedeem(record) { let retResultTemp = {}; Object.assign(retResultTemp, retResult); let lockedTime = Number(record.lockedTime); let buddyLockedTime = Number(record.buddyLockedTime); let status = record.status; let buddyLockedTimeOut = Number(record.buddyLockedTimeOut); //global.lockedTime if (status !== 'BuddyLocked' && status !== 'RedeemSent' && status !== 'RedeemSending' && status !== 'RedeemFail') { retResultTemp.code = false; retResultTemp.result = "waiting buddy lock"; return retResultTemp; } let currentTime = Number(Date.now()) / 1000; //unit s logger.debug("lockedTime,buddyLockedTime,status, currentTime, buddyLockedTimeOut\n"); logger.debug(lockedTime, buddyLockedTime, status, currentTime, buddyLockedTimeOut); if (currentTime < buddyLockedTimeOut) { retResultTemp.code = true; return retResultTemp; } else { retResultTemp.code = false; retResultTemp.result = "Hash lock time is not meet."; return retResultTemp; } }, /** * This function is used to check whether the record(representing one transaction) can be revoked or not.</br> * see comments of {@link ccUtil#canRedeem canRedeem} * @function canRevoke * @param record * @returns {{code: boolean, result: null}|transUtil.retResult|{code, result}} */ canRevoke(record) { let retResultTemp = {}; Object.assign(retResultTemp, retResult); let lockedTime = Number(record.lockedTime); let buddyLockedTime = Number(record.buddyLockedTime); let status = record.status; let htlcTimeOut = Number(record.htlcTimeOut); if (status !== 'BuddyLocked' && status !== 'Locked' && status !== 'RedeemSending' && status !== 'RedeemSent' && status !== 'RevokeSent' && status !== 'RevokeSending' && status !== 'RevokeFail' && status !== 'RedeemFail' && status !== 'RevokeSendFail' && status !== 'RedeemSendFail') { retResultTemp.code = false; retResultTemp.result = "Can not revoke,status is not BuddyLocked or Locked"; return retResultTemp; } let currentTime = Number(Date.now()) / 1000; logger.debug("lockedTime,buddyLockedTime,status, currentTime, htlcTimeOut\n"); logger.debug(lockedTime, buddyLockedTime, status, currentTime, htlcTimeOut); if (currentTime > htlcTimeOut) { retResultTemp.code = true; return retResultTemp; } else { retResultTemp.code = false; retResultTemp.result = "Hash lock time is not meet."; return retResultTemp; } }, /** Since one contract has two addresses, one is original address, the other is buddy address(contract address on WAN) * @function * @param contractAddr * @param chainType * @returns {string} */ getKeyByBuddyContractAddr(contractAddr, chainType) { return global.crossInvoker.getKeyByBuddyContractAddr(contractAddr, chainType); }, /** * Used to set initial nonce for Test Only. * @function setInitNonceTest * @param initNonce */ setInitNonceTest(initNonce) { global.nonceTest = initNonce; }, /** * Get nonce based on initial nonce for Test. * @function getNonceTest * @returns {*|null|number} */ getNonceTest() { global.nonceTest = Number(global.nonceTest) + 1; return global.nonceTest; }, /** *@function getCrossInvokerConfig * @param srcChainName - source {@link CrossInvoke#tokenInfoMap tokenInfo} * @param dstChainName - destination {@link CrossInvoke#tokenInfoMap tokenInfo} * @returns {*} - return computed config.{@link CrossChain#config example config} */ getCrossInvokerConfig(srcChainName, dstChainName) { return global.crossInvoker.getCrossInvokerConfig(srcChainName, dstChainName); }, /** * getCrossInvokerClass * @function getCrossInvokerClass * @param crossInvokerConfig - see {@link ccUtil#getCrossInvokerConfig crossInvokerConfig} * @param action - APPROVE,LOCK, REDEEM, REVOKE * @returns {CrossChain|*} - instance of class CrossChain or sub class of CrossChain. */ getCrossInvokerClass(crossInvokerConfig, action) { return global.crossInvoker.getCrossInvokerClass(crossInvokerConfig, action); }, /** * get CrossChain instance. * @param crossInvokerClass - see {@link ccUtil#getCrossInvokerClass} * @param crossInvokerInput - see {@link CrossChain#input} * @param crossInvokerConfig - see {@link ccUtil#getCrossInvokerConfig} * @returns {any|CrossChain} - uses can call return value's run function to finish cross chain transaction. */ getCrossChainInstance(crossInvokerClass, crossInvokerInput, crossInvokerConfig) { return global.crossInvoker.getInvoker(crossInvokerClass, crossInvokerInput, crossInvokerConfig); }, /** * get src chain dic. for end users to select source chain. * @function getSrcChainDic * @returns {*} - sub collection{'ETH','BTC','WAN'} */ getSrcChainDic() { return global.crossInvoker.getSrcChainDic(); }, /** * Override properies' value to '*******' * @function hiddenProperties * @param inputObj * @param properties */ hiddenProperties(inputObj, properties) { let retObj = {}; Object.assign(retObj, inputObj); for (let propertyName of properties) { retObj[propertyName] = '*******'; } return retObj; }, /** * Override properies' value to '*******' * @function hiddenProperties * @param inputObj * @param properties */ hiddenProperties2(inputObj, properties) { let retObj = {}; Object.assign(retObj, inputObj); for (let propertyName of properties) { if (retObj.hasOwnProperty(propertyName)) { retObj[propertyName] = '*******'; } } return retObj; }, /** * Collection A, Collection B, return A-B. * @param tokensA * @param tokensB * @returns {Array} */ differenceABTokens(tokensA, tokensB) { let mapB = new Map(); for (let token of tokensB) { mapB.set(token.tokenOrigAddr, token); } let diffMap = new Map(); for (let token of tokensA) { if (mapB.has(token.tokenOrigAddr) === false) { diffMap.set(token.tokenOrigAddr, token); } } let ret = []; for (let value of diffMap.values()) { ret.push(value); } return ret; }, getRegTokens(crossChain) { return global.crossInvoker.getRegTokens(crossChain); }, getRegTokenInfo(crossChain, tokenOrigAddr) { let tokens = global.crossInvoker.getRegTokens(crossChain); let token = {}; for (let i = 0; i < tokens.length; i++) { if ((tokens[i].hasOwnProperty('tokenOrigAddr') && tokens[i]['tokenOrigAddr'] === tokenOrigAddr) || (tokens[i].hasOwnProperty('tokenOrigAccount') && tokens[i]['tokenOrigAccount'] === tokenOrigAddr)) { token = tokens[i]; break; } } return token; }, /** * ======================================================================== * RPC communication - iWAN * ======================================================================== */ /** * get storeman groups . */ getSmgList(chainType) { return global.iWAN.call('getStoremanGroups', networkTimeout, [chainType]); }, /** * @function getTxReceipt * @param chainType * @param txhash * @returns {*} */ getTxReceipt(chainType, txhash, options) { return global.iWAN.call('getTransactionReceipt', networkTimeout, [chainType, txhash, options]); }, /** * @function getTxInfo * @param chainType * @param txhash * @returns {*} */ getTxInfo(chainType, txhash, options) { options = options || { format: true }; return global.iWAN.call('getTxInfo', networkTimeout, [chainType, txhash, options]); }, /** * Get the ration between WAN and crosschain. * @function * @param crossChain * @returns {*} */ getC2WRatio(crossChain = 'ETH') { return global.iWAN.call('getCoin2WanRatio', networkTimeout, [crossChain]); }, /** * Get coin balance. * @function getBalance * @param addr * @param chainType * @returns {*} */ getBalance(addr, chainType = 'WAN') { return global.iWAN.call('getBalance', networkTimeout, [chainType, addr]); }, /** * @function getMultiBalances * @param addrs * @param chainType * @returns {*} */ getMultiBalances(addrs, chainType = 'WAN') { return global.iWAN.call('getMultiBalances', networkTimeout, [chainType, addrs]); }, /** * @function getBlockByNumber * @param blockNumber * @param chainType * @returns {*} */ getBlockByNumber(blockNumber, chainType = 'WAN') { return global.iWAN.call('getBlockByNumber', networkTimeout, [chainType, blockNumber]); }, /** * Get token balance by contract address and users addresses. * @function getTokenBalance * @param addr address * @param tokenScAddr * @param chainType * @returns {*} */ getTokenBalance(addr, tokenScAddr, chainType) { return global.iWAN.call('getTokenBalance', networkTimeout, [chainType, addr, tokenScAddr]); }, /** * Get token balance by contract address and users addresses. * @function getMultiTokenBalance * @param addrs Array addresses * @param tokenScAddr * @param chainType * @returns {*} */ getMultiTokenBalance(addrs, tokenScAddr, chainType) { return global.iWAN.call('getMultiTokenBalance', networkTimeout, [chainType, addrs, tokenScAddr]); }, /** * Get token balance by contract address and users addresses. * @function getMultiTokenBalanceByTokenScAddr * @param addrs * @param tokenScAddr * @param chainType * @returns {*} */ getMultiTokenBalanceByTokenScAddr(addrs, tokenScAddr, chainType, symbol = '') { return global.iWAN.call('getMultiTokenBalance', networkTimeout, [chainType, addrs, tokenScAddr, symbol]); }, /** * Get all ERC 20 tokens from API server. The return information include token's contract address</b> * and the buddy contract address of the token. * @function getRegErc20Tokens * @returns {*} */ getRegTokensFromRPC(crossChain) { return global.iWAN.call('getRegTokens', networkTimeout, [crossChain]); }, /** * Get all storemen groups which provide special token service, this token's address is tokenScAddr. * @function syncTokenStoremanGroups * @param tokenScAddr * @returns {*} */ syncTokenStoremanGroups(crossChain, tokenScAddr) { return global.iWAN.call('getTokenStoremanGroups', networkTimeout, [crossChain, tokenScAddr]); }, /** * @function getNonce * @param addr * @param chainType * @param includePendingOrNot * @returns {*} */ getNonce(addr, chainType, includePending = true) { if (includePending) { return global.iWAN.call('getNonceIncludePending', networkTimeout, [chainType, addr]); } else { return global.iWAN.call('getNonce', networkTimeout, [chainType, addr]); } }, async getAddrNonce(addr, chainType) { let useLocalNode = utils.getConfigSetting("sdk:config:useLocalNode", false); if (useLocalNode) { return await this.getNonceByWeb3(addr); } else { return await this.getNonceByLocal(addr, chainType); } }, getTokenInfo(tokenScAddr, chainType) { return global.iWAN.call('getTokenInfo', networkTimeout, [chainType, tokenScAddr]); }, getMultiTokenInfo(tokenScArray, chainType) { return global.iWAN.call('getMultiTokenInfo', networkTimeout, [chainType, tokenScArray]); }, /** * getToken2WanRatio * @function getToken2WanRatio * @param tokenOrigAddr * @param crossChain * @returns {*} */ getToken2WanRatio(tokenOrigAddr, crossChain = "ETH") { return global.iWAN.call('getToken2WanRatio', networkTimeout, [crossChain, tokenOrigAddr]); }, /** * ERC standard function allowance. * @function getErc20Allowance * @param tokenScAddr * @param ownerAddr * @param spenderAddr * @param chainType * @returns {*} */ getErc20Allowance(tokenScAddr, ownerAddr, spenderAddr, chainType = 'ETH') { return global.iWAN.call('getTokenAllowance', networkTimeout, [chainType, tokenScAddr, ownerAddr, spenderAddr]); }, /** * If return promise resolve, the transaction has been on the block chain.</br> * else it fails to put transaction on the block chain. * @function waitConfirm * @param txHash * @param waitBlocks * @param chainType * @returns {*} */ waitConfirm(txHash, waitBlocks, chainType, options) { return global.iWAN.call('getTransactionConfirm', networkTimeout, [chainType, waitBlocks, txHash, options]); }, /** * @function sendTrans * @param signedData * @param chainType * @returns {*} */ sendTrans(signedData, chainType) { return global.iWAN.call('sendRawTransaction', networkTimeout, [chainType, signedData]); }, // Event API /** * Users lock on source chain, and wait the lock event of storeman on destination chain.</br> * This function is used get the event of lock of storeman.(WAN->ETH coin) * @function getOutStgLockEvent * @param chainType * @param hashX * @returns {*} */ getOutStgLockEvent(chainType, hashX, toAddress) { let config = utils.getConfigSetting('sdk:config', undefined); let topics = ['0x' + wanUtil.sha3(config.outStgLockEvent).toString('hex'), null, toAddress, hashX]; return global.iWAN.call('getScEvent', networkTimeout, [chainType, config.ethHtlcAddr, topics]); }, /** * Users lock on source chain, and wait the lock event of storeman on destination chain.</br> * This function is used get the event of lock of storeman.(ETH->WAN coin) * @function getInStgLockEvent * @param chainType * @param hashX * @returns {*} */ getInStgLockEvent(chainType, hashX, toAddress) { let config = utils.getConfigSetting('sdk:config', undefined); let topics = ['0x' + wanUtil.sha3(config.inStgLockEvent).toString('hex'), null, toAddress, hashX]; return global.iWAN.call('getScEvent', networkTimeout, [chainType, config.wanHtlcAddr, topics]); }, /** * Users lock on source chain, and wait the lock event of storeman on destination chain.</br> * This function is used get the event of lock of storeman.(WAN->ETH ERC20 token) * @function getOutStgLockEventE20 * @param chainType * @param hashX * @returns {*} */ getOutStgLockEventE20(chainType, hashX, toAddress) { let config = utils.getConfigSetting('sdk:config', undefined); let topics = ['0x' + wanUtil.sha3(config.outStgLockEventE20).toString('hex'), null, toAddress, hashX]; return global.iWAN.call('getScEvent', networkTimeout, [chainType, config.ethHtlcAddrE20, topics]); }, /** * Users lock on source chain, and wait the lock event of storeman on destination chain.</br> * This function is used get the event of lock of storeman.(ETH->WAN ERC20 token) * @function getInStgLockEventE20 * @param chainType * @param hashX * @returns {*} */ getInStgLockEventE20(chainType, hashX, toAddress) { let config = utils.getConfigSetting('sdk:config', undefined); let topics = ['0x' + wanUtil.sha3(config.inStgLockEventE20).toString('hex'), null, toAddress, hashX]; return global.iWAN.call('getScEvent', networkTimeout, [chainType, config.wanHtlcAddrE20, topics]); }, /** * Users lock on source chain, and wait the lock event of storeman on destination chain.</br> * This function is used get the event of lock of storeman.(WAN->EOS EOS token) * @function getOutStgLockEventEos * @param chainType * @param hashX * @returns {*} */ getOutStgLockEventEos(chainType, hashX, toAddress) { let self = this; return new Promise(async function (resolve, reject) { try { let config = utils.getConfigSetting('sdk:config', undefined); let filter = action => ['outlock'].includes(action.action_trace.act.name) && action.action_trace.act.data.xHash === self.hexTrip0x(hashX) && action.action_trace.act.data.user === toAddress; let result = await self.getActions(chainType, config.eosHtlcAddr); let actions = result.filter(filter); console.log(actions); resolve(actions); } catch (err) { reject(err); } }); }, /** * Users lock on source chain, and wait the lock event of storeman on destination chain.</br> * This function is used get the event of lock of storeman.(Eos->WAN Eos token) * @function getInStgLockEventEos * @param chainType * @param hashX * @returns {*} */ getInStgLockEventEos(chainType, hashX, toAddress) { let config = utils.getConfigSetting('sdk:config', undefined); let topics = ['0x' + wanUtil.sha3(config.inStgLockEventEOS).toString('hex'), toAddress, hashX]; return global.iWAN.call('getScEvent', networkTimeout, [chainType, config.wanHtlcAddrEos, topics]); }, getDepositCrossLockEvent(hashX, walletAddr, chainType) { let config = utils.getConfigSetting('sdk:config', undefined); let topics = [this.getEventHash(config.depositBtcCrossLockEvent, config.HTLCWBTCInstAbi), null, walletAddr, hashX]; return global.iWAN.call('getScEvent', networkTimeout, [chainType, config.wanchainHtlcAddr, topics]); }, getBtcWithdrawStoremanNoticeEvent(hashX, walletAddr, chainType) { let config = utils.getConfigSetting('sdk:config', undefined); let topics = [this.getEventHash(config.withdrawBtcCrossLockEvent, config.HTLCWBTCInstAbi), null, walletAddr, hashX]; return global.iWAN.call('getScEvent', networkTimeout, [chainType, config.wanchainHtlcAddr, topics]); }, /** * Get event for topic on address of chainType */ async getHtlcEvent(topic, htlcAddr, chainType) { return global.iWAN.call('getScEvent', networkTimeout, [chainType, htlcAddr, topic]); }, /** * Get HTLC locked time, unit seconds. * @function getEthLockTime * @param chainType * @returns {*} */ getEthLockTime(chainType = 'ETH') { let config = utils.getConfigSetting('sdk:config', undefined); return global.iWAN.call('getScVar', networkTimeout, [chainType, config.ethHtlcAddr, 'lockedTime', config.HtlcETHAbi]); }, /** * Get HTLC locked time, unit seconds. (ERC20) * @function getE20LockTime * @param chainType * @returns {*} */ getE20LockTime(chainType = 'ETH') { let config = utils.getConfigSetting('sdk:config', undefined); return global.iWAN.call('getScVar', networkTimeout, [chainType, config.ethHtlcAddrE20, 'lockedTime', config.HtlcETHAbi]); }, /** * Get HTLC locked time, unit seconds. * @function getWanLockTime, for HTLC lock time of BTC * @param chainType * @returns {*} */ getWanLockTime(chainType = 'WAN') { let config = utils.getConfigSetting('sdk:config', undefined); return global.iWAN.call('getScVar', networkTimeout, [chainType, config.wanHtlcAddrBtc, 'lockedTime', config.wanAbiBtc]); }, /** * Get HTLC locked time, unit seconds. (EOS) * @function getEosLockTime * @param chainType * @returns {*} */ getEosLockTime(chainType = 'WAN') { let config = utils.getConfigSetting('sdk:config', undefined); return global.iWAN.call('callScFunc', networkTimeout, [chainType, config.wanHtlcAddrEos, 'getEconomics', '', config.wanHtlcAbiEos]); }, /** * For outbound (from WAN to other chain), when users redeem on other chain, it means that user leave WAN chain.</br> * It takes users {@link ccUtil#calculateLocWanFee wan} for leave chain.</br> * If users revoke on WAN chain, it means that users keep on WAN chain.On this scenario, it takes users part {@link * ccUtil#calculateLocWanFee wan} for revoke transaction. The part is related to the return ratio of this function. * @function getE20RevokeFeeRatio * @param chainType * @returns {*} */ getE20RevokeFeeRatio(chainType = 'ETH') { let p; let config = utils.getConfigSetting('sdk:config', undefined); if (chainType === 'ETH') { p = global.iWAN.call('getScVar', networkTimeout, [chainType, config.ethHtlcAddrE20, 'revokeFeeRatio', config.ethAbiE20]); } else { if (chainType === 'WAN') { p = global.iWAN.call('getScVar', networkTimeout, [chainType, config.wanHtlcAddrE20, 'revokeFeeRatio', config.wanAbiE20]); } else { return null; } } return p; }, _getBtcUtxo(minconf, maxconf, addresses) { return global.iWAN.call('getUTXO', networkTimeout, ['BTC', minconf, maxconf, addresses]); }, /** */ btcImportAddress(address) { return global.iWAN.call('importAddress', networkTimeout, ['BTC', address]); }, getBtcTransaction(txhash) { return this.getTxInfo('BTC', txhash); }, getBlockNumber(chain) { return global.iWAN.call('getBlockNumber', networkTimeout, [chain]); }, checkOTAUsed(image, timeout) { return global.iWAN.call('checkOTAUsed', timeout || networkTimeout, ['WAN', image]); }, getOTAMixSet(otaAddr, number, timeout) { return global.iWAN.call('getOTAMixSet', timeout || networkTimeout, [otaAddr, number]); }, getTransByAddressBetweenBlocks(chain, addr, start, end, timeout) { return global.iWAN.call('getTransByAddressBetweenBlocks', timeout || networkTimeout, [chain, addr, start, end]); }, // specific api for EOS eosToFloat(str) { const floatRegex = /[^\d.-]/g return parseFloat(str.replace(floatRegex, '')); }, floatToEos(amount, symbol, decimals) { let precision = parseInt(decimals); return `${new Decimal(amount).toFixed(precision)} ${symbol}` // eosjs 16.0.9 // let DecimalPad = Eos.modules.format.DecimalPad; // let precision = parseInt(decimals); // return `${DecimalPad(amount, precision)} ${symbol}` }, getEosChainInfo() { return this.getChainInfo('EOS'); }, /** * Return general network information, getInfo * @function getChainInfo * @param {*} chain */ getChainInfo(chain){ return global.iWAN.call('getChainInfo', networkTimeout, [chain]); }, /** * static method of eos, getCurrencyStats * @function getStats * @param {*} chain * @param {*} tokenScAddr * @param {*} symbol */ getStats(chain, tokenScAddr, symbol='EOS') { return global.iWAN.call('getStats', networkTimeout, [chain, tokenScAddr, symbol]); }, /** * Fetch a blockchain account Info, getAccount * @function getAccounts * @param {*} chain * @param {*} accountOrPubkey */ getAccountInfo(chain, account) { return global.iWAN.call('getAccountInfo', networkTimeout, [chain, account]); }, /** * Fetch a blockchain account, getKeyAccounts * @function getAccounts * @param {*} chain * @param {*} pubkey */ getAccounts(chain, pubkey) { return global.iWAN.call('getAccounts', networkTimeout, [chain, pubkey]); }, /** * getAbi of the contract * @function getAbi * @param {*} chain * @param {*} tokenScAddr */ getAbi(chain, tokenScAddr) { return global.iWAN.call('getAbi', networkTimeout, [chain, tokenScAddr]); }, /** * getRawAbi of the contract * @function getRawAbi * @param {*} chain * @param {*} tokenScAddr */ getRawAbi(chain, tokenScAddr) { return global.iWAN.call('getRawAbi', networkTimeout, [chain, tokenScAddr]); }, /** * getRawCodeAndAbi of the contract * @function getRawCodeAndAbi * @param {*} chain * @param {*} tokenScAddr */ getRawCodeAndAbi(chain, tokenScAddr) { return global.iWAN.call('getRawCodeAndAbi', networkTimeout, [chain, tokenScAddr]); }, /** * Convert bin hex back into Abi json definition. abiBinToJson * @function getJson2Bin * @param {*} chain * @param {*} tokenScAddr * @param {*} action * @param {*} args */ getJson2Bin(chain, tokenScAddr, action, args) { return global.iWAN.call('getJson2Bin', networkTimeout, [chain, tokenScAddr, action, args]); }, /** * Receive the actions of the account * @function getActions * @param {*} chain * @param {*} address * @param {*} indexPos * @param {*} offset */ getActions(chain, address, indexPos = -1, offset = -500) { return global.iWAN.call('getActions', networkTimeout, [chain, address, indexPos, offset]); }, /** * get the currence cpu/ram/net of the account * @function * @param {*} chain */ getResource(chain) { return global.iWAN.call('getResource', networkTimeout, [chain]); }, /** * get the current price of the cpu/ram/net * @function getResourcePrice * @param {*} chain * @param {*} address */ getResourcePrice(chain, address) { return global.iWAN.call('getResourcePrice', networkTimeout, [chain, address]); }, /** * get the current price of the cpu/net * @function getBandwidthPrice * @param {*} chain * @param {*} address */ getBandwidthPrice(chain, address) { return global.iWAN.call('getBandwidthPrice', networkTimeout, [chain, address]); }, /** * get the current price of the ram * @function getRamPrice * @param {*} chain */ getRamPrice(chain) { return global.iWAN.call('getRamPrice', networkTimeout, [chain]); }, /** * get the current staked amount of the chain * @function getTotalStaked * @param {*} chain */ getTotalStaked(chain) { return global.iWAN.call('getTotalStaked', networkTimeout, [chain]); }, /** * get the total supply amount of the chain * @function getTotalSupply * @param {*} chain */ getTotalSupply(chain) { return global.iWAN.call('getTotalSupply', networkTimeout, [chain]); }, /** * get the current stake info of the chain, totalStaked, totalSup, percent * @function getTotalStakedPercent * @param {*} chain */ getTotalStakedPercent(chain) { return global.iWAN.call('getTotalStakedPercent', networkTimeout, [chain]); }, /** * get an object containing rows from the specified table * @function getTableRows * @param {*} chain */ getTableRows(chain, scAddr, scope, table, options) { return global.iWAN.call('getTableRows', networkTimeout, [chain, scAddr, scope, table, options]); }, /** * get an account stake detail info * @function getAccountStakeInfo * @param {*} chain */ getAccountStakeInfo(chain, account) { return global.iWAN.call('getTableRows', networkTimeout, [chain, 'eosio', account, 'delband']); }, /** * get an account stake detail info * @function getAccountStakeInfo * @param {*} chain */ getAccountUnStakeInfo(chain, account) { return global.iWAN.call('getTableRows', networkTimeout, [chain, 'eosio', account, 'refunds']); }, /** * pack the tran with acitons * @function getRamPrice * @param {*} chain * @param {*} transaction(Object) */ packTransaction(chain, transaction) { return global.iWAN.call('packTransaction', networkTimeout, [chain, transaction]); }, getTransByBlock(chain, blockNo) { return global.iWAN.call('getTransByBlock', networkTimeout, [chain, blockNo]); }, getGasPrice(chain) { return global.iWAN.call('getGasPrice', networkTimeout, [chain]); }, estimateGas(chain, txobj) { return global.iWAN.call('estimateGas', networkTimeout, [chain, txobj]); }, getSlotActivity(chain, epochID) { return global.iWAN.call('getSlotActivity', networkTimeout, [chain, epochID]); }, getValidatorActivity(chain, epochID) { return global.iWAN.call('getValidatorActivity', networkTimeout, [chain, epochID]); }, getMaxStableBlkNumber(chain) { return global.iWAN.call('getMaxStableBlkNumber', networkTimeout, [chain]); }, getIWanRpc() { return global.iWAN; }, /** * Get iWAN instance */ getIWanInstance() { return global.iWAN.getClientInstance(); }, //POS getEpochID(chain) { return global.iWAN.call('getEpochID', networkTimeout, [chain]); }, getSlotID(chain) { return global.iWAN.call('getSlotID', networkTimeout, [chain]); }, getValidatorStakeInfo(chain, address) { return global.iWAN.call('getValidatorStakeInfo', networkTimeout, [chain, address]); }, getValidatorTotalIncentive(chain, address, options) { return global.iWAN.call('getValidatorTotalIncentive', networkTimeout, [chain, address, options]); }, getDelegatorStakeInfo(chain, address) { return global.iWAN.call('getDelegatorStakeInfo', networkTimeout, [chain, address]); }, getEpochLeadersByEpochID(chain, epochID) { return global.iWAN.call('getEpochLeadersByEpochID', networkTimeout, [chain, epochID]); }, getRandomProposersByEpochID(chain, epochID) { return global.iWAN.call('getRandomProposersByEpochID', networkTimeout, [chain, epochID]); }, getStakerInfo(chain, blockNumber) { return global.iWAN.call('getStakerInfo', networkTimeout, [chain, blockNumber]); }, getEpochIncentivePayDetail(chain, epochID) { return global.iWAN.call('getEpochIncentivePayDetail', networkTimeout, [chain, epochID]); }, getActivity(chain, epochID) { return global.iWAN.call('getActivity', networkTimeout, [chain, epochID]); }, getSlotActivity(chain, epochID) { return global.iWAN.call('getSlotActivity', networkTimeout, [chain, epochID]); }, getValidatorActivity(chain, epochID) { return global.iWAN.call('getValidatorActivity', networkTimeout, [chain, epochID]); }, getMaxStableBlkNumber(chain) { return global.iWAN.call('getMaxStableBlkNumber', networkTimeout, [chain]); }, getRandom(chain, epochID, blockNumber = -1) { return global.iWAN.call('getRandom', networkTimeout, [chain, epochID, blockNumber]); }, getValidatorInfo(chain, address) { return global.iWAN.call('getValidatorInfo', networkTimeout, [chain, address]); }, getValidatorStakeInfo(chain, address) { return global.iWAN.call('getValidatorStakeInfo', networkTimeout, [chain, address]); }, getValidatorTotalIncentive(chain, address, options) { return global.iWAN.call('getValidatorTotalIncentive', networkTimeout, [chain, address, options]); }, getDelegatorStakeInfo(chain, address) { return global.iWAN.call('getDelegatorStakeInfo', networkTimeout, [chain, address]); }, getValidatorSupStakeInfo(chain, address, options) { return global.iWAN.call('getValidatorSupStakeInfo', networkTimeout, [chain, address, options]); }, getDelegatorSupStakeInfo(chain, address, options) { return global.iWAN.call('getDelegatorSupStakeInfo', networkTimeout, [chain, address, options]); }, getEpochIncentiveBlockNumber(chain, epochID) { return global.iWAN.call('getEpochIncentiveBlockNumber', networkTimeout, [chain, epochID]); }, getEpochStakeOut(chain, epochID) { return global.iWAN.call('getEpochStakeOut', networkTimeout, [chain, epochID]); }, /** * ======================================================================== * Private transaction * ======================================================================== */ getOtaFunds(wid, path, excludeRefund) { if (typeof wid !== 'number' || typeof path !== 'string') { throw error.InvalidParameter("Invalid paramter wid and/or path"); } }, getDelegatorIncentive(chain, address, options) { return global.iWAN.call('getDelegatorIncentive', networkTimeout, [chain, address, options]); }, getLeaderGroupByEpochID(chain, epochID) { return global.iWAN.call('getLeaderGroupByEpochID', networkTimeout, [chain, epochID]); }, getCurrentEpochInfo(chain) { return global.iWAN.call('getCurrentEpochInfo', networkTimeout, [chain]); }, getSlotCount(chain) { return global.iWAN.call('getSlotCount', networkTimeout, [chain]); }, getSlotTime(chain) { return global.iWAN.call('getSlotTime', networkTimeout, [chain]); }, getTimeByEpochID(chain, epochID) { return global.iWAN.call('getTimeByEpochID', networkTimeout, [chain, epochID]); }, getEpochIDByTime(chain, time) { return global.iWAN.call('getEpochIDByTime', networkTimeout, [chain, time]); }, getRegisteredValidator(address, after) { return global.iWAN.call('getRegisteredValidator', networkTimeout, [address, after]); }, getPosInfo(chain) { return global.iWAN.call('getPosInfo', networkTimeout, [chain]); }, getDelegatorTotalIncentive(chain, address, options) { return global.iWAN.call('getDelegatorTotalIncentive', networkTimeout, [chain, address, options]); }, getCurrentStakerInfo(chain) { return global.iWAN.call('getCurrentStakerInfo', networkTimeout, [chain]); }, getMaxBlockNumber(chain, epochID) { return global.iWAN.call('getMaxBlockNumber', networkTimeout, [chain, epochID]); }, getValidatorSupStakeInfo(chain, address, options) { return global.iWAN.call('getValidatorSupStakeInfo', networkTimeout, [chain, address, options]); }, getDelegatorSupStakeInfo(chain, address, options) { return global.iWAN.call('getDelegatorSupStakeInfo', networkTimeout, [chain, address, options]); }, getEpochIncentiveBlockNumber(chain, epochID) { return global.iWAN.call('getEpochIncentiveBlockNumber', networkTimeout, [chain, epochID]); }, getEpochStakeOut(chain, epochID) { return global.iWAN.call('getEpochStakeOut', networkTimeout, [chain, epochID]); }, /** * ======================================================================== * Private transaction * ======================================================================== */ getOtaFunds(wid, path, excludeRefund) { if (typeof wid !== 'number' || typeof path !== 'string') { throw error.InvalidParameter("Invalid paramter wid and/or path"); } excludeRefund = excludeRefund || true; let myAddr = utils.compositeWalletKey(wid, path); let f = function (r) { if (r.toAcctID == myAddr) { if (excludeRefund && r.state === 'Refund') { return false; } return true; } return false; } let otaTbl = global.wanScanDB.getUsrOTATable(); return otaTbl.filter(f); }, /* set pubkey, w, q */ generatePubkeyIWQforRing(Pubs, I, w, q) { let length = Pubs.length; let sPubs = []; for (let i = 0; i < length; i++) { sPubs.push(Pubs[i].toString('hex')); } let ssPubs = sPubs.join('&'); let ssI = I.toString('hex'); let sw = []; for (let i = 0; i < length; i++) { sw.push('0x' + w[i].toString('hex').replace(/(^0*)/g, "")); } let ssw = sw.join('&'); let sq = []; for (let i = 0; i < length; i++) { sq.push('0x' + q[i].toString('hex').replace(/(^0*)/g, "")); } let ssq = sq.join('&'); let KWQ = [ssPubs, ssI, ssw, ssq].join('+'); return KWQ; } } module.exports = ccUtil; module.exports = new Date(2018, 0, 29) /** * @author xukj * @date 2019/01/29 * @class * @description 界面展示组件FSLCachedImage 支持缓存的Image控件 * Support RN 0.52.0 * 请使用FSLCachedImage组件替换旧的FSLCommonImage组件。1.3.6版本以后,FSLCommonImage不再维护 * * npm react-native-img-cache-kp --save * npm install rn-fetch-blob --save * react-native link rn-fetch-blob * 如果iOS端使用CocoaPods, 则需要在 Podfile 中添加 * pod 'rn-fetch-blob', :path => '../node_modules/rn-fetch-blob' * 控制台执行 pod install */ import React from "react"; import PropTypes from "prop-types"; import { StyleSheet, View, TouchableOpacity, ViewPropTypes, Image } from "react-native"; import { CachedImage, CachedImageBackground } from "react-native-img-cache-kp"; export default class FSLCachedImage extends React.PureComponent { static propTypes = { imageStyle: ViewPropTypes.style, style: ViewPropTypes.style, onPress: PropTypes.func, source: Image.propTypes.source, defaultSource: Image.propTypes.defaultSource }; static defaultProps = {}; constructor(props) { super(props); } componentDidMount() { } render() { const { style, imageStyle, source, defaultSource, onPress, children, ...restProps } = this.props; let ContainerComponent = View; if (onPress) ContainerComponent = TouchableOpacity; let ImageComponent = CachedImage; if (children) ImageComponent = CachedImageBackground; const imgSource = source ? source : {}; const imgSourceDefault = defaultSource ? defaultSource : {}; return ( <ContainerComponent style={[styles.container, style && style]} onPress={onPress} > <ImageComponent style={[ StyleSheet.absoluteFillObject, imageStyle && imageStyle ]} source={imgSource} defaultSource={imgSourceDefault} {...restProps} /> {children} </ContainerComponent> ); } } const styles = StyleSheet.create({ container: { overflow: "hidden" } }); import styled from 'styled-components' import { LoadingButton } from '@atlaskit/button' import { COLORS_PRIMARY } from '@vkr/app-constants' export const AuthContainer = styled.div` position: absolute; top: 0; left: 0; width: 100%; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; background-color: ${COLORS_PRIMARY.background}; ` export const FormContainer = styled.div` width: 400px; min-width: 350px; ` export const SubmitContainer = styled.div` width: 100%; display: flex; align-items: center; justify-content: center; ` export const StyledButton = styled(LoadingButton)` margin: 30px 30% 30px 30%; width: 100% !important; ` /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ const sinon = require('sinon'); const serviceWorkerMock = require('service-worker-mock'); const { IDBFactory, IDBKeyRange, IDBDatabase, IDBObjectStore, } = require('shelving-mock-indexeddb'); const URLSearchParams = require('url-search-params'); const Blob = require('./sw-env-mocks/Blob'); const DOMException = require('./sw-env-mocks/DOMException'); const Event = require('./sw-env-mocks/Event'); const {addEventListener, dispatchEvent} = require('./sw-env-mocks/event-listeners'); const ExtendableEvent = require('./sw-env-mocks/ExtendableEvent'); const ExtendableMessageEvent = require('./sw-env-mocks/ExtendableMessageEvent'); const fetch = require('./sw-env-mocks/fetch'); const FetchEvent = require('./sw-env-mocks/FetchEvent'); const FileReader = require('./sw-env-mocks/FileReader'); const Headers = require('./sw-env-mocks/Headers'); const Request = require('./sw-env-mocks/Request'); const Response = require('./sw-env-mocks/Response'); const SyncEvent = require('./sw-env-mocks/SyncEvent'); const SyncManager = require('./sw-env-mocks/SyncManager'); const BroadcastChannel = require('./sw-env-mocks/BroadcastChannel'); // Assign all properties of `self` to `global`; Object.assign(global, serviceWorkerMock()); // Ensure `self` and `global` are the same object so stubbing works on either. global.self = global; // Add/fix globals not in 'service-worker-mock'. global.addEventListener = addEventListener; global.Blob = Blob; global.DOMException = DOMException; global.dispatchEvent = dispatchEvent; global.Event = Event; global.ExtendableEvent = ExtendableEvent; global.ExtendableMessageEvent = ExtendableMessageEvent; global.fetch = fetch; global.FetchEvent = FetchEvent; global.FileReader = FileReader; global.Headers = Headers; global.indexedDB = new IDBFactory(); global.IDBKeyRange = IDBKeyRange; global.IDBDatabase = IDBDatabase, global.IDBObjectStore = IDBObjectStore; global.importScripts = () => {}; global.location = new URL('https://example.com'); global.registration.sync = new SyncManager(); global.Request = Request; global.Response = Response; global.SyncEvent = SyncEvent; global.URLSearchParams = URLSearchParams; global.BroadcastChannel = BroadcastChannel; global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'Workbox User Agent'; // TODO: Remove when fixed in service-worker-mock: // https://github.com/pinterest/service-workers/issues/71 const origMatch = caches.match; sinon.stub(caches, 'match').callsFake(async (req, options) => { if (options && options.cacheName) { const cache = await caches.open(options.cacheName); return cache.match(req); } return origMatch(req, options); }); <filename>aspiredb/src/main/webapp/scripts/ASPIREdb/view/report/VariantReportPanel.js /* * The aspiredb project * * Copyright (c) 2013 University of British Columbia * * 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. * */ Ext.require( [] ); /** * Create Variant Report Chart Panel */ Ext.define( 'ASPIREdb.view.report.VariantReportPanel', { extend : 'Ext.Panel', alias : 'widget.variantReportPanel', id : 'variantReport', xtype : 'clustered-column', layout : 'fit', config : { logTransform : false, N_BINS : 20, }, initComponent : function() { this.callParent(); }, /** * Return the value where the bin is found */ findBin : function(val, bins, binsText) { for (var i = 0; i < bins.length; i++) { if ( (bins[i] - Number( val )) >= 0 ) { // console.log( val + " is in bin " + BINS_TEXT[i] ); return binsText[i]; } } // it must be the last bin // console.log( val + " is in bin " + BINS_TEXT[BINS_TEXT.length - 1] ); return binsText[binsText.length - 1]; }, /** * Returns the textual representation of the bins for the chart axis, e.g. <100000, 20000-30000 */ bins2text : function(BINS) { var BINS_TEXT = []; for (var i = 0; i < BINS.length; i++) { var bin = ""; var val = BINS[i]; var prevVal = ""; if ( i > 0 ) { prevVal = BINS[i - 1]; } if ( i === 0 ) { bin = "<=" + this.formatNumberComma( val ); } else if ( i == BINS.length - 1 ) { bin = this.formatNumberComma( prevVal + 1 ) + "-" + this.formatNumberComma( val ); BINS_TEXT.push( bin ); bin = ">=" + this.formatNumberComma( val + 1 ); } else { bin = this.formatNumberComma( prevVal + 1 ) + "-" + this.formatNumberComma( val ); } BINS_TEXT.push( bin ); } return BINS_TEXT; }, formatNumberComma : function(num) { return Ext.util.Format.number( num, "0,000" ); }, /** * Use for numerical data types, bin the data first and plot the frequencies * */ calculateBinFrequencies : function(data, columnName, countColumnName, bins, binsText) { var map = new Ext.util.HashMap(); if ( bins === null ) { bins = Array.apply( 0, Array( 20 ) ).map( function(val, i) { return 10000 * (i + 1); } ); binsText = this.bins2text( bins ); } // initialize map with all the bins for (var i = 0; i < binsText.length; i++) { map.add( binsText[i], 0 ); } for (var j = 0; j < data.length; j++) { var val = data[j]; // bin the value var bin = this.findBin( val, bins, binsText ); // now lets calculate and store it! var count = map.get( bin ); count++; map.add( bin, count ); } // a collection of freq objects var ret = []; map.each( function(key, value, length) { // console.log( key, value, length ); var freq = {}; freq[columnName] = key; freq[countColumnName] = value; ret.push( freq ); } ); return ret; }, /** * @param store * Array of Variant objects, * * e.g. [ Object{"id":"var1", "type":"LOSS" }, Object{"id":"var2", "type":"LOSS" }, ] * * @param columnName * input column to extract, e.g. 'type' * @param countColumnName * output column name to store the frequency in, e.g. 'count' * @returns e.g. { "type" : "LOSS", "count" : 2 } */ calculateFrequencies : function(data, columnName, countColumnName) { var map = new Ext.util.HashMap(); for (var i = 0; i < data.length; i++) { var val = data[i]; // now lets calculate and store it! if ( map.get( val ) === undefined ) { map.add( val, 1 ); } else { var count = map.get( val ); count++; map.add( val, count ); } } // a collection of freq objects var ret = []; map.each( function(key, value, length) { // console.log(key, value, length); var freq = {}; freq[columnName] = key; freq[countColumnName] = value; ret.push( freq ); } ); return ret; }, getColumnDataFromArray : function(data, columnName) { var result = []; var errorCount = 0; for (var i = 0; i < data.length; i++) { // extract values var row = data[i]; var val = row[columnName]; // special case for VariantValueObjects if ( columnName === "chromosome" ) { val = row['genomicRange'][columnName]; } if ( val == undefined ) { // possibly a characteristic ..., special case for VariantValueObject var characteristic = row['characteristics'][columnName]; if ( characteristic == undefined ) { // only print a few error messages if ( errorCount++ < 1 ) { console.log( "Error: Attribute '" + columnName + "' not found in variant " + row.genomeCoordinates + " of patient " + row.patientId + " " ); } continue; } else { val = characteristic['value']; } } // For CNV specific attributes like type and length, ignore SNVs if ( !ASPIREdb.view.report.VariantReportWindow.isVariantTypeAndReportFieldCompatible( columnName, row["variantType"] ) ) { continue; } // show NA for empty values if ( val === "" ) { val = "<NA>"; } result.push( val ); } return result; }, saveAsPNG : function() { this.down( '#variantChart' ).save( { type : 'image/png' } ); }, /** * Display the data in a column chart series * * mergedFreqData = '[{"type":"LOSS","asd1":136, "asd2":200},{"type":"GAIN","asd1":97, "asd2":100}]' columnName = * "type" labelNames = ["asd1","asd2"] */ createLabelReport : function(mergedFreqData, columnName, labelNames) { var me = this; var countColumnName = '# of variants'; var seriesTitle = labelNames; // get total counts for each label var totals = {}; mergedFreqData.forEach( function(o) { for ( var label in o) { if ( label === columnName ) { continue; } if ( totals[label] === undefined ) { totals[label] = o[label]; } else { totals[label] += o[label]; } } } ); var title = 'Project: ' + ASPIREdb.ActiveProjectSettings.getActiveProjectName(); var varCountsText = "# of variants: " + Ext.util.JSON.encode( totals ).replace( '{', '' ).replace( '}', '' ).replace( /,/g, ', ' ) .replace( /"/g, '' ).replace( /:/g, ' ' ); var xField = columnName; var yField = seriesTitle; var fields = [ columnName ].concat( seriesTitle ); // insert "type" into the first position // xField = "type" // yField = "withVar" // fields = ["type", "withVar"] // mergedFreqData = { { type : "LOSS", withVar : 68}, { type : "GAIN", withVar : 40 } } // convert to Extjs Store // JSON store have problems with columnNames that have spaces! /* * var myDataStore = Ext.create( 'Ext.data.JsonStore', { storeId : 'reportStore', fields : fields, data : * mergedFreqData, // ensures that key names with spaces are quoted } ); */ var mergedFreqArray = [] for (var i = 0; i < mergedFreqData.length; i++) { var row = [] for (var j = 0; j < fields.length; j++) { // truncate long texts if ( typeof mergedFreqData[i][fields[j]] === "string" ) { var txt = mergedFreqData[i][fields[j]]; if ( txt.length > 20 ) { txt = txt.substr( 0, 15 ) + "..." + txt.substr( txt.length - 5, 5 ); } row.push( txt ); } else { row.push( mergedFreqData[i][fields[j]] ); } } mergedFreqArray.push( row ); } var myDataStore = Ext.create( 'Ext.data.ArrayStore', { storeId : 'reportStore', fields : fields, data : mergedFreqArray, // ensures that key names with spaces are quoted } ); me.add( [ { xtype : 'chart', id : 'variantChart', width : '100%', // height : 410, padding : '10 0 0 0', // (top, right, bottom, left). animate : true, shadow : false, layout : 'fit', style : 'background: #fff;', legend : { padding : 0, position : 'bottom', boxStrokeWidth : 0, labelFont : '11px Helvetica' }, store : myDataStore, insetPadding : 50, items : [ { type : 'text', text : title, font : '18px Helvetica', width : 100, height : 100, x : 40, // the sprite x position y : 10 // the sprite y position }, { type : 'text', text : 'ASPIREdb', font : '12px Helvetica', x : 12, y : 380 }, { type : 'text', text : varCountsText, font : '12px Helvetica', x : 40, y : 340 } ], axes : [ { type : 'numeric', position : 'left', fields : yField, grid : true, minimum : 0, title : countColumnName, label : { renderer : function(v) { // return v + '%'; return v; } } }, { type : 'category', position : 'bottom', fields : xField, title : columnName, grid : true, label : { rotate : { degrees : -90 } } } ], series : [ { type : 'column', axis : 'left', xField : xField, yField : yField, title : seriesTitle, style : { opacity : 0.80 }, highlight : { fill : '#000', 'stroke-width' : 1, stroke : '#000' }, tips : { trackMouse : true, width : 150, style : 'background: #FFF', renderer : function(storeItem, item) { var label = item.series.title[Ext.Array.indexOf( item.series.yField, item.yField )]; var msg = label + " " + storeItem.get( xField ) + ': ' + storeItem.get( item.yField ); this.update( msg ); } } } ] } ] ); me.doLayout(); me.show(); }, saveAsTXT : function() { ASPIREdb.TextDataDownloadWindow.showChartDownload( Ext.getStore( 'reportStore' ) ); }, /** * Merges the contents of freqData to mergedFreqData * * freqData = "[{"type":"LOSS","withVar":68},{"type":"GAIN","withVar":48}]" freqData = * "[{"type":"LOSS","label2":20},{"type":"GAIN","label2":10}]" * * mergedFreqData = "[{"type":"LOSS","withVar":68,"label2":20},{"type":"GAIN","withVar":48,"label2":10}]" */ mergeFreqData : function(freqData, mergedFreqData, columnName) { if ( mergedFreqData === null || mergedFreqData.length == 0 ) { return freqData; } var ret = []; // copy mergedFreqData to ret for (var i = 0; i < mergedFreqData.length; i++) { ret.push( mergedFreqData[i] ); } // copy freqData to ret, while checking if it already exists, // and if it does then merge! for (var i = 0; i < freqData.length; i++) { var freqVal = freqData[i][columnName]; for (var j = 0; j < mergedFreqData.length; j++) { var mergedVal = mergedFreqData[j][columnName]; if ( mergedVal === freqVal ) { ret.splice( j, 1, Ext.Object.merge( freqData[i], mergedFreqData[j] ) ); break; } } } return ret; }, createFreqData : function(variantsByLabel, labelName, columnName, bins, binsText) { var me = this; var data = variantsByLabel[labelName]; var freqData = null; var rawData = me.getColumnDataFromArray( data, columnName ); if ( rawData.length === 0 ) { console.log( "Could not extract '" + columnName + "' from data" ); return null; } var countColumnName = labelName; if ( bins !== null ) { freqData = me.calculateBinFrequencies( rawData, columnName, countColumnName, bins, binsText ); } else { freqData = me.calculateFrequencies( rawData, columnName, countColumnName ); } return freqData; }, isHistogramType : function(data) { return (!isNaN( Number( data[0] ) ) && Ext.Array.unique( data ).length >= 10); }, generateBinsLogTransform : function(data, logbase) { var start = 5; var bins = Array.apply( start, Array( this.N_BINS ) ).map( function(val, i) { return Math.pow( logbase, start + i ); } ); return bins; }, generateBins : function(data) { var binSize = this.N_BINS; var bins = Array( binSize ); data = data.sort( function(a, b) { return Number( a ) - Number( b ); } ); var unique = []; data.forEach( function(e) { if ( unique.indexOf( e ) == -1 && e !== undefined ) unique.push( Number( e ) ); } ); data = unique; var dataMid = data[Math.floor( (data.length - 1) / 2 )]; var binWidth = Math.ceil( (data[Math.floor( (data.length - 1) * 3 / 4 )] - dataMid) / binSize / 2 ); for (var i = 0; i < binSize; i++) { bins[i] = i - Math.floor( binSize / 2 ); } bins.forEach( function(e, i) { bins[i] = e * binWidth + dataMid; } ); if ( bins[0] < 0 ) { bins.forEach( function(e, i) { bins[i] = i * binWidth + Ext.Array.min( data ); } ); } // console.log("dataMid="+dataMid+"; binWidth="+binWidth+"; bins[0]=" + bins[0] + "; // bins[last]="+bins[bins.length-1]); return bins; }, createReport : function(store, columnName) { var me = this; var reportWindow = me.up( '#variantReportWindow' ); reportWindow.setLoading( true ); // get a list of variants grouped by Subject labels // var variantIds = this.getColumnDataFromStore( store, 'id' ); var variantIds = ASPIREdb.view.report.VariantReportWindow.getColumnDataFromStore( store, 'id' ); VariantService.groupVariantsBySubjectLabels( variantIds, { callback : function(variantsByLabel) { var mergedFreqData = []; var labelNames = []; // special case for histogram, gather all data and generate bins var allData = []; var bins = null; var binsText = null; var logbase = 2; Object.keys( variantsByLabel ).forEach( function(labelName) { var vals = me.getColumnDataFromArray( variantsByLabel[labelName], columnName ); allData = allData.concat( vals ); } ); if ( me.isHistogramType( allData ) ) { if ( !me.logTransform ) { bins = me.generateBins( allData ); } else { bins = me.generateBinsLogTransform( allData, logbase ); } binsText = me.bins2text( bins ); } for ( var labelName in variantsByLabel) { labelNames.push( labelName ); var freqData = me.createFreqData( variantsByLabel, labelName, columnName, bins, binsText ); if ( freqData === null ) { continue; } mergedFreqData = me.mergeFreqData( freqData, mergedFreqData, columnName ); } me.createLabelReport( mergedFreqData, columnName, labelNames ); reportWindow.setLoading( false ); }, errorHandler : function(message, exception) { Ext.Msg.alert( 'Error', message ); console.log( message ); console.log( dwr.util.toDescriptiveString( exception.stackTrace, 3 ) ); reportWindow.setLoading( false ); } } ); }, } ); const rectangleArea = (width, height) => width * height; const rectangle1 = [1, 2]; const rectangle2 = [3, 5]; const rectangle3 = [6, 9]; const rectangles = [rectangle1, rectangle2, rectangle3]; rectangles.forEach((rectangle) => { console.log(rectangleArea(...rectangle)); }); <reponame>ulgaal/react-reducer-table /* Copyright 2020 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react' import img from './ai-faces.jpg' import './SellerTip.css' const SellerTip = props => { const { seller: { name, username, email, phone, company, address: { street, suite, city, zipcode }, image } } = props const x = image % 15 const y = Math.floor(image / 15) return ( <div className='seller-tip'> <table> <tbody> <tr> <td className='seller-tip-key'>Name:</td> <td>{name}</td> <td rowSpan={5}> <svg className='seller-tip-image' title={name}> <image x={0} y={0} href={img} transform={`scale(1.6, 1.6) translate(-${x * 50}, -${y * 50})`} /> </svg> </td> </tr> <tr> <td className='seller-tip-key'>User Name:</td> <td>{username}</td> </tr> <tr> <td className='seller-tip-key'>Email:</td> <td>{email}</td> </tr> <tr> <td className='seller-tip-key'>Phone:</td> <td>{phone}</td> </tr> <tr> <td className='seller-tip-key'>Company:</td> <td>{company.name}</td> </tr> <tr> <td className='seller-tip-key'>Address:</td> <td colSpan={2}> {suite} <br /> {street} <br /> {zipcode} {city} </td> </tr> </tbody> </table> </div> ) } export const areEqual = (prev, next) => { const areEqual = prev.seller === next.seller /* if (!areEqual) { console.log('!SellerTip.areEqual') } */ return areEqual } export default React.memo(SellerTip, areEqual) <gh_stars>1-10 import {assert, assertEquals} from './lib/Testimony.js'; import Parse from './../src/Parse.js'; import lex from "./../src/lex.js"; import htmljs from "./../src/lex-htmljs.js"; /** * Convert an array of Token to an array of strings. * Also works with an array of arrays, to arbitrary depth, converting each Token to a string of its text property. * @param array {Token[]|Token[][]} * @returns {string[]|string[][]} */ function tokensToText(array) { let result = []; for (let i in array) if (Array.isArray(array[i])) result[i] = tokensToText(array[i]); else { result[i] = array[i].text; if (array[i].tokens) result[i] = Object.assign(result[i], {tokens: tokensToText(array[i].tokens)}); } return result; } Deno.test('Parse.singleVar', () => { let code = 'fruit'; let tokens = lex(htmljs, code, 'js'); let pathTokens = Parse.varExpressions_(tokens, ['fruit']); assertEquals(tokensToText(pathTokens), [['fruit']]); }); Deno.test('Parse.thisVars', () => { let code = 'this.one'; let tokens = lex(htmljs, code, 'js'); let pathTokens = Parse.varExpressions_(tokens); pathTokens = tokensToText(pathTokens); assertEquals(pathTokens, [['this', '.', 'one']]); }); Deno.test('Parse.multipleVars', () => { let code = 'this.one.two(); test["a"].b; test()'; let tokens = lex(htmljs, code, 'js'); let pathTokens = Parse.varExpressions_(tokens, ['test']); pathTokens = tokensToText(pathTokens); assertEquals(pathTokens, [ ['this', '.', 'one'], ['test', '[', '"a"', ']', '.', 'b'] ] ); }); Deno.test('Parse.duplicate', () => { let code = 'this.one.two; one.three'; let tokens = lex(htmljs, code, 'js'); let pathTokens = Parse.varExpressions_(tokens, ['one']); pathTokens = tokensToText(pathTokens); assertEquals(pathTokens, [ // Make sure we don't match the "one.two" within "this.one.two." ['this', '.', 'one', '.', 'two'], ['one', '.', 'three'] ] ); }); Deno.test('Parse.varExpressionToPath', () => { let code = 'this["fruit"][0].name'; let tokens = lex(htmljs, code, 'js'); let pathTokens = Parse.varExpressions_(tokens); let paths = pathTokens.map(Parse.varExpressionToPath_); assertEquals(paths, [['this', 'fruit', '0', 'name']]); }); Deno.test('Parse.varExpressionWithinParens', () => { let code = 'escapeHtml(sport[0].name)'; let tokens = lex(htmljs, code, 'js'); let pathTokens = Parse.varExpressions_(tokens, ['fruit', 'sport']); let paths = pathTokens.map(Parse.varExpressionToPath_); assertEquals(paths, [['sport', '0', 'name']]); }); Deno.test('Parse.findFunction.arrow1', () => { let code = 'b=3;a => a+1; b=4;'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunction(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a => a+1'); }); Deno.test('Parse.findFunction.arrow2', () => { let code = 'b=3;a => (a+1); b=4;'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunction(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a => (a+1)'); }); Deno.test('Parse.findFunction.arrow3', () => { let code = 'b=3;(a => a+1); b=4;'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunction(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a => a+1'); }); Deno.test('Parse.findFunction.arrow4', () => { let code = 'b=3;a => { return a+1 }; b=4;'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunction(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a => { return a+1 }'); }); Deno.test('Parse.findFunction.arrow5', () => { let code = 'b=3;a => { return {a:1} }; b=4;'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunction(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a => { return {a:1} }'); }); Deno.test('Parse.findFunction.arrow6', () => { let code = 'b=3;(a) => a+1;'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunction(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), '(a) => a+1'); }); Deno.test('Parse.findFunction.arrow7', () => { let code = '() => a+1;'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunction(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), '() => a+1'); }); Deno.test('Parse.findFunction.func', () => { let code = 'b=3;function(a) { return a+1 }; b=4;'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunction(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'function(a) { return a+1 }'); }); Deno.test('Parse.findFunctionArgs.arrow1', () => { let code = 'a => a+1'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunctionArgs(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a'); }); Deno.test('Parse.findFunctionArgs.arrow2', () => { let code = '(a) => (a+1)'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunctionArgs(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a'); }); Deno.test('Parse.findFunctionArgs.arrow3', () => { let code = '(a, b) => a+1'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunctionArgs(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a, b'); }); Deno.test('Parse.findFunctionArgs.arrow4', () => { let code = '(a=1) => { return a+1 }'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunctionArgs(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a=1'); }); Deno.test('Parse.findFunctionArgs.arrow5', () => { let code = '(a={}, b) => { return {a:1} }'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunctionArgs(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a={}, b'); }); Deno.test('Parse.findFunctionArgs.arrow6', () => { let code = '(a=x=> {return (x+1)},b) => { return {a:1} }'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunctionArgs(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a=x=> {return (x+1)},b'); }); Deno.test('Parse.findFunctionArgs.func', () => { let code = 'function(a) { return a+1 }'; let tokens = lex(htmljs, code, 'js'); let result = Parse.findFunctionArgs(tokens); assertEquals(tokensToText(tokens.slice(...result)).join(''), 'a'); });/*eslint max-nested-callbacks: 0*/ /*global describe, it*/ 'use strict'; var assert = require('assert'); var raven = require('raven'); describe('core/handlers/sentry-handler', function () { var Handler = require('../core/handlers/sentry-handler'); var layout = {}; function SpyHandler(l, params) { Handler.call(this, l, params); } SpyHandler.prototype = Object.create(Handler.prototype); SpyHandler.prototype._createClient = function (dsn, options) { return { dsn: dsn, options: options, captureError: function () {} }; }; function createHandler(params) { return new SpyHandler(layout, params); } describe('handler.client', function () { it('Should create raven client', function () { var handler = new Handler(layout, {}); assert.ok(handler.client instanceof raven.Client); }); it('Should create client', function () { var handler = createHandler({}); assert.ok(handler.client); }); it('Should call captureError()', function () { var handler = createHandler({}); var spy; var messageObj = new Error(); handler.client.captureError = function (message, options) { spy = { message: message, options: options }; }; handler.handle({ message: messageObj, level: 'DEBUG', bar: 'baz' }); assert.deepEqual(spy, { message: messageObj, options: { level: 'debug', extra: { level: 'DEBUG', bar: 'baz' } } }); }); it('Should call captureMessage()', function () { var handler = createHandler({}); var spy; var messageObj = 'foo'; handler.client.captureMessage = function (message, options) { spy = { message: message, options: options }; }; handler.handle({ message: messageObj, level: 'DEBUG', bar: 'baz' }); assert.deepEqual(spy, { message: messageObj, options: { level: 'debug', extra: { level: 'DEBUG', bar: 'baz' } } }); }); }); }); <reponame>GuillaumeLiard/gravidyne<gh_stars>0 export const state = function() { return { // bodies: [], bodies: [ { id: 1, type: 'Circle', initialGeometryPercent: { x: 0.5, y: 0.5, radius: 0.2, }, physic: { friction: 0.1, frictionAir: 0.001, restitution: 1, // isStatic: true, } }, { id: 2, type: 'Rectangle', initialGeometryPercent: { x: 0.5, y: 0, width: 1, height: 1 / 12, }, physic: { isStatic: true, restitution: 1 } }, { id: 3, type: 'Rectangle', initialGeometryPercent: { x: 0.5, y: 1, width: 1, height: 1 / 12, }, physic: { isStatic: true, } }, { id: 4, type: 'Rectangle', initialGeometryPercent: { x: 1, y: 0.5, width: 1 / 12, height: 2, }, physic: { isStatic: true, restitution: 1 } }, { id: 5, type: 'Rectangle', initialGeometryPercent: { x: 0, y: 0.5, width: 1 / 12, height: 1, }, physic: { isStatic: true, restitution: 1 } }, { id: 6, type: 'Rectangle', initialGeometryPercent: { x: 0.25, y: 1 / 6, width: 0.08, height: 0.1, }, physic: { frictionAir: 0.001 } }, // { // id: 7, // type: 'Rectangle', // initialGeometryPercent: { // x: 0.50, // y: 1 / 6, // width: 0.08, // height: 0.1, // }, // physic: { // frictionAir: 0.05 // } // }, // { // id: 8, // type: 'Rectangle', // initialGeometryPercent: { // x: 0.75, // y: 1 / 6, // width: 0.08, // height: 0.1, // }, // physic: { // frictionAir: 0.1 // } // }, ] } } export const getters = { getBodies(state) { return state.bodies } } /* Copyright 2019 The Tekton 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. */ module.exports = api => { api.cache(true); return { presets: [ [ '@babel/preset-env', { corejs: '3', useBuiltIns: 'entry' } ], '@babel/preset-react' ], plugins: [ '@babel/plugin-proposal-class-properties', '@babel/plugin-proposal-export-default-from', '@babel/plugin-syntax-dynamic-import', '@babel/plugin-transform-runtime' ], env: { development: { sourceMaps: true, plugins: ['react-hot-loader/babel'] }, test: { presets: [ [ '@babel/preset-env', { targets: { node: 'current' } } ] ] } } }; }; <reponame>humeniukd/neokan import React from 'react'; import { StaticImage } from 'gatsby-plugin-image' import { FormattedMessage } from 'react-intl' export function Partners() { return ( <center> <h2><FormattedMessage id="partners" /></h2> <a title="Bernard Controls" href="http://www.bernardcontrols.com/ru/" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="Bernard Controls" src="../images/partners/bernard-controls.jpg" /> </a> <br/> <a title="Flowserve Corporation" href="http://www.flowserve.com/" target="_blank" rel="noreferrer"> <StaticImage src="http://www.flowserve.com//files/assets/fls2/images/logo.png" width="160" alt="Flowserve" /> </a> <br/> <a title="BIFFI" href="http://www.biffi.it" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="BIFFI" src="../images/partners/bifiLogo.gif" /> </a> <br/> <a title="AUMA MATIC" href="http://www.auma.com" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="AUMA MATIC" src="../images/partners/auma.gif" /> </a> <br/> <a title="REGADA" href="http://www.regada.sk" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="REGADA" src="../images/partners/regada.png" /> </a> <br/> <a title="Bettis" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="Bettis" src="../images/partners/Bettis.gif" /> </a> <br/> <a title="Emerson" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="Emerson" src="../images/partners/emersonlogo.gif" /> </a> <br/> <a title="Exlar" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="Exlar" src="../images/partners/exl_logo.jpg" /> </a> <br/> <a title="Armatury" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="Armatury" src="../images/partners/logo_armatury.gif" /> </a> <br/> <a title="Vacono" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="Vacono" src="../images/partners/vac_log.gif" /> </a> <br/> <a title="MSA" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="MSA" src="../images/partners/logomsa.gif" /> </a> <br/> <a title="DKG" target="_blank" rel="noreferrer"> <StaticImage width="160" alt="DKG" src="../images/partners/logodkg.gif" /> </a> <br/> <a title="Leser" target="_blank" rel="noreferrer"> <StaticImage width="160" height="20" alt="Leser" src="../images/partners/leserLogo.gif" /> </a> <br/> <a title="Rotork Homepage" href="http://www.rotork.com/en" target="_blank" rel="noreferrer"> <StaticImage width="160" height="50" alt="Rotork Logo" src="../images/partners/rotork.svg"/> </a> </center> ) } export default Partners; <reponame>vFujin/HearthLounge import {call, put, takeEvery} from 'redux-saga/effects'; import * as types from "./types"; import * as actions from "./actions"; import axios from "axios/index"; import {calendarKey, calendarId} from "../../../keys"; const fetchUpcomingTournaments = () => { const dateNow = new Date().toISOString(); const maxResults = 10; return axios.get(`https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events?maxResults=${maxResults}&orderBy=startTime&singleEvents=true&timeMin=${dateNow}&key=${calendarKey}`) .then(({data}) => ({tournaments: data})) .catch(error => ({error})); }; export function* fetchUpcomingTournamentsSaga() { const {tournaments, error} = yield call(fetchUpcomingTournaments); if(error){ yield put(actions.fetchUpcomingTournamentsFailure(error)); } else { yield put(actions.fetchUpcomingTournamentsSuccess(tournaments)); } } export function* watchUpcomingTournaments() { yield takeEvery(types.FETCH_UPCOMING_TOURNAMENTS_REQUEST, fetchUpcomingTournamentsSaga) }// register.js import { addons } from '@storybook/addons'; import * as FullStory from '@fullstory/browser'; addons.register('storybook/fullstory', () => { FullStory.init({ orgId: 'P6XKD', devMode: window.location.hostname !== 'ux.palmetto.com', }); });// 把小程序的websocket变成h5的使用方式 module.exports = class WebSocket { /** * @param uri {string} * @param protocols * @param opts * */ constructor (uri, protocols, opts) { this.binaryType = undefined this.supports = { binary: false } this.SocketTask = undefined this.onopen = this.onclose = this.onmessage = this.onerror = undefined wx.connectSocket({ url: uri, header: opts.headers, protocols: opts.protocols || [], perMessageDeflate: opts.perMessageDeflate, timeout: opts.timeout || 10000, // 好像是只有小程序支持 success: (d) => { this.SocketTask = d this.SocketTask.onOpen = (header, profile) => { this.onopen && this.onopen(header, profile) } this.SocketTask.onMessage = (data) => { this.onmessage && this.onmessage({data}) } this.SocketTask.onError = (errMsg) => { this.onerror && this.onerror({errMsg}) } this.SocketTask.onClose = (code, reason) => { this.onclose && this.onclose({code, reason}) } }, fail (res) { this.onerror && this.onerror({errMsg: 'wx.connectSocket失败', res}) } }) } send (data, opts) { if(this.SocketTask){ this.SocketTask.send({ data: data }) } } close () { if(this.SocketTask){ this.SocketTask.close() } } } import { createInjector, elem, getProp, finalizeAttributes, setAttribute, addClass } from '../../runtime'; export default function(host, scope) { const target = host.componentView; const elem1 = target.appendChild(elem('main')); const injector = scope.injector = createInjector(elem1); setAttribute(injector, 'a1', attrValue1(host)); elem1.setAttribute('a2', '0'); // TODO should set class attribute once, all `addClass()` calls should // only add/remove class names, not replace entire class attribute setAttribute(injector, 'class', 'foo'); ifAttr1(host, injector); ifAttr2(host, injector); ifAttr3(host, injector); addClass(injector, attrValue2(host)); finalizeAttributes(injector); return updateTemplate; } function updateTemplate(host, scope) { const { injector } = scope; setAttribute(injector, 'a1', attrValue1(host)); setAttribute(injector, 'class', 'foo'); ifAttr1(host, injector); ifAttr2(host, injector); ifAttr3(host, injector); addClass(injector, attrValue2(host)); finalizeAttributes(injector); } function ifAttr1(host, injector) { if (getProp(host, 'c1')) { setAttribute(injector, 'a2', '1'); } } function ifAttr2(host, injector) { if (getProp(host, 'c2')) { addClass(injector, 'foo bar'); } } function ifAttr3(host, injector) { if (getProp(host, 'c3')) { setAttribute(injector, 'class', attrValue3(host)); } } function attrValue1(host) { return getProp(host, 'id'); } function attrValue2(host) { return getProp(host, 'classAddon'); } function attrValue3(host) { return 'bam ' + getProp(host, 'id'); } <gh_stars>0 const config = require('config.json'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const db = require('_helpers/db'); const City = db.City; module.exports = { getAllCities, getCityById, getCityByState }; async function getAllCities() { return await City.find().select(any); } async function getCityById(id) { return await City.findById(id).select(any); } async function getCityByState(stateid) { return await City.findById(stateid).select(any); } <reponame>ManikumarGoud/faker.js<gh_stars>0 module["exports"] = [ "Fried Rice", "Manchurian", "Noodles", "Spicy Sichuan", "Sweet Cantonese", "Fishy Shandong", "Fujian", "Jiangsu", "Zhejiang", "Hot and Sour Sunan" ];const { Command } = require('reconlx'); module.exports = new Command({ name: 'blacklistuser', alias: [], description: 'blocks a user from using the bot', usage: 'PREFIX Command: blacklistuser <userID>', permissions: { client: [], user: [] }, cooldowns: { global: 0, user: 0 }, category: 'Owner-Only', slashCommand: false, prefixCommand: true, run: async (client, message) => { if (!message.args[0]) return; message.args = message.content.replace(/[<@>]/g, '').split(' '); if (message.args[0] == 'off') { const oldData = await client.db.get('blacklist'); const newData = oldData.filter(entry => entry != message.args[1]); await client.db.set('blacklist', newData); client.functions.reply(`The blacklist entry about ${message.args[1]} has been deleted.`, message); } else { await client.db.push('blacklist', message.args[0]); client.functions.reply(`${message.args[0]} has been blacklisted from using the bot.`, message); } } })<reponame>zakjan/luma.gl /** @typedef {import('../../types').ShaderPass} ShaderPass */ const fs = `\ uniform float amount; vec4 vibrance_filterColor(vec4 color) { float average = (color.r + color.g + color.b) / 3.0; float mx = max(color.r, max(color.g, color.b)); float amt = (mx - average) * (-amount * 3.0); color.rgb = mix(color.rgb, vec3(mx), amt); return color; } vec4 vibrance_filterColor(vec4 color, vec2 texSize, vec2 texCoord) { return vibrance_filterColor(color); } `; const uniforms = { amount: {value: 0, min: -1, max: 1} }; /** @type {ShaderPass} */ export const vibrance = { name: 'vibrance', uniforms, fs, passes: [{filter: true}] }; import List from './list'; import Edit from './edit'; export default { List, Edit }import React from 'react' import { useStaticQuery, graphql } from "gatsby" import {RiMailSendFill, RiPhoneLine, RiUserLocationLine} from 'react-icons/ri' import Layout from "../components/layout" import SEO from "../components/seo" import { Wrapper, Image, BottomEdgeDown, BottomEdgeUp} from "../pageStyles/pageStyles" import {COLORS} from '../constants' const ContactPage = () => { const { wpcontent: { page: { contactMeta: { contactAddress, contactCity, contactDescription, contactEmail, contactPhone, contactPostalCode, contactHeaderPicture } } } } = useStaticQuery(graphql` query { wpcontent { page(id: "contact", idType: URI) { contactMeta { contactAddress contactCity contactDescription contactEmail contactPhone contactPostalCode contactHeaderPicture { altText sourceUrl imageFile { childImageSharp { fluid(quality: 90) { ...GatsbyImageSharpFluid_withWebp } } } } } } } } `) return( <Layout> <SEO title="Contact"/> <Wrapper descriptionColor={COLORS.PRIMARY}> <div className="banner"> <Image fluid={contactHeaderPicture.imageFile.childImageSharp.fluid} alt={contactHeaderPicture.altText} /> <BottomEdgeUp color={COLORS.PRIMARY}/> </div> <div className="description"> <h2>Hit us up</h2> <p>{contactDescription}</p> <BottomEdgeDown color={COLORS.BLACK}/> </div> <div className="contact-info"> <div> <RiMailSendFill style={{height: "4rem", width: "4rem"}}/> <p>Email us at{" "} <a target="__blank" href={`mailto:${contactEmail}`}> {contactEmail} </a> </p> </div> <div> <RiPhoneLine style={{height: "4rem", width: "4rem"}}/> <p>Call us: {contactPhone}</p> </div> <div> <RiUserLocationLine style={{height: "4rem", width: "4rem"}}/> <p> {contactAddress}, {contactPostalCode}, {contactCity} </p> </div> </div> </Wrapper> </Layout> ) } export default ContactPage<reponame>adamsoffer/react-html5video const path = require('path'); const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const pkg = require('./../package.json'); const srcPath = path.resolve(__dirname, 'src'); const distPath = path.resolve(__dirname, 'dist'); module.exports = ({ optimize, extractCss, hot, publicPath = '/' }) => { const cssString = 'css?modules&importLoaders=1&localIdentName=[hash:base64:5]&-autoprefixer!postcss'; let config = { entry: [ path.resolve(srcPath, 'entry.js') ], output: { path: distPath, filename: '[name].js', publicPath: publicPath }, resolve: { extensions: ['.js', '.json', '.jsx', ''] }, module: { loaders: [{ test: /\.(js|jsx)$/, include: srcPath, loader: 'babel', query: { cacheDirectory: true } }, { test: /\.json$/, loader: 'json' }, { test: /\.css$/, include: srcPath, loader: extractCss ? ExtractTextPlugin.extract('style', cssString) : 'style!' + cssString }, { test: /\.css$/, include: [new RegExp(pkg.name + '/dist/'), new RegExp('reset-css')], loader: extractCss ? ExtractTextPlugin.extract('style', 'css') : 'style!css' }, { test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|svg|vtt)(\?.*)?$/, loader: 'file' }] }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve(srcPath, 'index.html') }), new CopyWebpackPlugin([{ context: 'assets/static', from: '**/*' }]), new CaseSensitivePathsPlugin() ] }; if (hot) { config.entry.unshift( 'webpack-hot-middleware/client', 'react-hot-loader/patch' ); config.plugins.unshift( new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ); } if (extractCss) { config.plugins.push(new ExtractTextPlugin('[name].css')); } if (optimize) { config.plugins.push(new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false }, output: { comments: false } })); } return config; }; // XXX The third-party react-native modules react-native-fetch-blob utilizes the // same HTTP library as react-native i.e. okhttp. Unfortunately, that means that // the versions of okhttp on which react-native and react-native-fetch-blob // depend may have incompatible APIs. Such an incompatibility will be made // apparent at compile time and the developer doing the compilation may choose // to not compile react-native-fetch-blob's source code. // XXX The choice between the use of react-native-img-cache could've been done // at runtime based on whether NativeModules.RNFetchBlob is defined if only // react-native-fetch-blob would've completely protected itself. At the time of // this writing its source code appears to be attempting to protect itself from // missing native binaries but that protection is incomplete and there's a // TypeError. import { Image } from 'react-native'; export { Image as CachedImage, undefined as ImageCache }; <filename>web/admin-addRandom.js $('#test_no').hide(); var uid; $.post('../api/cookie',function(retCoo) { if (retCoo.code == 8788) { window.location.href = "http://m.xmgc360.com/start/web/account/?page=acc_login" } else{ uid=retCoo.data.uid; console.log(uid) } }); //读取所有课程名称和编号,编号为value $.post('../api/ManageClass', function (res) { for (var i=0;i<res.length;i++) { $('#check').append("<option value='"+res[i].classNo+"'>"+res[i].className+"</option>"); } var checkClass,checkClassName,dat1,checkClass1; $('#check').change(function () { //选择课程后执行的函数 var options=$("#check option:selected"); //获取选中的项 checkClass = options.val(); checkClassName = options.text(); var dat={ checkClass:checkClass }; //查询选择的课程在题库中题目的数量 if(checkClass=='--请选择--'){ alert('请选择课程') } else{ $.post('../api/ManageCount',dat,function (res1) { if(res1[0]['count(*)']==0){ $('#classNumber').html('您选择的课程在题库中没有题目,不能进行抽取试题'); checkClass=''; checkClassName='' } else{ $('#classNumber').html('') $('#checkNum').html(' <option>--请选择--</option>'); for(var i=0;i<res1[0]['count(*)'];i++){ $('#checkNum').append("<option value='"+(i+1)+"'>"+(i+1)+"</option>"); } } }); checkClass1=''; } }); $('#checkNum').change(function () { // 选择题目数量后执行的函数 var options1=$("#checkNum option:selected"); //获取选中的项 checkClass1 = options1.val(); dat1={ checkClass1:checkClass1, //选中的题目数量 checkClass:checkClass //获选择的课程编号,课程名称checkClassName }; // console.log(dat1,checkClassName); }); $('#generate').click(function () { $('#paper').html(''); // console.log("dddddddddd",checkClass1,checkClass); if(checkClass1==''||checkClass==''){ alert('请选择课程和生成题目数量'); $('#total').hide(); } else if(checkClass1==undefined||checkClass==undefined){ alert('请选择课程和生成题目数量') $('#total').hide(); } else if(checkClass1=='--请选择--'||checkClass=='--请选择--'){ alert('请选择课程和生成题目数量') $('#total').hide(); } else{ $('#total').show(); $.post('../api/ManageRandom',dat1,function (paper) { for(var a=0;a<paper.length;a++){ var model=$('#topic').clone(true,true); model.find('#topicNum').html(a+1); model.find('#topicContent').html(paper[a]['testContent']); model.find('#test_no').html(paper[a]['testNo']); model.find('#topicA').html(paper[a]['optionA']); model.find('#topicB').html(paper[a]['optionB']); model.find('#topicC').html(paper[a]['optionC']); model.find('#topicD').html(paper[a]['optionD']); model.find('#answer').html(paper[a]['answer']); $('#paper').append(model); } // console.log("试卷",paper) }) } }); }); $.post('../api/family',function (res) { for (var i=0;i<res.length;i++){ /*$('#family').append('<option value="'+res[i]["familyNo"]+'">'+res[i]["familyName"]+'</option>');*/ $('#family2').append('<option value="'+res[i]["familyNo"]+'">'+res[i]["familyName"]+'</option>') } }) var paper_total = {}; //试卷内部 var array_subject = []; //所有题目数组 $('input').blur(function () { var inputData = $('#total input')[0].value; var re=/^\S{2,20}$/ var reg=inputData.match(re); if(reg==null) alert('试卷名称为2-20个非空白字符') else{ $('#createExam').click(function () { var time=$('#testTime option:selected').val(); var familyNo=$('#family2 option:selected').val(); var checkObj=$('#check option:selected').val(); var confirmRes=confirm('确定创建考试吗') if(confirmRes==true) { var textareaData = $('#total textarea'); var a=7; var num = (textareaData.length)/7; /* console.log(num); console.log("inputData",inputData.length); console.log("num",num);*/ var judgment=0; for(var j=1;j<=num;j++){ var newAA=[]; //每到题目数组 for(var i = a*(j-1);i <a*j ;i++){ // console.log(i); var dat = textareaData[i].innerHTML||textareaData[i].value; // console.log(dat); if(dat==''){ judgment+=1; console.log(textareaData[i],'请把必填选项填写完整') } else{ // console.log(a*(j-1),a*j); newAA.push(dat); // console.log(newAA) } } /* 分值判断NAN var str = newAA[j*7]; reg=/^[-+]?\d*$/; if(!reg.test(str)){ judgment+=1; console.log(judgment); } console.log(j*7,newAA[7]);*/ array_subject[j-1]=newAA } if(judgment!=0) alert('请把必填选项填写完整和正确'); var inputData = $('#total input')[0].value; var re=/^\S{2,20}$/ var reg=inputData.match(re); // console.log(reg) if(inputData==''){ alert('请输入试卷名称') } else if(reg==null){ alert('试卷名称为2-20个字符') } else{ paper_total.planName=inputData; paper_total.time=time; paper_total.classNo=checkObj; paper_total.bank=array_subject; paper_total.uid=uid; paper_total.familyNo=familyNo; console.log(paper_total) $.post('../api/randomTest',paper_total,function (res) { alert(res) window.location.href='adminManage.html' }) } } }); } }); module.exports = { extends: "iamnapo", }; import React from "react"; import PropTypes from "prop-types"; import { UserPropType } from "../../../types"; import "./NavbarUser.css"; export const NavbarUser = ({ user, notifications = 0 }) => { return ( <div className="navbar-user"> {notifications > 0 && <div className="navbar-user__badge"> {notifications} </div>} <img className="navbar-user__image" src={user.avatarUrl} alt={user.name} height="40px" width="40px" /> </div> ); }; NavbarUser.propTypes = { user: UserPropType, notifications: PropTypes.number }; <gh_stars>0 'use babel'; import WorklogView from './worklog-view'; import { CompositeDisposable } from 'atom'; export default { worklogView: null, modalPanel: null, subscriptions: null, activate(state) { this.worklogView = new WorklogView(state.worklogViewState); this.modalPanel = atom.workspace.addModalPanel({ item: this.worklogView.getElement(), visible: false }); // 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-text-editor', { 'worklog:toggle': () => this.toggle(), 'worklog:insert-date': () => this.insertDateTime(), }) ); }, deactivate() { this.modalPanel.destroy(); this.subscriptions.dispose(); this.worklogView.destroy(); }, serialize() { return { worklogViewState: this.worklogView.serialize() }; }, insertDateTime() { let editor; if (editor = atom.workspace.getActiveTextEditor()) { const dateStr = new Date().toLocaleString(); editor.insertText(dateStr.substring(0, dateStr.length - 3)); } }, toggle() { console.log('Worklog was toggled!'); return ( this.modalPanel.isVisible() ? this.modalPanel.hide() : this.modalPanel.show() ); } }; const config = { init: true, nav: true, dots: true, loop: false, items: 1, destroy: false, centered: false, swipes: true, adaptiveHeight: false, appendDots: false, appendNav: false, margins: 30, activeSlide: 0, classNames: { slider: { wrapper: 'slippery__wrapper', item: 'slippery__item', active: 'slippery__item--active', prev: 'slippery__item--prev', }, nav: { block: 'slippery__nav', item: 'slippery__nav-button', prev: 'slippery__nav-button--prev', next: 'slippery__nav-button--next', disabled: 'slippery__nav-button--disabled', }, dots: { block: 'slippery__dots', item: 'slippery__dots-item', active: 'slippery__dots-item--active', }, }, transition: { type: 'linear', delay: 0, duration: 750, }, callbacks: { dotContent: function() {}, navContent: function(prev, next) { prev.innerText = '‹'; next.innerText = '›'; }, beforeMove: function() {}, afterMove: function() {}, onResize: function() {}, onSwipe: function() {}, beforeInit: function() {}, afterInit: function() {}, }, }; export default config; import { formatDateForUser, formatDateForMySql } from '../dateFormatter'; it('Date formatter works for getting it into the proper date', () => { let dateString = '09/13/1999 5:36 PM'; let result = formatDateForUser(dateString); expect(result).toEqual('9/13/1999, 5:36 PM'); }); it('Date formatter works for getting it into the proper date', () => { let dateString = ''; let result = formatDateForUser(dateString); expect(result).toEqual('unspecified'); }); it('Formats the date for sending to SQL', () => { let dateString = '09/13/1999 5:36 PM'; let result = formatDateForMySql(dateString); expect(result).toEqual('1999-09-13 17:36:00'); }); --- --- {% include_relative _javascript/tracking.js %} {% include_relative _javascript/vendor/lazyload.js %}import { useEffect, useState } from 'react' import { usePrefersReducedMotion } from 'hooks' function useParallax(multiplier, clamp = true) { const [offset, setOffset] = useState(0) const prefersReducedMotion = usePrefersReducedMotion() useEffect(() => { let ticking = false let animationFrame = null const animate = () => { const { innerHeight } = window const offsetValue = Math.max(0, window.scrollY) * multiplier const clampedOffsetValue = Math.max( -innerHeight, Math.min(innerHeight, offsetValue) ) setOffset(clamp ? clampedOffsetValue : offsetValue) ticking = false } const handleScroll = () => { if (!ticking) { ticking = true animationFrame = requestAnimationFrame(animate) } } if (!prefersReducedMotion) { window.addEventListener('scroll', handleScroll) } return () => { window.removeEventListener('scroll', handleScroll) cancelAnimationFrame(animationFrame) } }, [clamp, multiplier, prefersReducedMotion]) return offset } export default useParallax const config = require('config'); const DEBUG = config.get('DEBUG'); const errorHandleMiddleware = function (error, req, res, next) { const responseError = { statusCode: error.statusCode, message: error.message }; if (DEBUG) { if (error.statusCode >= 500) { responseError.stackTrace = error.stack; } responseError.initError = error.initError; } res.status(error.statusCode || 500); res.send(responseError); }; module.exports = errorHandleMiddleware; <filename>src/util/cloneNodes.js<gh_stars>1-10 import _ from 'lodash' export default function cloneNodes(nodes) { return _.map(nodes, (node) => node.clone()) } var Formulas = (function(){ var iva = 0.18; return { calcularIva: function(monto) { var subTotal = Formulas.calcularMontoSinIva(monto); return monto - subTotal; }, calcularMontoSinIva: function(monto){ return monto / (1 + iva); }, calcularUtilidad: function(costo, ingreso) { return ingreso - costo; }, calcularMargenUtilidad: function(costo, ingreso) { return ((ingreso - costo) / costo) * 100; }, calcularTasaEfectivaAnual: function(capital, interes, periodos) { return capital * Math.pow(1 + interes, 2); } }; })();import { derived } from 'svelte/store'; import dataStore from './dataStore'; import covidEstimator from '../../../src/estimator'; const resultStore = derived([dataStore], ([$ds], set) => { const result = covidEstimator($ds); set(result); return () => { dataStore.reset(); }; }); export default resultStore; $(document).ready(function () { $('.img-click-change').on('click', function () { var imgUrl = $(this).data('imgUrl'); $('#imageZoom').prop('src', this.src); }); var zoomImage = $('#imageZoom'); zoomImage.imageZoom(); var emotionsArray = ['angry','disappointed','meh', 'happy', 'smile']; $("#element").emotionsRating({ emotionSize: 20, bgEmotion: 'smile', emotions: emotionsArray, color: 'gold' }); }); var searchData= [ ['detach_0',['detach',['../class_ground_mission_control.html#ae5ffb37c3e088247b939ccc6d6239ecb',1,'GroundMissionControl']]], ['dragon_1',['Dragon',['../class_dragon.html#a79b87e0d47c37113663005bd6d3ec06e',1,'Dragon']]] ]; <gh_stars>0 module.exports = 'shared/baz.js'; <reponame>powerpool-finance/powerindex-routers const { ether: rEther } = require('@openzeppelin/test-helpers'); const TruffleContract = require('@nomiclabs/truffle-contract'); const template = artifacts.require('PowerIndexRouter'); const { promisify } = require('util'); const { assert } = require('chai'); const { web3 } = template; const { toBN } = web3.utils; const BigNumber = require('bignumber.js'); const fs = require('fs'); const AdminUpgradeabilityProxyArtifact = require('@openzeppelin/upgrades-core/artifacts/AdminUpgradeabilityProxy.json'); const ProxyAdminArtifact = require('@openzeppelin/upgrades-core/artifacts/ProxyAdmin.json'); const AdminUpgradeabilityProxy = TruffleContract(AdminUpgradeabilityProxyArtifact); const ProxyAdmin = TruffleContract(ProxyAdminArtifact); AdminUpgradeabilityProxy.setProvider(template.currentProvider); AdminUpgradeabilityProxy.defaults(template.class_defaults); ProxyAdmin.setProvider(template.currentProvider); ProxyAdmin.defaults(template.class_defaults); let proxyAdmin; const getCounter = ( n => () => n++ )(1); /** * Rewinds ganache by n blocks * @param {number} n * @returns {Promise<void>} */ async function advanceBlocks(n) { // eslint-disable-next-line no-undef const send = promisify(web3.currentProvider.send).bind(web3.currentProvider); const requests = []; for (let i = 0; i < n; i++) { requests.push( send({ jsonrpc: '2.0', method: 'evm_mine', id: `${new Date().getTime()}-${Math.random()}`, }), ); } await Promise.all(requests); } /** * Deploys a proxied contract * * @param contract Truffle Contract * @param {string[]} constructorArgs * @param {string[]} initializerArgs * @param {object} opts * @param {string} opts.deployer * @param {string} opts.initializer * @param {string} opts.proxyAdminOwner * @returns {Promise<any>} */ async function deployProxied(contract, constructorArgs = [], initializerArgs = [], opts = {}) { const impl = opts.implementation ? await contract.at(opts.implementation) : await contract.new(...constructorArgs); const adminContract = opts.proxyAdmin ? await ProxyAdmin.at(opts.proxyAdmin) : await createOrGetProxyAdmin(opts.proxyAdminOwner); const data = getInitializerData(impl, initializerArgs, opts.initializer); const proxy = await AdminUpgradeabilityProxy.new(impl.address, adminContract.address, data); const instance = await contract.at(proxy.address); instance.proxy = proxy; instance.initialImplementation = impl; instance.adminContract = adminContract; return instance; } /** * Creates and returns ProxyAdmin contract * @param {string} proxyOwner * @returns {Promise<TruffleContract>} */ async function createOrGetProxyAdmin(proxyOwner) { if (!proxyAdmin) { proxyAdmin = await ProxyAdmin.new(); await proxyAdmin.transferOwnership(proxyOwner); } return proxyAdmin; } function getInitializerData(impl, args, initializer) { const allowNoInitialization = initializer === undefined && args.length === 0; initializer = initializer || 'initialize'; if (initializer in impl.contract.methods) { return impl.contract.methods[initializer](...args).encodeABI(); } else if (allowNoInitialization) { return '0x'; } else { throw new Error(`Contract ${impl.name} does not have a function \`${initializer}\``); } } async function ethUsed(web3, receipt) { const tx = await web3.eth.getTransaction(receipt.transactionHash); return fromEther( new BigNumber(receipt.gasUsed.toString()).multipliedBy(new BigNumber(tx.gasPrice.toString())).toString(), ); } /** * Fetches logs of a given contract for a given tx, * since Truffle provides logs for a calle contract only. * @param {TruffleContract} contract * @param {object} receipt * @param {string} receipt.tx * @returns {Promise<{object}>} */ async function fetchLogs(contract, receipt) { const res = await web3.eth.getTransactionReceipt(receipt.tx); return contract.decodeLogs(res.logs); } async function expectExactRevert(promise, expectedMsg) { try { await promise; } catch (error) { const coverageTailoredError = `Returned error: VM Exception while processing transaction: revert ${expectedMsg}`; if (error.message !== expectedMsg && error.message !== coverageTailoredError) { assert.equal( error.message, `VM Exception while processing transaction: reverted with reason string '${expectedMsg}'`, 'Wrong kind of exception received', ); } return; } assert.fail('Expected an exception but none was received'); } /** * Creates a truffle contract from bytecode and abi * @param {string} name of the contract along with path * @param {[{substr: regex, newSubstr: string}]} bytecodeReplacements the list of bytecode replacements * @returns {TruffleContract} */ function artifactFromBytecode(name, bytecodeReplacements = []) { const data = require(`../../assets/${name}.json`); for (let i = 0; i < bytecodeReplacements.length; i++) { data.bytecode = data.bytecode.replace(bytecodeReplacements[i].substr, bytecodeReplacements[i].newSubstr); } const contract = TruffleContract(data); contract.setProvider(web3.currentProvider); contract.defaults(template.class_defaults); contract.numberFormat = 'String'; return contract; } function toEvmBytes32(bytes32) { return web3.utils.padRight(bytes32, 64); } /** * Splits a payload into a signature and calldata. * @param {string} payload * @returns Object */ function splitPayload(payload) { return { signature: payload.substring(0, 10), calldata: `0x${payload.substring(10)}`, }; } function ether(value) { return rEther(value.toString()).toString(10); } function fromEther(value) { return parseFloat(web3.utils.fromWei(value.toString(), 'ether')); } function gwei(value) { return web3.utils.toWei(value.toString(), 'gwei').toString(); } function fromGwei(value) { return web3.utils.fromWei(value.toString(), 'gwei').toString(); } function mwei(value) { return web3.utils.toWei(value.toString(), 'mwei').toString(10); } function fromMwei(value) { return web3.utils.fromWei(value.toString(), 'mwei').toString(); } async function getResTimestamp(res) { return (await web3.eth.getBlock(res.receipt.blockNumber)).timestamp.toString(); } async function deployAndSaveArgs(Contract, args) { const newInstance = await Contract.new.apply(Contract, args); fs.writeFileSync(`./tmp/${newInstance.address}-args.js`, `module.exports = ${JSON.stringify(args, null, 2)}`); return newInstance; } async function impersonateAccount(ethers, adminAddress) { await ethers.provider.getSigner().sendTransaction({ to: adminAddress, value: '0x' + new BigNumber(ether('1')).toString(16), }); await ethers.provider.send('hardhat_impersonateAccount', [adminAddress]); } async function forkContractUpgrade(ethers, adminAddress, proxyAdminAddress, proxyAddress, implAddress) { const iface = new ethers.utils.Interface(['function upgrade(address proxy, address impl)']); await impersonateAccount(ethers, adminAddress); await ethers.provider.getSigner(adminAddress).sendTransaction({ to: proxyAdminAddress, data: iface.encodeFunctionData('upgrade', [proxyAddress, implAddress]), }); } const { BN } = web3.utils; const increaseTime = buildEndpoint('evm_increaseTime'); async function latestBlockTimestamp() { const block = await web3.eth.getBlock('latest'); return block.timestamp; } async function latestBlockNumber() { const block = await web3.eth.getBlock('latest'); return block.number; } async function latestBlock() { return await web3.eth.getBlock('latest'); } async function increaseTimeTo(target) { if (!BN.isBN(target)) { target = new BN(target); } const now = new BN(await latestBlockTimestamp()); if (target.lt(now)) throw Error(`Cannot increase current time (${now}) to a moment in the past (${target})`); const diff = target.sub(now); return increaseTime(diff.toNumber()); } function buildEndpoint(endpoint) { return async function (...args) { return new Promise((resolve, reject) => { web3.currentProvider.send( { jsonrpc: '2.0', method: endpoint, params: args, id: getCounter(), }, async (err, res) => { if (err) { return reject(err); } if (res.error && res.error.message && res.error.message.length > 0) { let err = new Error(`'${endpoint}' call failed`); err.stack = res.error.data.stack; err.name = res.error.data.name; return reject(err); } return resolve(res.result); }, ); }); }; } async function forkReplacePoolTokenWithNewPiToken( artifacts, ethers, controller, tokenAddress, factoryAddress, routerArgs, admin, type = 'aave', ) { const MockERC20 = await artifacts.require('MockERC20'); const { web3 } = MockERC20; const token = await MockERC20.at(tokenAddress); const PowerIndexPool = await artifacts.require('PowerIndexPool'); const PowerIndexPoolController = await artifacts.require('PowerIndexPoolController'); const WrappedPiErc20 = await artifacts.require('WrappedPiErc20'); console.log('type', type); const PowerIndexRouter = await artifacts.require( type === 'aave' ? 'AavePowerIndexRouter' : 'contracts/powerindex-router/implementations/SushiPowerIndexRouter.sol:SushiPowerIndexRouter', ); const pool = await PowerIndexPool.at(await callContract(controller, 'pool')); console.log('pool getBalance before', await callContract(pool, 'getBalance', [token.address])); const [account] = await web3.eth.getAccounts(); await web3.eth.sendTransaction({ from: account, to: admin, value: ether(10), }); // await pool.setController(controller.address, {from: admin}); const balanceBefore = fromEther(await web3.eth.getBalance(admin)); console.log( 'await callContract(pool, "getDenormalizedWeight", [token])', await callContract(pool, 'getDenormalizedWeight', [tokenAddress]), ); const data = controller.contract.methods .replacePoolTokenWithNewPiToken(tokenAddress, factoryAddress, routerArgs, 'Power Index Sushi', 'piSushi') .encodeABI(); const options = { from: admin, to: controller.address, data }; const gas = await web3.eth.estimateGas(options); const gasLimit = gas * 1.2; console.log('gasLimit', gasLimit); console.log('data', data); const txRes = await web3.eth.sendTransaction({ gasLimit, ...options }); const receipt = await web3.eth.getTransactionReceipt(txRes.transactionHash); const logs = PowerIndexPoolController.decodeLogs(receipt.logs); const balanceAfter = fromEther(await web3.eth.getBalance(admin)); console.log('replacePoolTokenWithNewPiToken ETH spent', balanceBefore - balanceAfter); const wrappedTokenAddress = logs.filter(l => l.event === 'CreatePiToken')[0].args.piToken; const wrappedToken = await WrappedPiErc20.at(wrappedTokenAddress); console.log('wrappedToken symbol', await callContract(wrappedToken, 'symbol')); console.log('wrappedToken name', await callContract(wrappedToken, 'name')); const router = await PowerIndexRouter.at(await callContract(wrappedToken, 'router', [])); await increaseTime(60); if (controller.finishReplace) { await controller.finishReplace(); } console.log('await callContract(pool, "isBound", [token])', await callContract(pool, 'isBound', [tokenAddress])); console.log( 'await callContract(pool, "isBound", [wrappedTokenAddress])', await callContract(pool, 'isBound', [wrappedTokenAddress]), ); console.log( 'await callContract(pool, "getDenormalizedWeight", [wrappedTokenAddress])', await callContract(pool, 'getDenormalizedWeight', [wrappedTokenAddress]), ); return { token, wrappedToken, router, }; } function callContract(contract, method, args = []) { // console.log(method, args); return contract.contract.methods[method].apply(contract.contract, args).call(); } function isBnGreater(bn1, bn2) { return toBN(bn1.toString(10)).gt(toBN(bn2.toString(10))); } function mulScalarBN(bn1, bn2) { return toBN(bn1.toString(10)) .mul(toBN(bn2.toString(10))) .div(toBN(ether('1').toString(10))) .toString(10); } function divScalarBN(bn1, bn2) { return toBN(bn1.toString(10)) .mul(toBN(ether('1').toString(10))) .div(toBN(bn2.toString(10))) .toString(10); } function mulBN(bn1, bn2) { return toBN(bn1.toString(10)) .mul(toBN(bn2.toString(10))) .toString(10); } function divBN(bn1, bn2) { return toBN(bn1.toString(10)) .div(toBN(bn2.toString(10))) .toString(10); } function subBN(bn1, bn2) { return toBN(bn1.toString(10)) .sub(toBN(bn2.toString(10))) .toString(10); } function addBN(bn1, bn2) { return toBN(bn1.toString(10)) .add(toBN(bn2.toString(10))) .toString(10); } function assertEqualWithAccuracy(bn1, bn2, accuracyPercentWei = '100000000') { bn1 = toBN(bn1.toString(10)); bn2 = toBN(bn2.toString(10)); const bn1GreaterThenBn2 = bn1.gt(bn2); let diff = bn1GreaterThenBn2 ? bn1.sub(bn2) : bn2.sub(bn1); if (diff.toString() === '0') { return; } let diffPercent = divScalarBN(diff, bn1); const lowerThenAccurancy = toBN(diffPercent).lte(toBN(accuracyPercentWei)); assert.equal(lowerThenAccurancy, true, 'diffPercent is ' + web3.utils.fromWei(diffPercent, 'ether')); } async function newCompContract(contract, ...args) { const instance = await contract.new(...args); attachToInstance(instance); return instance; } async function attachCompContract(contract, address) { const instance = await contract.at(address); attachToInstance(instance); return instance; } function attachToInstance(instance) { for (let methodName of Object.keys(instance)) { if (!instance.contract.methods[methodName]) { continue; } const method = instance[methodName]; instance[methodName] = async function (...args) { const res = await method(...args); if (typeof res === 'object' && 'logs' in res) { for (let log of res.logs) { if (log.event === 'Failure') { throw new Error(`Comp error: ${log.args.error} info: ${log.args.info}`); } } } return res; }; } } async function getTimestamp(shift = 0) { const currentTimestamp = (await web3.eth.getBlock(await web3.eth.getBlockNumber())).timestamp; return currentTimestamp + shift; } function isBNHigher(bn1, bn2) { return toBN(bn1.toString(10)).gt(toBN(bn2.toString(10))); } const zeroAddress = '0x0000000000000000000000000000000000000000'; module.exports = { deployProxied, createOrGetProxyAdmin, artifactFromBytecode, toEvmBytes32, advanceBlocks, latestBlock, latestBlockNumber, latestBlockTimestamp, splitPayload, fetchLogs, ether, fromEther, ethUsed, gwei, fromGwei, mwei, fromMwei, expectExactRevert, getResTimestamp, forkContractUpgrade, deployAndSaveArgs, increaseTime, increaseTimeTo, evmSetNextBlockTimestamp: buildEndpoint('evm_setNextBlockTimestamp'), impersonateAccount, callContract, forkReplacePoolTokenWithNewPiToken, isBnGreater, mulScalarBN, divScalarBN, mulBN, divBN, subBN, addBN, assertEqualWithAccuracy, newCompContract, attachCompContract, getTimestamp, isBNHigher, zeroAddress, }; import React from "react" import Hero from "./Hero" import PartnersSection from "./PartnersSection" import SuccessStory from "./SuccessStory" import HomePageEvents from "./HomePageEvents" import AboutSection from "./AboutSection" const Index = ({ lang, location }) => { return ( <div> <Hero /> <AboutSection lang={lang} /> <SuccessStory lang={lang} /> <HomePageEvents lang={lang} /> <PartnersSection partnerTitle={lang === "ar" ? "شركاؤنا:" : "Our partners:"} /> </div> ) } export default Index <reponame>ensbot/ensbot-PortalNetwork-bns-sdk<filename>lib/helper/ins/resolver.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _axios = require("axios"); var _axios2 = _interopRequireDefault(_axios); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var bodyTemplate = { "jsonrpc": "2.0", "method": "icx_call" }; var Resolver = function () { // Provider URL function Resolver(endpoint, resolverAddr, walletAddr) { _classCallCheck(this, Resolver); this.endpoint = endpoint; this.resolverAddr = resolverAddr; this.walletAddr = walletAddr; this.id = 0; } _createClass(Resolver, [{ key: "addr", value: async function addr(node) { try { var body = Object.assign({}, bodyTemplate); body["id"] = this.id; body["params"] = { "from": this.walletAddr, "to": this.resolverAddr, "dataType": "call", "data": { "method": "addr", "params": { "node": node } } }; var response = await _axios2.default.post(this.endpoint, body); var result = response.data.result; return result; } catch (err) { console.log("address: ", err); throw err; } } }, { key: "multihash", value: async function multihash(node, key) { try { var body = Object.assign({}, bodyTemplate); body["id"] = this.id; body["params"] = { "from": this.walletAddr, "to": this.resolverAddr, "dataType": "call", "data": { "method": "multihash", "params": { "node": node, "name": key } } }; var response = await _axios2.default.post(this.endpoint, body); var result = response.data.result; return result; } catch (err) { console.log("owner: ", err); throw err; } } }]); return Resolver; }(); exports.default = Resolver;<filename>CelsToFahr.js function convertToF(celsius) { let fahrenheit = celsius * (9 / 5) + 32; return fahrenheit; } console.log(convertToF(37));import React from 'react' import { MemoryRouter } from 'react-router-dom' import reduxThunk from 'redux-thunk' import { expect } from 'chai' import { shallow } from 'enzyme' import td from 'testdouble' import configureMockStore from 'redux-mock-store' import merge from 'lodash/merge' import RoutineForm from 'components/RoutineForm' describe('CONTAINER: EditRoutineForm', () => { let EditRoutineForm const getMockStore = configureMockStore([reduxThunk]) const createInstance = (passedProps, passedInitialState) => { const initialState = passedInitialState || { routines: [] } const mockStore = getMockStore(initialState) const requiredProps = { store: mockStore, history: { push: () => {} }, match: { params: { id: 'xyz', }, }, } const finalProps = passedProps ? merge({}, requiredProps, passedProps) : requiredProps return shallow( <MemoryRouter> <EditRoutineForm {...finalProps} /> </MemoryRouter> ) .find(EditRoutineForm) } beforeEach(() => { EditRoutineForm = require('./EditRoutineForm').default }) afterEach(() => { td.reset() }) it('should render <RoutineForm /> inside the HOC', () => { const wrapper = createInstance() expect(wrapper.dive()).to.match(RoutineForm) }) describe('the rendered <RoutineForm />', () => { context('when route id matches a routine in state', () => { it('should pass the data of matched routine as initialValues prop to its wrapped component', () => { const mockRoutine = { id: '123', restOfRoutineData: 'restOfRoutineData', } const initialState = { routines: [mockRoutine], } const wrapper = createInstance({ store: getMockStore(initialState), match: { params: { id: mockRoutine.id, }, }, }) const wrappedComponent = wrapper.dive() expect(wrappedComponent).to.have.prop('initialValues', mockRoutine) }) it('should receive a handleSubmit() prop', () => { const wrappedComponent = createInstance().dive() expect(wrappedComponent.prop('handleSubmit')).to.be.a('function') }) describe('the passed handleSubmit() prop', () => { it('should dispatch the action created by calling editRoutine() with handleSubmit()\'s argument', () => { const initialState = { routines: [] } const mockStore = getMockStore(initialState) const dispatch = td.replace(mockStore, 'dispatch') const editRoutineArg = 'editRoutineArg' const editRoutineRes = 'editRoutineRes' const editRoutine = td.function() td.replace('duck/actions', { editRoutine }) td.when(editRoutine(editRoutineArg)).thenReturn(editRoutineRes) EditRoutineForm = require('./EditRoutineForm').default const wrapper = createInstance({ store: mockStore }) const wrappedComponent = wrapper.dive() td.verify(dispatch(), { times: 0, ignoreExtraArgs: true }) wrappedComponent.prop('handleSubmit')(editRoutineArg) td.verify(dispatch(editRoutineRes), { times: 1 }) }) it('should redirect to path \'/\' after calling the dispatch', () => { const push = td.function() const idThatShouldMatch = '123' const initialState = { routines: [{ id: idThatShouldMatch }], } const wrapper = createInstance( { history: { push } }, initialState, ) const wrappedComponent = wrapper.dive() const handleSubmitArg = { id: idThatShouldMatch } td.verify(push(), { times: 0, ignoreExtraArgs: true }) wrappedComponent.prop('handleSubmit')(handleSubmitArg) td.verify(push('/'), { times: 1 }) }) }) it('should receive a handleDelete() prop', () => { const wrappedComponent = createInstance().dive() expect(wrappedComponent.prop('handleDelete')).to.be.a('function') }) describe('the passed handleDelete() prop', () => { it('should dispatch the action created by calling deleteRoutine() with handleDelete()\'s argument', () => { const initialState = { routines: [] } const mockStore = getMockStore(initialState) const dispatch = td.replace(mockStore, 'dispatch') const deleteRoutineArg = 'deleteRoutineArg' const deleteRoutineRes = 'deleteRoutineRes' const deleteRoutine = td.function() td.replace('duck/actions', { deleteRoutine }) td.when(deleteRoutine(deleteRoutineArg)).thenReturn(deleteRoutineRes) EditRoutineForm = require('./EditRoutineForm').default const wrapper = createInstance({ store: mockStore, }) const wrappedComponent = wrapper.dive() td.verify(dispatch(), { times: 0, ignoreExtraArgs: true }) wrappedComponent.prop('handleDelete')(deleteRoutineArg) td.verify(dispatch(deleteRoutineRes), { times: 1 }) }) it('should redirect to path \'/\' after calling the dispatch', () => { const push = td.function() const wrapper = createInstance({ history: { push }, }) const wrappedComponent = wrapper.dive() td.verify(push(), { times: 0, ignoreExtraArgs: true }) wrappedComponent.prop('handleDelete')() td.verify(push('/'), { times: 1 }) }) }) }) context('when route id does not match any routine', () => { it('should receive true as notFound prop', () => { const initialState = { routines: [], } const wrapper = createInstance({ store: getMockStore(initialState), match: { params: { id: '123', }, }, }) const wrappedComponent = wrapper.dive() expect(wrappedComponent).to.have.prop('notFound', true) }) }) }) }) <filename>src/pages/404.js import React from 'react'; import Layout from '../components/layout/Layout'; export default () => ( <Layout> <section className="section-hero"> <h1>Oh no, page not found!</h1> </section> </Layout> ); $(function() { // RateItの設定 ...(2) $("#rateit").rateit(); }); // 評価値を確定した時 $("#rateit").on("rated", function(){ var evaluation = parseFloat($("#rateit").rateit("value")); var rid = $("#reviewid-text").text(); // csrfトークンを設定 $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url: '/ajax/rateit', type: 'POST', dataType: 'text', data : { review_id : rid, review_eval : evaluation } }).done(function(data){ /* 通信成功時 */ alert('評価を反映しました'); $("#reteit-value").text("☆"+evaluation.toFixed(1)); }).fail(function(data){ /* 通信失敗時 */ alert('評価を反映できませんでした'); //console.log("XMLHttpRequest : " + XMLHttpRequest.status); //console.log("textStatus : " + textStatus); //console.log("errorThrown : " + errorThrown.message); }); }); // 評価値を確定する直前 $("#rateit").on("beforerated", function(event, value){ //$("#msg3").text("event: beforerated, value= " + value); // confirmでキャンセルした時にはイベントをなかったことに if (!confirm("評価を"+ value + "に変更します。よろしいですか?")) { event.preventDefault(); } }); var webpack = require('webpack'); var release = true; var settings = require('./config/settings.js'); var webpackConfig = require('./config/webpack.config.js')(release); module.exports = webpackConfig;<filename>src/components/common/permission-context/withPermission.js import React from 'react'; import { wrapDisplayName, setDisplayName, compose } from 'recompose'; import { withRouter } from 'react-router-dom'; import usePermission from '../../../hooks/usePermission'; const withPermissionProps = Component => { const hoc = setDisplayName(wrapDisplayName(Component, 'withPermission')); return hoc(props => { const [permissionFetched, fetchPermission, canView] = usePermission(); return ( <Component {...props} permissionFetched={permissionFetched} fetchPermission={fetchPermission} canView={canView} /> ); }); }; const withPermission = compose( withRouter, withPermissionProps, ); export default withPermission; <reponame>wilebeast/FireFox-OS<gh_stars>1-10 /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ // Bug 557943 - Searching for addons can result in wrong results var gManagerWindow; var gProvider; function test() { waitForExplicitFinish(); gProvider = new MockProvider(); gProvider.createAddons([{ id: "<EMAIL>", name: "Microsoft .NET Framework Assistant", description: "", version: "6.66" }, { id: "<EMAIL>", name: "AwesomeNet Addon", description: "" }, { id: "<EMAIL>", name: "Dictionnaire MySpell en Francais (réforme 1990)", description: "" }]); open_manager("addons://list/extension", function(aWindow) { gManagerWindow = aWindow; run_next_test(); }); } function end_test() { close_manager(gManagerWindow, function() { finish(); }); } function perform_search(aQuery, aCallback) { waitForFocus(function() { var searchBox = gManagerWindow.document.getElementById("header-search"); searchBox.value = aQuery; EventUtils.synthesizeMouseAtCenter(searchBox, { }, gManagerWindow); EventUtils.synthesizeKey("VK_RETURN", { }, gManagerWindow); wait_for_view_load(gManagerWindow, function() { var list = gManagerWindow.document.getElementById("search-list"); var rows = list.getElementsByTagName("richlistitem"); aCallback(rows); }); }, gManagerWindow); } add_test(function() { perform_search(".net", function(aRows) { is(aRows.length, 1, "Should only get one result"); is(aRows[0].mAddon.id, "<EMAIL>", "Should get expected addon as only result"); run_next_test(); }); }); add_test(function() { perform_search("réf", function(aRows) { is(aRows.length, 1, "Should only get one result"); is(aRows[0].mAddon.id, "<EMAIL>", "Should get expected addon as only result"); run_next_test(); }); }); add_test(function() { perform_search("javascript:void()", function(aRows) { is(aRows.length, 0, "Should not get any results"); run_next_test(); }); }); 'use strict'; const {SERVER_ERRORS} = require('../constants'); class ApplicationError extends Error { constructor(message = 'Application error', code = SERVER_ERRORS.GENERIC, payload = undefined) { super(); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; this.code = code; this.payload = payload; } } module.exports = ApplicationError; function resizeHeight() { } function initResizable() { } import { queue } from "./queue/" import { dominator } from "./dominator/" import { manager } from "./manager/" const Operator = { dominator, queue, manager } Operator.start = function () { Operator.dominator.initialize(); } export { Operator } 'use strict'; var crypto = require('crypto'); var assert = require('assert'); var request = require('request'); var Utils = require('../services/utils'); var CustomersConfigProvider = require('../services/customers-config-provider'); module.exports = function (app) { var bodyParser = require('body-parser'); var loopback = require('loopback'); var passport = require('passport'); function hasEnglishLetters(str) { var matchedPosition = str.search(/[a-zA-Z]/i); if (matchedPosition !== -1) { return true; } return false; } function generateKey(hmacKey, algorithm, encoding) { assert(hmacKey, 'HMAC key is required'); algorithm = algorithm || 'sha1'; encoding = encoding || 'hex'; var hmac = crypto.createHmac(algorithm, hmacKey); var buf = crypto.randomBytes(32); hmac.update(buf); var key = hmac.digest(encoding); return key; } function profileToUser(provider, profile, options) { var userObj = {}; var generatedEmail = (profile.username || profile.id) + '@loopback.' + (profile.provider || provider) + '.com'; var profileEmail = (profile.emails && profile.emails[0] && profile.emails[0].value) || profile.email; var email = profileEmail || generatedEmail; var password = generateKey('password'); var username = provider + '.' + (profile.username || profile.id); var photo; // Get user photo with error handling try { photo = profile.photos[0].value; } catch (err) { photo = ''; } switch (provider) { case 'digitalTown': userObj.firstName = profile.first_name; userObj.lastName = profile.last_name; break; case 'facebook': userObj.firstName = profile.name.givenName; userObj.lastName = profile.name.familyName; userObj.city = profile._json.location ? profile._json.location.name : ""; break; case 'facebook-mobile': userObj.firstName = profile.name.givenName; userObj.lastName = profile.name.familyName; userObj.city = profile._json.location ? profile._json.location.name : ""; break; case 'twitter': if (hasEnglishLetters(profile.displayName)) { userObj.firstName = profile.displayName.split(" ")[0] || ""; userObj.lastName = profile.displayName.split(" ")[1] || ""; } else { userObj.firstName = profile.displayName.split(" ")[1] || ""; userObj.lastName = profile.displayName.split(" ")[0] || ""; } break; default: break; } userObj.username = username; userObj.password = password; userObj.imageUrl = photo; userObj.emailVerified = true; if (email) { userObj.email = email; } return userObj; } function setupProvidersConfigs(AuthProvider, passportConfigurator) { for (var s in config) { var c = config[s]; if (c.provider != 'local') { var providerClass = c.provider; if (c.provider === 'google') { providerClass = 'google-plus'; } /* if (c.provider === 'digitalTown'){ c.userProfile = function(token, done){ request({ method: 'GET', uri: app.get('digitalTownApi') + 'users', headers: { 'Authorization': 'Bearer ' + token } }, function (error, response, body) { if (error || response.statusCode !== 200) { console.error("Error:" + JSON.stringify(error)); done(error); } else { var data = JSON.parse(body); done(null, data); } }); } } */ c.profileToUser = profileToUser; var entry = { name: s, link: c.link, authPath: c.authPath, provider: c.provider, class: providerClass }; AuthProvider.create(entry, function (err, data) { console.log("provider created:" + JSON.stringify(data)); if (err) { console.log(err); } }); c.session = c.session !== false; passportConfigurator.configureProvider(s, c); } } } function setupAuthProviders(){ if (config) { var AuthProvider = app.models.AuthProvider; var loopbackPassport = require('loopback-component-passport'); var PassportConfigurator = loopbackPassport.PassportConfigurator; var passportConfigurator = new PassportConfigurator(app); // Initialize passport passportConfigurator.init(); // Set up related models passportConfigurator.setupModels({ userModel: app.models.user, userIdentityModel: app.models.userIdentity, userCredentialModel: app.models.userCredential }); // Configure passport strategies for third party auth providers and add them to the API AuthProvider.destroyAll(function (err, data) { if (err) { console.log(err); } else { setupProvidersConfigs(AuthProvider, passportConfigurator); } }); } } function setupAuthRoutes(){ // Third-party login success, redirect the app with the created access token. app.get(app.get('restApiRoot') + '/auth/account', ensureLoggedIn('/'), function (req, res, next) { app.models.user.update({id : req.user.id },{ lastLogin : new Date()}, function(err, result){ if (err){ console.log("Error: Could not save lastLogin: " + JSON.stringify(err)); } }); //Copy the cookie over for our AppAuth service that looks for accessToken cookie. res.cookie('accessToken', req.signedCookies['access_token'], {signed: true}); var accessToken = req.signedCookies['access_token']; console.log("accessToken: " + accessToken); res.redirect(Utils.getClientPrefixFromRequest(app, req) + 'auth/success?userId=' + req.user.id + '&accessToken=' + accessToken); }); app.get(app.get('restApiRoot') + '/auth/error', function (req, res, next) { console.log('Error authenticating to 3rd party') res.redirect(Utils.getClientPrefixFromRequest(app, req) + + 'auth/error'); }); app.get(app.get('restApiRoot') + '/auth/current', function (req, res, next) { if (!req.isAuthenticated || !req.isAuthenticated()) { return res.status(200).json({}); } //poor man's copy var ret = JSON.parse(JSON.stringify(req.user)); delete ret.password; res.status(200).json(ret); }); app.post(app.get('restApiRoot') + '/auth/logout', function (req, res, next) { req.session.destroy(function (err) { res.sendStatus(200); }); }); } // to support JSON-encoded bodies app.use(bodyParser.json()); // to support URL-encoded bodies app.use(bodyParser.urlencoded({ extended: true })); //// The access token is only available after boot app.use(app.loopback.token({ model: app.models.accessToken })); app.use(require('cookie-parser')(app.get('cookieSecret'))); var session = require('express-session'); var MySQLStore = require('express-mysql-session')(session); var options = { host: app.dataSources.db.connector.settings.host, port: app.dataSources.db.connector.settings.port, user: app.dataSources.db.connector.settings.user, password: app.dataSources.db.connector.settings.password || null, database: app.dataSources.db.connector.settings.database }; var sessionStore = new MySQLStore(options); app.middleware('session', require('express-session')({ store : sessionStore, secret: app.get('cookieSecret'), saveUninitialized: true, resave: true })); var config = false; try { var env = process.env.NODE_ENV || 'dev'; config = require('../providers.' + env + '.json'); setupAuthProviders(); } catch (err) { console.error('Please configure your passport strategy in `providers.json`.'); console.error('Copy `providers.json.template` to `providers.json` and replace the clientID/clientSecret values with your own.'); } var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn; setupAuthRoutes(); }; <filename>src/redux/index.js import cfgStore from "./configureStore"; import Provider from "./ReduxProvider"; export * from "./hooks.js"; export const ReduxProvider = Provider; export const configureStore = cfgStore; <filename>4.views/files.js const fs = require('fs'); var path = require('path'); const uploadFolder = path.join(__dirname, '../public'); /*****************************************\ * Handle files list view * \*****************************************/ var uploaded_list = []; module.exports.get = function(req,res){ var errors = req.validationErrors(); var title = 'Uploaded Files'; // Server variable declaration. var files_list = [] fs.readdirSync(uploadFolder).forEach(file => { console.log(file); files_list.push(file); }) res.render('files',{title:title, files:files_list}); // Embedding the values in the client document. } module.exports.add_post = function(req, res) { uploaded_list = []; console.log(req.files); if (!req.files){ return res.status(400).send('No files were uploaded.'); } // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file let sampleFile = req.files.sampleFile; sampleFile.mv(path.join(uploadFolder, sampleFile.name), function(err) { if (err){ return res.status(500).send(err); } else{ uploaded_list.push(sampleFile.name); } }); // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file let sampleFiles = req.files.sampleFiles; sampleFiles.forEach(function(file){ console.log(file); // Use the mv() method to place the file somewhere on your server file.mv(path.join(uploadFolder, file.name), function(err) { if (err){ return res.status(500).send(err); } else{ uploaded_list.push(file.name); } }); }) res.redirect('/files'); } module.exports.delete = function(req, res) { //var title = 'users'; // Server variable declaration. console.log(req.params.id); fs.unlink(path.join(uploadFolder, req.params.id), function(err){ if(err){ console.log(err); } }); this.get(req,res); //res.redirect('/files'); } module.exports.download = function(req, res) { res.download(path.join(uploadFolder, req.params.id)); } const startTime = new Date() const fs = require('fs-extra') const path = require('path') const webpack = require('webpack') const webpackConfig = require('../config/webpack.config.prod') const ProgressBarPlugin = require('progress-bar-webpack-plugin') const user = require('./utils/format-config')(require('../config/main.config.js')) const sh = require('kool-shell/namespaced')('__kirbywebpack') const compiler = webpack(webpackConfig) new ProgressBarPlugin({ format: sh.colors.gray('build [:bar] :percent'), clear: true, summary: false }).apply(compiler) Promise.resolve() .then(() => fs.remove(path.join(user.paths.assets, 'builds'))) .then(() => sh.log('Running the webpack compiler...')) .then( () => new Promise((resolve, reject) => { compiler.run((err, stats) => { if (err) reject(err) else if (stats.hasErrors()) { webpackErrorMessage() if (stats.compilation) { if (stats.compilation.errors) stats.compilation.errors.map(sh.error) if (stats.compilation.children) { stats.compilation.children.map(child => { const childStats = child.getStats() if (childStats.compilation) { if (childStats.compilation.errors) childStats.compilation.errors.map(sh.error) if (childStats.compilation.warnings) childStats.compilation.warnings.map(sh.warn) } }) } } sh.exit(0) } else if (stats.hasWarnings()) { sh.log('Warnings during the webpack compilation') if (stats.compilation) { if (stats.compilation.warnings) stats.compilation.warnings.map(sh.warn) if (stats.compilation.children) { stats.compilation.children.map(child => { const childStats = child.getStats() if (childStats.compilation && childStats.compilation.warnings) { childStats.compilation.warnings.map(sh.warn) } }) } } } resolve(stats) }) }) ) .catch(err => { webpackError(err) }) .then(() => { const elapsedTime = ((new Date() - startTime) / 1000).toFixed(3) sh.log() sh.success(`Build completed in ${elapsedTime}s !\n`) sh.exit(0) }) function webpackErrorMessage() { sh.error('Error during the webpack compilation') } function webpackError (err) { webpackErrorMessage() sh.error(err) sh.exit(0) } <gh_stars>0 /** * const prefixCls = 'style-104163'; * const images = '/static/images/src/bbs/Registration'; * @Author: czy0729 * @Date: 2018-06-26 15:33:02 * @Last Modified by: czy0729 * @Last Modified time: 2018-10-25 09:57:22 * @Path dev.tw-bt.com.mobile /src/bbs/Registration/store.js */ import React from 'react'; import PropTypes from 'prop-types'; import { injectV2, observer, form } from '@'; import { Layout } from '@_'; import { Form, Link } from '@components'; import CityPicker from '@components/Form/CityPicker'; import Const from '@const'; import Utils from '@utils'; import store from './store'; const Registration = (props, { $ }) => { const { form, onSubmit } = props; const { ww, _loaded: loadedUserInfo } = $.getState('userInfo'); const { status, name, phone, wechat, province, city, county, address, qq, message, order_no: orderNo, marks, _loaded: loadedRegistration } = $.getState('registration'); const { bankNo, bankName, branchName, cardUsername, _loaded: bankLoaded } = $.getState('bank'); if (!loadedUserInfo || !loadedRegistration || !bankLoaded) { return null; } let isCanEdit = false; let isFormRegist = false; let isCanRegist = false; let isFormSubmit = false; let isCanSubmit = false; let isUpdateOrder = false; let text; // status(-1=>取消报名, 0=>报名审核中, 1=>报名审核未通过, 2=>报名审核通过, // 3=>订单信息审核中, 4=>订单信息审核未通过, 5=>订单信息审核通过) switch (parseInt(status)) { case -1: isFormRegist = true; isCanRegist = true; isCanEdit = true; text = '重新报名'; break; case 0: isFormRegist = true; text = '报名审核中'; break; case 1: isFormRegist = true; isCanRegist = true; isCanEdit = true; text = '审核未通过,重新报名'; break; case 2: isFormSubmit = true; isCanSubmit = true; isCanEdit = true; text = '提交订单'; break; case 3: isFormSubmit = true; text = '订单审核中'; break; case 4: isFormSubmit = true; isCanSubmit = true; isCanEdit = true; isUpdateOrder = true; text = '审核未通过,重新提交订单'; break; case 5: isFormSubmit = true; text = '审核通过,请等待奖金发放'; break; default: isFormRegist = true; isCanRegist = true; isCanEdit = true; text = '提交报名'; break; } return ( <Layout title="活动报名"> {isFormRegist && ( <> <Form label form={form} renderHeader="请填写基本信息"> <Form.Input label="姓名" name="name" option={Const.rules.required} updatePlaceholder={false} initialValue={name} disabled={!isCanEdit} /> <Form.Input label="手机号" name="phone" option={Const.rules.gen('mobile')} type="phone" updatePlaceholder={false} initialValue={phone} disabled={!isCanEdit} /> <Form.Input label="旺旺号" name="ww" option={Const.rules.required} updatePlaceholder={false} initialValue={ww} disabled extra={ !ww && ( <Link className="t-primary" href={Const.__ROUTER__.ww}> 去绑定 </Link> ) } /> <Form.Input label="微信昵称" name="wechat" option={Const.rules.required} updatePlaceholder={false} initialValue={wechat} disabled={!isCanEdit} /> <CityPicker label="地区" name="area" option={Const.rules.required} initialValue={province ? [province, city, county] : []} disabled={!isCanEdit} /> <Form.Input label="详细地址" name="address" option={Const.rules.required} updatePlaceholder={false} initialValue={address} disabled={!isCanEdit} /> </Form> <Form label form={form} renderHeader="选填"> <Form.Input label="QQ" name="qq" updatePlaceholder={false} initialValue={qq} disabled={!isCanEdit} /> <Form.Input label="备注" name="message" updatePlaceholder={false} initialValue={message} disabled={!isCanEdit} /> </Form> <Form.Button type="primary" onClick={() => onSubmit(form, values => Utils.onConfirm('报名信息提交后不可修改,确定提交?', () => $.do.regist(values))) } disabled={!isCanRegist} > {text} </Form.Button> </> )} {isFormSubmit && ( <> <Form label form={form} renderHeader={ bankNo ? ( <p className="text-sm"> <span>银行卡使用绑定银行卡,</span> <span className="text-primary" onClick={() => Utils.router.push('/person/bank')} > 前往查看 </span> </p> ) : ( <p className="text-sm"> <span>请先绑定银行卡后再提交,</span> <span className="text-primary" onClick={() => Utils.router.push('/person/bank/bind')} > 前往绑定 </span> </p> ) } > <Form.Input label="订单号" name="order_no" option={Const.rules.required} updatePlaceholder={false} initialValue={orderNo} disabled={!isCanSubmit || !bankNo} /> <Form.Input label="开户行" name="bank_name" option={Const.rules.required} updatePlaceholder={false} initialValue={ bankName ? `${bankName || ''} ${branchName || ''}` : undefined } disabled /> <Form.Input label="开户姓名" name="bank_user" option={Const.rules.required} updatePlaceholder={false} initialValue={cardUsername} disabled /> <Form.Input label="银行卡号" name="bank_card" option={Const.rules.required} updatePlaceholder={false} initialValue={bankNo} disabled /> </Form> {marks && ( <p className="p-w mt-d text-sm text-danger"> <span>近一次审核信息:</span> <span>{marks}</span> </p> )} <Form.Button type="primary" onClick={() => onSubmit(form, values => Utils.onConfirm( '订单信息提交后,在审核前不可修改,确定提交?', () => { if (isUpdateOrder) { $.do.update(values); } else { $.do.submit(values); } } )) } disabled={!isCanSubmit} > {text} </Form.Button> </> )} </Layout> ); }; Registration.contextTypes = { $: PropTypes.object }; export default injectV2(store)(form(observer(Registration))); <filename>config-examples/cerner-open.js // Use this to template define new configurations module.exports = { baseURL: "https://fhir-open.stagingcerner.com/beta/ec2458f2-1e24-41c8-b71b-0e701af7583d", authType: "none", patientExportEndpoint: "Patient/$export", requiresAuth: false, strictSSL: true, fastestResource: "Patient" }; <filename>dnsconfig.js var NONE_REG = NewRegistrar("none", "NONE"); var DIGITALOCEAN = NewDnsProvider("digitalocean", "DIGITALOCEAN"); D( "zaverden.com", NONE_REG, DnsProvider(DIGITALOCEAN), DefaultTTL("10m"), NAMESERVER_TTL("30m") ); require_glob("./configs/"); <reponame>Lawrence-Portfolio/Hamovniky import UrlGeneration from '@lovata/url-generation'; export default new(class ArticlesListing { constructor() { this.radioButton = 'input[name="filter"]'; this.postsWrap = '#postsWrap'; this.xhr = null; this.init(); } init() { $(`${this.radioButton}`).on('change', (target) => { target.preventDefault(); if (this.xhr) { this.xhr.abort(); } let button = $(target.currentTarget); UrlGeneration.init(); UrlGeneration.clear(); UrlGeneration.set('filter', button.val()); UrlGeneration.update(); this.xhr = $.request('onAjax', { update: { 'posts/default' : `${this.postsWrap}` } }) }); } })(); /* eslint-disable react/prop-types */ /** * 外机选择,主要用于服务器入库 */ // ================== // 所需的各种插件 // ================== import React from 'react'; import P from 'prop-types'; import _ from 'lodash'; import http from '@src/util/http'; import { Table, Modal, } from 'antd'; import { inject} from 'mobx-react'; import { withRouter } from 'react-router'; import tools from '@src/util/tools'; // 工具 @withRouter class OutsideMachineRadio extends React.Component { static propTypes = { location: P.any, history: P.any, match: P.any, children: P.any, portDict: P.any, disabled: P.bool, // 父组件 来控制子组件是否可用 比如:前置条件机房已经有了 就让使用子组件 allowClear: P.bool, // 父组件 来控制子组件是否可用 比如:前置条件机房已经有了 就让使用子组件 disabledTip: P.string, // 不能使用子组件原因 title: P.string, style: P.any, // 样式 fetchPath: P.string, // 获取数据的查询条件 defaultData: P.any, // 当前选中的信息 onSelect: P.func, // 确认选择 }; formRefAdd = React.createRef(); constructor (props) { super(props); this.selectAreaNode = {}; // 选中的地区节点信息 this.selectedRows = []; // 选中行数据 this.regionId = ''; this.uw = 0; this.state = { nwoData: {}, // 获取的机柜数据 orgionLists: [], // 第一次获取的list数据(原始数据) lists: [], // 通过机柜名称查询后的数据 loading: false, showModal: false, cabinetName: '', }; } componentDidMount () { // this.getDetail(this.props.cabinetId); } // shouldComponentUpdate (nextProps, nextState) { // return nextProps.regionId !== this.props.regionId; // } componentWillReceiveProps (nextProps) { } /** * 获取节点详情信息 * @param 查询条件 fileds */ getDetail (fileds = {}) { this.setState({ loading: true, }); http.get(`${this.props.fetchPath}`, { params: fileds }) .then((res) => { res = res.data; if (tools.hasStatusOk(res)) { this.setState({ loading: false, lists: res.data, orgionLists: res.data, }); } else { tools.dealFail(res); this.setState({ loading: false, }); } }) .catch(() => { this.setState({ loading: false, }); }); } // 选择选中行 selectedRow (selectedRowKeys, selectedRows) { this.selectedRows = selectedRows; this.props.onSelect(selectedRowKeys, selectedRows); this.setState({ showModal: false, cabinetName: selectedRows[0].name, }); } modalShow () { if (this.props.disabled) { Modal.warning({ title: this.props.disabledTip }); return; } this.getDetail(); this.setState({ showModal: true }); } /** 点击关闭时触发 **/ onClose = () => { this.setState({showModal: false}); }; // 构建字段 makeColumns () { const columns = [ { title: '外机名称', dataIndex: 'nodeServerName', key: 'nodeServerName' }, { title: '位置码', dataIndex: 'physicsLocationCode', key: 'physicsLocationCode' }, { title: '节点数', dataIndex: 'nodeNum', key: 'nodeNum' }, { title: '剩余节点数', dataIndex: 'nodeRemain', key: 'nodeRemain' }, { title: '总U位数', dataIndex: 'us', key: 'us' }, { title: '资源备注', dataIndex: 'remark', key: 'remark' }, ]; return columns; } render () { const {title, uw, regionId} = this.props; const {lists, showModal, loading} = this.state; return ( <main className="mian"> <Modal title={this.props.title || '选择外机'} maskClosable={false} width="90%" destroyOnClose footer={false} onOk={this.onModalOk} onCancel={this.onClose} visible={showModal} > {/* 搜索 */} {/* <div className="g-search"> <Form ref={this.searchFormRef} name="searchbox" layout="inline" onFinish={(values) => {this.getDetail(values);}}> <Form.Item name="cabinetName"> <Input placeholder="外机名称" allowClear/> </Form.Item> <Form.Item shouldUpdate> <Button type="primary" htmlType="submit" >搜索</Button> </Form.Item> </Form> </div> */} {/* 数据展示 */} <div className="g-table"> <Table columns={this.makeColumns()} rowKey={(record) => record.id} loading={loading} dataSource={lists} pagination={false} rowSelection={{ type: 'radio', onChange: (selectedRowKeys, selectedRows) => {this.selectedRow(selectedRowKeys, selectedRows);} }} /> </div> </Modal> <span onClick={() => {this.modalShow();}}> {this.props.children} </span> </main> ); } } export default OutsideMachineRadio; <filename>Chapter04/my-article/MyArticle.js export default class MyArticle extends HTMLElement { constructor() { // We are not even going to touch this. super(); // lets create our shadow root this.shadowObj = this.attachShadow({mode: 'open'}); // Then lets render the template this.render(); } render() { this.shadowObj.innerHTML = this.getTemplate(); } getTemplate() { return ` <h1 class="article-heading"> <slot name="article-heading"></slot> </h1> <div class="article-author"> <slot name="author"></slot> </div> <div class="article-content"> <slot name="article"></slot> </div> ${this.getStyle()} `; } getStyle() { return ` <style> :host { display: block; background: #e4f4fb; padding: 10px; } .article-heading { text-align: right; text-transform: lowercase; font-size: 50px; margin-bottom: 0; } .article-author { text-align: right; text-transform: lowercase; font-style: italic; font-size: 22px; padding-bottom: 20px; border-bottom: 2px solid black; } .article-content { line-height: 1.5; margin-top: 20px; } .article-content::first-letter { font-size: 50px; line-height: 0; } </style> `; } } <reponame>tstutorial/code const element = document.getElementById(123); // ~~~ // 参数类型错误,应该为 string 类型 <reponame>LuisPaGarcia/store-maker import React from "react"; export default React.createContext({ points: 0, addPoints: () => { }, pedido: [], addPedido: () => { }, removePedido: () => { }, waURL: 'https://wa.me/50249033688/' }); var searchData= [ ['elems',['elems',['../classo3_1_1array.html#a55a4f63a7d5bbee794e02fad1c4534d9',1,'o3::array']]] ]; import React, { Component } from 'react' // import local css as s. import s from './styles.css' // import global css as gs import gs from './../../styles/grid.css' import Card from '../../components/Card/Card' class HomePage extends Component { render() { return ( <div className={gs.container}> <div className={gs.line}> <div className={s.cardContainer}> <Card target="/stupid-tree" header="Idiotic Tree Keeps Trying To Plant Seeds On Sidewalk" body="PORTLAND, OR—Pointing out that the total dipshit had dropped dozens of acorns all along the length of pavement, sources confirmed Thursday that a completely idiotic tree keeps trying to plant seeds on the sidewalk. “Come on, you fucking moron, what are you doing? That’s concrete"/> </div> <div className={s.cardContainer}> <Card target="/stupid-tree" header="Idiotic Tree Keeps Trying To Plant Seeds On Sidewalk" body="PORTLAND, OR—Pointing out that the total dipshit had dropped dozens of acorns all along the length of pavement, sources confirmed Thursday that a completely idiotic tree keeps trying to plant seeds on the sidewalk. “Come on, you fucking moron, what are you doing? That’s concrete"/> </div> <div className={s.cardContainer}> <Card target="/stupid-tree" header="Idiotic Tree Keeps Trying To Plant Seeds On Sidewalk" body="PORTLAND, OR—Pointing out that the total dipshit had dropped dozens of acorns all along the length of pavement, sources confirmed Thursday that a completely idiotic tree keeps trying to plant seeds on the sidewalk. “Come on, you fucking moron, what are you doing? That’s concrete"/> </div> <div className={s.cardContainer}> <Card target="/stupid-tree" header="Idiotic Tree Keeps Trying To Plant Seeds On Sidewalk" body="PORTLAND, OR—Pointing out that the total dipshit had dropped dozens of acorns all along the length of pavement, sources confirmed Thursday that a completely idiotic tree keeps trying to plant seeds on the sidewalk. “Come on, you fucking moron, what are you doing? That’s concrete"/> </div> </div> </div> ) } } export default HomePage /** @jsx jsx */ import { jsx, Box } from 'theme-ui' export default function Container(props) { return ( <Box {...props} sx={{ maxWidth: 'container', mx: 'auto', px: 3, }} /> ) } <filename>cypress/support/step-definitions/popover-container-steps.js import { popoverContainerContent, popoverContainerTitle, popoverContainerContentSecondInnerElement, popoverCloseIcon, popoverSettingsIconNoIFrame, } from "../../locators/popover-container"; import { keyCode } from "../helper"; Then("Popover container is visible", () => { popoverContainerContent().should("exist"); popoverSettingsIconNoIFrame().should("exist"); popoverContainerContent().should("be.visible"); popoverContainerContent() .should("have.css", "background-color", "rgb(255, 255, 255)") .and( "have.css", "box-shadow", "rgba(0, 20, 29, 0.2) 0px 5px 5px 0px, rgba(0, 20, 29, 0.1) 0px 10px 10px 0px" ); popoverContainerContentSecondInnerElement() .should("have.attr", "data-element", "popover-container-close-component") .and("be.visible"); popoverContainerContentSecondInnerElement() .children() .should("have.attr", "data-element", "close") .and("be.visible"); }); Then("Popover title on preview is set to {word}", (title) => { popoverContainerTitle().should("have.text", title); }); Then("Popover container is not visible", () => { popoverContainerContent().should("not.exist"); }); When("I click onto popover setting icon using {string} key", (key) => { popoverSettingsIconNoIFrame().trigger("keydown", keyCode(key)); }); Then("I press onto closeIcon using {string} key", (key) => { popoverCloseIcon().trigger("keydown", keyCode(key)); }); When("I click popover close icon", () => { popoverCloseIcon().click(); }); When("I open popover container in NoIFrame", () => { popoverSettingsIconNoIFrame().click(); }); import firebaseApp from './firebaseapp'; /** Authentication */ export function loginWithEmailPassword(email, password) { return firebaseApp.auth().signInWithEmailAndPassword(email, password) } export const logout = () => { return firebaseApp.auth().signOut(); }var searchData= [ ['icomponent_124',['IComponent',['../classvlk_1_1IComponent.html',1,'vlk']]], ['ieventlistener_125',['IEventListener',['../classvlk_1_1IEventListener.html',1,'vlk']]], ['isloglevelenabled_126',['IsLogLevelEnabled',['../classvlk_1_1IsLogLevelEnabled.html',1,'vlk']]], ['isspecialization_127',['IsSpecialization',['../structvlk_1_1IsSpecialization.html',1,'vlk']]], ['isspecialization_3c_20primary_3c_20args_2e_2e_2e_20_3e_2c_20primary_20_3e_128',['IsSpecialization< Primary< Args... >, Primary >',['../structvlk_1_1IsSpecialization_3_01Primary_3_01Args_8_8_8_01_4_00_01Primary_01_4.html',1,'vlk']]] ]; <gh_stars>0 import { ajax } from "discourse/lib/ajax"; export default Discourse.Route.extend({ controllerName: "admin-plugins-explorer", model() { const p1 = this.store.findAll("query"); const p2 = ajax("/admin/plugins/explorer/schema.json", { cache: true }); return p1 .then(model => { model.forEach(query => query.markNotDirty()); return p2.then(schema => { return { model, schema }; }); }) .catch(() => { p2.catch(() => {}); return { model: null, schema: null, disallow: true }; }); }, setupController: function(controller, model) { controller.setProperties(model); }, actions: { refreshModel: function() { this.refresh(); return false; } } }); module.exports = { async find(ctx) { try { const data = await strapi.plugins.vercel.services.vercel.getDeployments(); ctx.send(data); } catch (e) { ctx.send({ error: e }, 400); } }, async findOne(ctx) { const { id } = ctx.params; try { const data = await strapi.plugins.vercel.services.vercel.getDeployment(id); ctx.send(data); } catch (e) { ctx.send({ error: e }, 400); } }, async deploy(ctx) { const { target } = ctx.params; try { const data = await strapi.plugins.vercel.services.vercel.deploy(target); ctx.send(data); } catch (e) { ctx.send({ error: e }, 400); } } }; <reponame>dweinstein/json-stream-response<filename>index.js var JSONStream = require('JSONStream'); module.exports = function jsonStreamResponse(res) { res.writeHead(200, { 'Content-Type': 'application/json' }); var stringify = JSONStream.stringify(); stringify.pipe(res, {end: true}); return stringify; }; <gh_stars>0 import React from 'react'; import moment from 'moment'; import momentDurationFormatSetup from 'moment-duration-format'; import CancelDeployment from 'components/CancelDeployment'; import BulkDeploymentLink from 'components/link/BulkDeployment'; import LogViewer from 'components/LogViewer'; import { bp, color, fontSize } from 'lib/variables'; export const getDeploymentDuration = deployment => { const deploymentStart = deployment.started || deployment.created; const durationStart = (deploymentStart && moment.utc(deploymentStart)) || moment.utc(); const durationEnd = (deployment.completed && moment.utc(deployment.completed)) || moment.utc(); const duration = moment .duration(durationEnd - durationStart) .format('HH[hr] mm[m] ss[sec]'); return duration; }; /** * Displays information about a deployment. */ const Deployment = ({ deployment }) => ( <div className="deployment"> <div className="details"> <div className="field-wrapper created"> <div> <label>Created</label> <div className="field"> {moment .utc(deployment.created) .local() .format('DD MMM YYYY, HH:mm:ss (Z)')} </div> </div> </div> <div className={`field-wrapper status ${deployment.status}`}> <div> <label>Status</label> <div className="field"> {deployment.status.charAt(0).toUpperCase() + deployment.status.slice(1)} </div> </div> </div> <div className="field-wrapper duration"> <div> <label>Duration</label> <div className="field">{getDeploymentDuration(deployment)}</div> </div> </div> {deployment.bulkId &&<div className="field-wrapper bulk"> <div> <label>Bulk Deployment</label> <div className="field"> <BulkDeploymentLink bulkIdSlug={deployment.bulkId} > View bulk deployment </BulkDeploymentLink> </div> </div> </div>} </div> <div className="button-row"> {['new', 'pending', 'running'].includes(deployment.status) && ( <CancelDeployment deployment={deployment} /> )} </div> <LogViewer logs={deployment.buildLog} /> <style jsx>{` .button-row { padding: 0px calc(100vw / 16) 20px; width: 100%; @media ${bp.xs_smallUp} { display: flex; flex-wrap: wrap; min-width: 100%; padding-left: calc(((100vw / 16) * 1.5) + 28px); position: relative; width: 100%; } @media ${bp.tabletUp} { padding: 0 calc(100vw / 16) 20px calc(((100vw / 16) * 1.5) + 28px); } @media ${bp.extraWideUp} { padding-left: calc(100vw / 16); } } .details { padding: 104px calc(100vw / 16) 20px; width: 100%; @media ${bp.xs_smallUp} { display: flex; flex-wrap: wrap; min-width: 100%; padding-left: calc(((100vw / 16) * 1.5) + 28px); position: relative; width: 100%; } @media ${bp.tabletUp} { padding: 120px calc(100vw / 16) 20px calc(((100vw / 16) * 1.5) + 28px); } @media ${bp.extraWideUp} { padding-left: calc(100vw / 16); padding-top: 48px; } h3 { width: 100%; @media ${bp.xs_smallUp} { left: calc(100vw / 16); position: absolute; top: 32px; } @media ${bp.tabletUp} { top: 48px; } @media ${bp.extraWideUp} { min-width: 25%; padding-right: 60px; position: initial; width: 25%; } } .field-wrapper { &::before { left: calc(((-100vw / 16) * 1.5) - 28px); } @media ${bp.xs_smallUp} { min-width: 50%; position: relative; width: 50%; } @media ${bp.desktopUp} { min-width: 33.33%; min-width: calc(100% / 3); width: 33.33%; width: calc(100% / 3); } @media ${bp.extraWideUp} { min-width: 25%; width: 25%; } &.created { &::before { background-image: url('/static/images/created.svg'); background-size: 17px 16px; } } &.duration { &::before { background-image: url('/static/images/duration.svg'); background-size: 17px; } } &.status { &::before { background-size: 14px; } &.new { &::before { background-image: url('/static/images/pending.svg'); } } &.pending { &::before { background-image: url('/static/images/pending.svg'); } } &.running { &::before { background-image: url('/static/images/in-progress.svg'); } } &.cancelled { &::before { background-image: url('/static/images/failed.svg'); } } &.error { &::before { background-image: url('/static/images/failed.svg'); } } &.failed { &::before { background-image: url('/static/images/failed.svg'); } } &.complete { &::before { background-image: url('/static/images/successful.svg'); } } } &.bulk { &::before { background-image: url('/static/images/tasks-dark.svg'); background-size: 14px; } } & > div { width: 100%; } .field { padding-right: calc((100vw / 16) * 1); @media ${bp.extraWideUp} { padding-right: calc((100vw / 16) * 0.5); } } } } `}</style> </div> ); export default Deployment; <reponame>vivaxy/JavaScript<filename>lib/__tests__/fixtures/execute/identifier-000/output.js /** * @since 20180905 18:10 * @author vivaxy */ module.exports = undefined; // import dependencies via preval.require so that they're available as values at compile time const processorNames = preval.require('./processorNames'); const RingBuffer = preval.require('./ringBuffer').default; class RecorderProcessor extends AudioWorkletProcessor { constructor(options) { super(); const processorOptions = options.processorOptions || {}; this.numOutputChannels = options.outputChannelCount || 2; this.numInputChannels = processorOptions.numInputChannels || 2; this.bufferSize = processorOptions.bufferSize || 1024; this.recording = false; this.clear(); this.port.onmessage = (event) => { const data = event.data; if (data.name === 'start') { this.record(data.duration); } else if (data.name === 'stop') { this.stop(); } }; } process(inputs) { if (!this.recording) { return true; } else if (this.sampleLimit && this.recordedSamples >= this.sampleLimit) { this.stop(); return true; } const input = inputs[0]; this.inputRingBuffer.push(input); if (this.inputRingBuffer.framesAvailable >= this.bufferSize) { this.inputRingBuffer.pull(this.inputRingBufferArraySequence); for (let channel = 0; channel < this.numOutputChannels; ++channel) { const inputChannelCopy = this.inputRingBufferArraySequence[ channel ].slice(); if (channel === 0) { this.leftBuffers.push(inputChannelCopy); if (this.numInputChannels === 1) { this.rightBuffers.push(inputChannelCopy); } } else if (channel === 1 && this.numInputChannels > 1) { this.rightBuffers.push(inputChannelCopy); } } this.recordedSamples += this.bufferSize; } return true; } record(duration) { if (duration) { this.sampleLimit = Math.round(duration * sampleRate); } this.recording = true; } stop() { this.recording = false; const buffers = this.getBuffers(); const leftBuffer = buffers[0].buffer; const rightBuffer = buffers[1].buffer; this.port.postMessage( { name: 'buffers', leftBuffer: leftBuffer, rightBuffer: rightBuffer }, [leftBuffer, rightBuffer] ); this.clear(); } getBuffers() { const buffers = []; buffers.push(this.mergeBuffers(this.leftBuffers)); buffers.push(this.mergeBuffers(this.rightBuffers)); return buffers; } mergeBuffers(channelBuffer) { let result = new Float32Array(this.recordedSamples); let offset = 0; let lng = channelBuffer.length; for (var i = 0; i < lng; i++) { let buffer = channelBuffer[i]; result.set(buffer, offset); offset += buffer.length; } return result; } clear() { this.leftBuffers = []; this.rightBuffers = []; this.inputRingBuffer = new RingBuffer( this.bufferSize, this.numInputChannels ); this.inputRingBufferArraySequence = new Array(this.numInputChannels) .fill(null) .map(() => new Float32Array(this.bufferSize)); this.recordedSamples = 0; this.sampleLimit = null; } } registerProcessor(processorNames.recorderProcessor, RecorderProcessor); �������.���E���\���s�����������������������������+��B��Y��p����������������������(��?��V��m����������������������%��<��S��j�������������������� ��"��9��P��g��~���������������������6��M��d��{���������������������3��J��a��x���������������������0��G��^��u����������������������-��D��[��r�������������������� ��* ��A ��X ��o ��� ��� ��� ��� ��� ��� �� ��' ��> ��U ��l ��� ��� ��� ��� ��� ��� �� ��$ ��; ��R ��i ��� ��� ��� ��� ��� ��� �� ��! ��8 ��O ��f ��} ��� ��� ��� ��� ��� �� �� ��5 ��L ��c ��z ��� ��� ��� ��� ��� ������2��I��`��w���������������������/��F��]��t����������������������,��C��Z��q����������������������)��@��W��n����������������������&��=��T��k�������������������� ��#��:��Q��h������������������� �� ��7��N��e��|���������������������4��K��b��y���������������������1��H��_��v����������������������.��E��\��s����������������������+��B��Y��p����������������������(��?��V��m����������������������%��<��S��j�������������������� ��"��9��P��g��~���������������������6��M��d��{���������������������3��J��a��x���������������������0��G��^��u����������������������-��D��[��r�������������������� ��* ��A ��X ��o ��� ��� ��� ��� ��� ��� ��!��'!��>!��U!��l!���!���!���!���!���!���!�� "��$"��;"��R"��i"���"���"���"���"���"���"�� #��!#��8#��O#��f#��}#���#���#���#���#���#��$��$��5$��L$��c$��z$���$���$���$���$���$��%��%��2%��I%��`%��w%���%���%���%���%���%��&��&��/&��F&��]&��t&���&���&���&���&���&���&��'��,'��C'��Z'��q'���'���'���'���'���'���'��(��)(��@(��W(��n(���(���(���(���(���(���(��)��&)��=)��T)��k)���)���)���)���)���)���)�� *��#*��:*��Q*��h*��*���*���*���*���*���*�� +�� +��7+��N+��e+��|+���+���+���+���+���+��,��,��4,��K,��b,��y,���,���,���,���,���,��-��-��1-��H-��_-��v-���-���-���-���-���-���.��.��..��E.��\.��s.���.���.���.���.���.���.��/��+/��B/��Y/��p/���/���/���/���/���/���/��0��(0��?0��V0��m0���0���0���0���0���0���0��1��%1��<1��S1��j1���1���1���1���1���1���1�� 2��"2��92��P2��g2��~2���2���2���2���2���2��3��3��63��M3��d3��{3���3���3���3���3���3��4��4��34��J4��a4��x4���4���4���4���4���4��5��5��05��G5��^5��u5���5���5���5���5���5���5��6��-6��D6��[6��r6���6���6���6���6���6���6��7��*7��A7��X7��o7���7���7���7���7���7���7��8��'8��>8��U8��l8���8���8���8���8���8���8�� 9��$9��;9��R9��i9���9���9���9���9���9���9�� :��!:��8:��O:��f:��}:���:���:���:���:���:��;��;��5;��L;��c;��z;���;���;���;���;���;��<��<��2<��I<��`<��w<���<���<���<���<���<��=��=��/=��F=��]=��t=���=���=���=���=���=���=��>��,>��C>��Z>��q>���>���>���>���>���>���>��?��)?��@?��W?��n?���?���?���?���?���?���?��@��&@��=@��T@��k@���@���@���@���@���@���@�� A��#A��:A��QA��hA��A���A���A���A���A���A�� B�� B��7B��NB��eB��|B���B���B���B���B���B��C��C��4C��KC��bC��yC���C���C���C���C���C��D��D��1D��HD��_D��vD���D���D���D���D���D���E��E��.E��EE��\E��sE���E���E���E���E���E���E��F��+F��BF��YF��pF���F���F���F���F���F���F��G��(G��?G��VG��mG���G���G���G���G���G���G��H��%H��<H��SH��jH���H���H���H���H���H���H�� I��"I��9I��PI��gI��~I���I���I���I���I���I��J��J��6J��MJ��dJ��{J���J���J���J���J���J��K��K��3K��JK��aK��xK���K���K���K���K���K��L��L��0L��GL��^L��uL���L���L���L���L���L���L��M��-M��DM��[M��rM���M���M���M���M���M���M��N��*N��AN��XN��oN���N���N���N���N���N���N��O��'O��>O��UO��lO���O���O���O���O���O���O�� P��$P��;P��RP��iP���P���P���P���P���P���P�� Q��!Q��8Q��OQ��fQ��}Q���Q���Q���Q���Q���Q��R��R��5R��LR��cR��zR���R���R���R���R���R��S��S��2S��IS��`S��wS���S���S���S���S���S��T��T��/T��FT��]T��tT���T���T���T���T���T���T��U��,U��CU��ZU��qU���U���U���U���U���U���U��V��)V��@V��WV��nV���V���V���V���V���V���V��W��&W��=W��TW��kW���W���W���W���W���W���W�� X��#X��:X��QX��hX��X���X���X���X���X���X�� Y�� Y��7Y��NY��eY��|Y���Y���Y���Y���Y������StarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascript������������� ����� � ���������E������� �� ��� ����������@���������� ��������������������������� ������ ����������������������������������� �������"�������������������������������� �������������3�������������@��������������@��������������@������������������������������&���.���6���=���E���M���T���\���d���j���r���y����������������������������������������������������������������������������������#��*��1��9��A��H��O��W��_��g��o��w��~������������������������������������������������������� ������ ��(��/��6��>��E��L��R��Y��a��i��o��w��~������������������������������������������������������� ������"��*��1��9��A��I��Q��X��_��g��n��v��}������������������������������������������������������� ������$��+��2��9��A��H��P��W��_��f��n��v��~����������������������������������������������������������������#��+��0��8��?��F��N��U��\��c��k��s��{������������������������������������������������������� ������$��+��2��:��A��H��P��W��_��g��o��w��~������������������������������������������������������� ������#��+��2��9��@��G��N��U��Z��b��i��q��y������������������������������������������������������� ������"��*��1��9��A��H��N��U��\��c��j��r��z�������������������������������������������������������� �� �� �� ��# ��+ ��2 ��: ��A ��I ��Q ��Y ��` ��h ��o ��v ��~ ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� �� �� �� �� ��# ��+ ��2 ��: ��A ��H ��O ��V ��^ ��e ��m ��t ��z ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� �� �� �� �� �� ��( ��0 ��5 ��= ��D ��K ��S ��Z ��b ��j ��q ��y �� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� �� �� �� �� ��$ ��, ��3 ��; ��C ��J ��P ��X ��` ��g ��o ��w ��~ ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� �� �� �� �� �� ��( ��0 ��7 ��? ��F ��M ��T ��[ ��b ��i ��q ��y ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ���� ������!��)��0��8��?��G��N��U��\��c��k��s��{���������������������������������������������������������� ������%��,��2��9��@��H��P��X��`��f��m��t��z�������������������������������������������������������������� ��'��/��7��?��F��M��U��]��e��l��r��z���������������������������������154464961328292121069841266682481909131856648912831404326506515500720129533427792698157168101917978949993815199236501603776870306293262489808116030573220815427765611212438193444691290025614244762135594261951654124608691399839710884341174360027921721659823597690286635479444032456397969361064416193432568311664320013503308523707488102861715031913522795104961911331304218920394299112114172659331787415805012149934841324513417331638861731815885847116500983384019273254601001119307050799617176126631746596958443619062309279324116549163582611132189812387457267251415058661451010936455419766565826061619737912200126174560784952711433052063948961506964882735564006849000741105872271585756118209901150422372297574491828710907981284448012608862105960554255264969744949766212680336183671911994756152089301239738618859469993444212403117173820661045181317453834364619154917791360416923550291807512331637982907852104434811616995073084061063838062102961112137113955987641221815311279513673373763836219581109796991372246619388430405593211260949137726091574710583425041129005675944812494454698978517412854325213312993199223961710525261956573313734597156129271746487727566544393648363816176663821842121965616276000441098244465421006975385106205116898181654775594515717241771563041012478456778293718697299281145694372625491664319269816383401456321516424573134498066164194777888710879458828222417921139868715892897184113668373429173818038114373143076341554617816404488419321813595905104184121459163614684617161689871668688118316577428652567915238146231510652614231961138378881786115214366678694939632360731826198125561745313690171144703817372107402521776698211974601146488643185353417210729304932601723417802918919626807790449477654290999148857211073507314518835114851406704208184236251433592977231498715620165471511636925464873641949829814622531176928632151475589440945150337202405660164268389778276817708790545208911387959132858071673907518157801764638177319706236219159148981519743211256044142457591579579210049055676532316704854157829622777223122862181830865015541972669737216317068106442697488102150689756224463168225451475592523230047748581399175888453616922406049393181365341547963119444609772537991778734456483552061365971813950294143201009969805505487752514441081916478502574291225245906315804604563467437866911290435711343898104681401886473014507581587501069385711014166941032421867291515273276117608963743625114706654772115399259610047570218204213515208124155941830036658274357828666143604349234225150027756554689154868181913051617601947194305444242242385700818352381337526212109021005684937598982737235185581298092647155730799381524751228083170716945165127643571584119125959623905602693198159058331156619918592869181451793140297171197799239831148434601723565819274565718663925147699623261598670264376164122661179950466179428175032512801998138682121190178310297003192076811330118667526944323294364781428323444808571351360119449562180528516143456102909125009361444123616494910939187172781411137309117167126460716472770241067606676597301927202294058581151657014578743473207170889762208582167180921421298044718919359566118537977506862122823191811924131766545133221447910310508473935713413154127123643452630613686212713963322351121884106184148455170273119527050111758267609214654862786132042451364781405049887021579155337918301326468111271027114087723640723684359218239173149437511616186676071041396902681523472819127510705141821647768998928128013304785172583925779296177557571427040109116571156408082340711947895800218616793424890788537787548720844132140922655173791039497685083009896116585654400152112126356252435134755110208111922469253761691277604156001721275725833677305754744251245759713671665059212803494156806088869986677165103284607437292169957501171385610255495156748055361717567925943033326820060989086266874796311536102968223207218122523617597416734249214025098118823581696436552684382648483040602372822712174810113355731335003512436981330363532712347998543882581512057116113022872432715871237937881851749398487371203521252985681943656720660301902755615333157508000212446022111218736973464154557113960299179960451102662512196932595331018335112109271721511005664834143230620177526031919540711478014729993876643917813278166185281600248018773314417574216376965109022398057139387770113652737�����n�����* ���!��'$���)���8���S���[���]��a���c���j���u���w���������9���o���z���h������������������]���j���1���z��� ���������������o*��+��0�H�J�+c��d�dj�[t��~������ ��?��q�������ZD�OE��L�EO�!`�8x�������J��u��d���������������������������������=�����<�����!��i�������[���� ���o�e������!��-�]:��:� <�3@��J�iT�z�{����L��J����D��ڒ�ٺ������������������:�����w��u�-���n�� �����#��)� 7��R��T��Z�z[�2a�������2��L��s��ܨ�|��X��������P�������������������� �K������!����,������� ��*��+�Q5�8��;�C�\I�n`��l�Op��v����U�������6����˥�������|����R!��)��+�t;��e��m�qn�v���_�����]��5���������������������'�_)�]9�X�yX��[��\�6^�`� b�tf��i�an��v��w��x�z�V�����!��q��n�����R��� �# �� �� �� �� �� ��" �Q0 �3 �a6 �!@ �lD �^O ��V �]Y �] ��] ��a ��� �>� �s� ��� ��� ��� ��U ��^ ��z ��} ��� �� ��� �� �� ��� �(� �7� �>� ��� �L� ��� ��� ��� ��� ��� �Q� �� ��< ��? �4B ��E �x� �q� �~� �� �2� ��� �!� �*� ��� �� �� �K �c ��R ��S ��[ �] �` �(a �Wl �p � { �J~ �Z� �8� �U� ��� ��� ��� �y� ��� ��� �� ��� �u� �� �i �"1 �l2 �6 ��9 �]i ��i �n �� �y� �� �6� �� �o� ��� �9� ��� �!� ��� �5��=��H��P��R��a��c��h��l�1t��v� ����������� ������.��8�����������#�����<��(�������� ��d�t���z!�(�+\�%s�nv��v��z�ދ�������b�����F�����h��ɧ�����)����ϸ�Ľ������������g�����������r�����*��1�\5�4;��C��O�{Y��i����������������M��������F����������� �=��������/�W5��=�-~����[�����e����E���� �� ��������w��������1������������k�p�q��u��w��~����:����ڒ�����������+��7�lC�lD��f��i��k�dl�n�ޛ����������� ��̴�u��d���������������������}����������"��$��+�.��0�1�2��5��P��o�������������E����� ����� ��%��&��.��/��1��L��M�"Q�=p��t��}�Ճ�]��r����b��u�����<�������_�����<�� �H��#��'��'�e)��.�D/�?0�11��1�94�K<�l@�+A��A�EG�IK��O��T�gW��Z��n��s��u�R~��~����������[�������� ��6���]��^�^u�U��.��̭����n��r�����S��������(function () { 'use strict'; var d2sApp = angular.module('d2sApp'); /** * Is called on every request or response of an HTTP call. Adds authentication info * from cookies to requests. Removes old authentication info from cookies on responses * with error code 401 due to an expired authentication. * * derived from: http://www.aschua.de/blog/pairing-angularjs-and-javaee-for-authentication/ (02/07/2015) */ d2sApp.factory('authHttpInterceptor', function ($rootScope, $injector, $cookieStore) { var authHttpInterceptor = { request: function ($request) { // on requests if ($request.url.substr(0, 3) === "api") { // attach auth only to api calls var authFactory = $injector.get('authFactory'); if (authFactory.isAuthenticated()) { // if auth data is present $request.headers['auth-id'] = authFactory.getAuthData().username; // add user name $request.headers['auth-token'] = authFactory.getAuthData().authToken; // and auth token to headers } } return $request; }, responseError: function (res) { // on responses with an erroneous status if (res.status === 401 && !angular.isUndefined(res.data.authCode)) { // unauthorized with auth code var authCode = res.data.authCode; if (authCode !== "-1") { // auth code -1 meaning no valid auth data var authFactory = $injector.get('authFactory'); authFactory.logout(); // remove auth data cookie } } return res; } }; return authHttpInterceptor; }); //Add interceptor to chain: d2sApp.config(function ($httpProvider) { $httpProvider.interceptors.push('authHttpInterceptor'); }); })();import React from "react"; import ReactDOM from "react-dom"; import { GameContextProvider } from "./context/GameContext"; import "./Game"; import UI from "./UI"; function App() { return ( <GameContextProvider> <UI /> </GameContextProvider> ); } ReactDOM.render(<App />, document.getElementById("root")); <filename>config/rollup.config.aliases.js import memory from 'rollup-plugin-memory'; import rollupConfig from './rollup.config'; export default Object.assign({}, rollupConfig, { plugins: [ memory({ path: 'src/preact', contents: `import { h } from './preact';export * from './preact';export { h as createElement };` }), ...rollupConfig.plugins.slice(1) ] }); /** * Patterns logging - minimal logging framework * * Copyright 2012 <NAME>.V. */ // source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError( "Function.prototype.bind - what is trying to be bound is not callable" ); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function() {}, fBound = function() { return fToBind.apply( this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)) ); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } var root, // root logger instance writer; // writer instance, used to output log entries var Level = { DEBUG: 10, INFO: 20, WARN: 30, ERROR: 40, FATAL: 50 }; function IEConsoleWriter() {} IEConsoleWriter.prototype = { output: function(log_name, level, messages) { // console.log will magically appear in IE8 when the user opens the // F12 Developer Tools, so we have to test for it every time. if ( typeof window.console === "undefined" || typeof console.log === "undefined" ) return; if (log_name) messages.unshift(log_name + ":"); var message = messages.join(" "); // Under some conditions console.log will be available but the // other functions are missing. if (typeof console.info === undefined) { var level_name; if (level <= Level.DEBUG) level_name = "DEBUG"; else if (level <= Level.INFO) level_name = "INFO"; else if (level <= Level.WARN) level_name = "WARN"; else if (level <= Level.ERROR) level_name = "ERROR"; else level_name = "FATAL"; console.log("[" + level_name + "] " + message); } else { if (level <= Level.DEBUG) { // console.debug exists but is deprecated message = "[DEBUG] " + message; console.log(message); } else if (level <= Level.INFO) console.info(message); else if (level <= Level.WARN) console.warn(message); else console.error(message); } } }; function ConsoleWriter() {} ConsoleWriter.prototype = { output: function(log_name, level, messages) { if (log_name) messages.unshift(log_name + ":"); if (level <= Level.DEBUG) { // console.debug exists but is deprecated messages.unshift("[DEBUG]"); console.log.apply(console, messages); } else if (level <= Level.INFO) console.info.apply(console, messages); else if (level <= Level.WARN) console.warn.apply(console, messages); else console.error.apply(console, messages); } }; function Logger(name, parent) { this._loggers = {}; this.name = name || ""; this._parent = parent || null; if (!parent) { this._enabled = true; this._level = Level.WARN; } } Logger.prototype = { getLogger: function(name) { var path = name.split("."), root = this, route = this.name ? [this.name] : []; while (path.length) { var entry = path.shift(); route.push(entry); if (!(entry in root._loggers)) root._loggers[entry] = new Logger(route.join("."), root); root = root._loggers[entry]; } return root; }, _getFlag: function(flag) { var context = this; flag = "_" + flag; while (context !== null) { if (context[flag] !== undefined) return context[flag]; context = context._parent; } return null; }, setEnabled: function(state) { this._enabled = !!state; }, isEnabled: function() { this._getFlag("enabled"); }, setLevel: function(level) { if (typeof level === "number") this._level = level; else if (typeof level === "string") { level = level.toUpperCase(); if (level in Level) this._level = Level[level]; } }, getLevel: function() { return this._getFlag("level"); }, log: function(level, messages) { if ( !messages.length || !this._getFlag("enabled") || level < this._getFlag("level") ) return; messages = Array.prototype.slice.call(messages); writer.output(this.name, level, messages); }, debug: function() { this.log(Level.DEBUG, arguments); }, info: function() { this.log(Level.INFO, arguments); }, warn: function() { this.log(Level.WARN, arguments); }, error: function() { this.log(Level.ERROR, arguments); }, fatal: function() { this.log(Level.FATAL, arguments); } }; function getWriter() { return writer; } function setWriter(w) { writer = w; } if ( !window.console || !window.console.log || typeof window.console.log.apply !== "function" ) { setWriter(new IEConsoleWriter()); } else { setWriter(new ConsoleWriter()); } root = new Logger(); var logconfig = /loglevel(|-[^=]+)=([^&]+)/g, match; while ((match = logconfig.exec(window.location.search)) !== null) { var logger = match[1] === "" ? root : root.getLogger(match[1].slice(1)); logger.setLevel(match[2].toUpperCase()); } var api = { Level: Level, getLogger: root.getLogger.bind(root), setEnabled: root.setEnabled.bind(root), isEnabled: root.isEnabled.bind(root), setLevel: root.setLevel.bind(root), getLevel: root.getLevel.bind(root), debug: root.debug.bind(root), info: root.info.bind(root), warn: root.warn.bind(root), error: root.error.bind(root), fatal: root.fatal.bind(root), getWriter: getWriter, setWriter: setWriter }; export default api; <reponame>coyotte508/honeycomb export function hexes(chai) { const Assertion = chai.Assertion Assertion.addMethod('hexes', function(expected) { const actual = this._obj const coordinates = hex => `{ x: ${hex.x}, y: ${hex.y} }` this.assert( expected.every(hex => actual.includes(hex)), 'expected #{this} to contain #{exp}, but got #{act}', 'expected #{this} to not contain #{exp}', expected.map(coordinates).join(', '), actual.map(coordinates).join(', ') ) }) } import angular from 'angular'; const SERVICE_NAME = 'NoCallOptionsResourcesService'; /** * Resource service for the noCallOptions API * @param $http * @param UrlBuilderService - Service to create url * @param ExceptionService - throws an API error * @returns {{isAuthenticated: (function()), createOauth: (function()), createAuth: (function())}} */ function noCallOptionsService($http, UrlBuilderService, ExceptionService) { const resources = { noCallOptions: (customerId, orderId) => `customers/${customerId}/orders/${orderId}/callOptions`, }; return { /** * API method for updating a customer's measurements. * @param customerID * @param orderID * @param apiVer * @returns {*} */ getNoCallOptions: (customerID, orderID, apiVersion = '1.0.0') => { if (angular.isDefined(customerID) && angular.isDefined(orderID)) { const req = { method: 'PUT', url: UrlBuilderService.createUrl(resources.noCallOptions(customerID, orderID)), headers: { 'Accept-Version': apiVersion, }, }; const promise = $http(req); return promise; } return ExceptionService.throwAPIError(SERVICE_NAME, 'getNoCallOptions - missing params'); }, }; } noCallOptionsService.$inject = ['$http', 'UrlBuilderService', 'ExceptionService']; export { SERVICE_NAME as noCallOptionsServiceName, noCallOptionsService }; Bridge.define("System.Collections.Generic.List$1.Enumerator", function (T) { return { inherits: [System.Collections.Generic.IEnumerator$1(T),System.Collections.IEnumerator], $kind: "struct", statics: { methods: { getDefaultValue: function () { return new (System.Collections.Generic.List$1.Enumerator(T))(); } } }, fields: { list: null, index: 0, version: 0, current: Bridge.getDefaultValue(T) }, props: { Current: { get: function () { return this.current; } }, System$Collections$IEnumerator$Current: { get: function () { if (this.index === 0 || this.index === ((this.list._size + 1) | 0)) { throw new System.InvalidOperationException(); } return this.Current; } } }, alias: [ "dispose", "System$IDisposable$dispose", "moveNext", "System$Collections$IEnumerator$moveNext", "Current", ["System$Collections$Generic$IEnumerator$1$" + Bridge.getTypeAlias(T) + "$Current$1", "System$Collections$Generic$IEnumerator$1$Current$1"] ], ctors: { $ctor1: function (list) { this.$initialize(); this.list = list; this.index = 0; this.version = list._version; this.current = Bridge.getDefaultValue(T); }, ctor: function () { this.$initialize(); } }, methods: { dispose: function () { }, moveNext: function () { var localList = this.list; if (this.version === localList._version && ((this.index >>> 0) < (localList._size >>> 0))) { this.current = localList._items[System.Array.index(this.index, localList._items)]; this.index = (this.index + 1) | 0; return true; } return this.moveNextRare(); }, moveNextRare: function () { if (this.version !== this.list._version) { throw new System.InvalidOperationException(); } this.index = (this.list._size + 1) | 0; this.current = Bridge.getDefaultValue(T); return false; }, System$Collections$IEnumerator$reset: function () { if (this.version !== this.list._version) { throw new System.InvalidOperationException(); } this.index = 0; this.current = Bridge.getDefaultValue(T); }, getHashCode: function () { var h = Bridge.addHash([3788985113, this.list, this.index, this.version, this.current]); return h; }, equals: function (o) { if (!Bridge.is(o, System.Collections.Generic.List$1.Enumerator(T))) { return false; } return Bridge.equals(this.list, o.list) && Bridge.equals(this.index, o.index) && Bridge.equals(this.version, o.version) && Bridge.equals(this.current, o.current); }, $clone: function (to) { var s = to || new (System.Collections.Generic.List$1.Enumerator(T))(); s.list = this.list; s.index = this.index; s.version = this.version; s.current = this.current; return s; } } }; }); import notify from 'osg/notify'; import Texture from 'osg/Texture'; import ShadowTexture from 'osgShadow/ShadowTexture'; import Uniform from 'osg/Uniform'; import utils from 'osg/utils'; import { vec2 } from 'osg/glMatrix'; /** * ShadowTexture Attribute encapsulate Texture webgl object * with Shadow specificities (no need of texcoord,fragtexcoord) * trigger hash change when changing texture precision from float to byt * shadowSettings.js header for param explanations * @class ShadowTextureAtlas * @inherits TextureAttribute */ var ShadowTextureAtlas = function() { Texture.call(this); this._uniforms = {}; this._lightNumberArray = []; // default for a valid cloneType this._viewMatrices = []; this._projection = []; this._depthRanges = []; this._mapSizes = []; this._renderSize = vec2.create(); this._dirtyHash = true; this._hash = ''; }; ShadowTextureAtlas.uniforms = {}; /** @lends Texture.prototype */ utils.createPrototypeStateAttribute( ShadowTextureAtlas, utils.objectInherit(Texture.prototype, { cloneType: function() { return new ShadowTextureAtlas(); }, getLightNumberArray: function() { return this._lightNumberArray; }, hasLightNumber: function(lightNum) { return this._lightNumberArray.indexOf(lightNum) !== -1; }, setLightNumberArray: function(lightNumberArray) { this._lightNumberArray = lightNumberArray; this._dirtyHash = true; }, getUniformName: function(lightNumber, name) { var prefix = 'Shadow_' + this.getType() + lightNumber.toString(); return 'u' + prefix + '_' + name; }, setInternalFormatType: function(value) { Texture.prototype.setInternalFormatType.call(this, value); this._dirtyHash = true; }, createUniforms: function(lightNumber, uniforms) { uniforms['ViewRight_' + lightNumber] = Uniform.createFloat4( this.getUniformName(lightNumber, 'viewRight') ); uniforms['ViewUp_' + lightNumber] = Uniform.createFloat4( this.getUniformName(lightNumber, 'viewUp') ); uniforms['ViewLook_' + lightNumber] = Uniform.createFloat4( this.getUniformName(lightNumber, 'viewLook') ); uniforms['Projection_' + lightNumber] = Uniform.createFloat3( this.getUniformName(lightNumber, 'projection') ); uniforms['DepthRange_' + lightNumber] = Uniform.createFloat2( this.getUniformName(lightNumber, 'depthRange') ); uniforms['MapSize_' + lightNumber] = Uniform.createFloat4( this.getUniformName(lightNumber, 'mapSize') ); uniforms['RenderSize_' + lightNumber] = uniforms['RenderSize']; }, getOrCreateUniforms: function(unit) { // uniform are once per CLASS attribute, not per instance var obj = ShadowTextureAtlas; notify.assert(unit !== undefined || this._lightNumberArray.length !== 0); if (obj.uniforms[unit] !== undefined) { return obj.uniforms[unit]; } var uniforms = (obj.uniforms[unit] = {}); // shadowmap texture size used for texel space which is viewport independant var renderSizeUniform = Uniform.createFloat2(this.getUniformName(0, 'renderSize')); uniforms['RenderSize'] = renderSizeUniform; for (var i = 0, l = this._lightNumberArray.length; i < l; i++) { this.createUniforms(this._lightNumberArray[i], uniforms); } // Dual Uniform of texture, needs: // - Sampler (type of texture) // - Int (texture unit) // tells Shader Program where to find it var name = 'Texture' + unit; var uniform = Uniform.createInt1(unit, name); uniforms[name] = uniform; return obj.uniforms[unit]; }, setViewMatrix: function(lightNumber, viewMatrix) { this._viewMatrices[lightNumber] = viewMatrix; }, setProjection: function(lightNumber, projection) { this._projection[lightNumber] = projection; }, setDepthRange: function(lighNumber, depthRange) { this._depthRanges[lighNumber] = depthRange; }, setLightShadowMapSize: function(lightNumber, dimension) { this._mapSizes[lightNumber] = dimension; }, apply: function(state, texUnit) { // Texture stuff: call parent class method Texture.prototype.apply.call(this, state, texUnit); if (this._lightNumberArray.length === 0) { return; } // update Uniforms var uniformMap = this.getOrCreateUniforms(texUnit); for (var i = 0, l = this._lightNumberArray.length; i < l; i++) { var lightNumber = this._lightNumberArray[i]; if (!uniformMap['ViewRight_' + lightNumber]) { // enable disable uniforms and yet using getOrCreate this.createUniforms(lightNumber, uniformMap); } ShadowTexture.prototype._updateViewMatrixUniforms.call( this, this._viewMatrices[lightNumber], uniformMap['ViewRight_' + lightNumber], uniformMap['ViewUp_' + lightNumber], uniformMap['ViewLook_' + lightNumber] ); uniformMap['Projection_' + lightNumber].setFloat3(this._projection[lightNumber]); uniformMap['DepthRange_' + lightNumber].setFloat2(this._depthRanges[lightNumber]); uniformMap['MapSize_' + lightNumber].setFloat4(this._mapSizes[lightNumber]); } uniformMap['RenderSize'].setFloat2(this._renderSize); }, setTextureSize: function(w, h) { this._renderSize[0] = 1.0 / w; this._renderSize[1] = 1.0 / h; Texture.prototype.setTextureSize.call(this, w, h); this.dirty(); }, _computeInternalHash: function() { var hash = this.getTypeMember(); for (var i = 0, l = this._lightNumberArray.length; i < l; i++) { hash += '_' + this._lightNumberArray[i]; } hash += '_' + this._type; return hash; }, getHash: function() { if (!this._dirtyHash) return this._hash; this._hash = this._computeInternalHash(); this._dirtyHash = false; return this._hash; } }), 'osgShadow', 'ShadowTextureAtlas' ); export default ShadowTextureAtlas; <filename>src/js/app/components/results/SearchResult.js import React, {Component} from 'react'; import GeneResult from './GeneResult'; import DiseaseResult from './DiseaseResult'; import {classNames as cx} from 'classnames'; export default class SearchResult extends Component { render() { const { term, diseases, genes, organisms, selectedOrganism, setOrganismFilter, fetchOrtholog } = this.props; if (diseases.length == 0 && genes.length == 0) { return null; } else { return ( <div> <h3>Search results for <mark>{term}</mark></h3> <ul className="nav nav-tabs" role="tablist"> <li role="presentation" className="active"> <a href="#genes" aria-controls="genes" role="tab" data-toggle="tab">Genes ({genes.length})</a> </li> <li role="presentation"> <a href="#diseases" aria-controls="diseases" role="tab" data-toggle="tab">Diseases ({diseases.length})</a> </li> </ul> <div className="tab-content"> <div role="tabpanel" className="tab-pane active" id="genes"> <GeneResult genes={genes} organisms={organisms} selectedOrganism={selectedOrganism} setOrganismFilter={setOrganismFilter} fetchOrtholog={fetchOrtholog} /> </div> <div role="tabpanel" className="tab-pane" id="diseases"> <DiseaseResult diseases={diseases} fetchOrtholog={fetchOrtholog} /> </div> </div> </div> ); } return null; } } <filename>src/helpers/makeArrayOfDateStr.js import * as dateFns from "date-fns"; const makeArrayOfDateStr = (arrayDateObj) => { let arrayOfDateStr = []; arrayDateObj.forEach(dateObj => { let day = dateFns.getDate(dateObj); if (day < 10) { day = `0${day}`; } let month = dateFns.getMonth(dateObj) + 1; let year = dateFns.getYear(dateObj); let dateStr = `${year}-${month}-${day}`; arrayOfDateStr.push(dateStr) }) return arrayOfDateStr } export default makeArrayOfDateStr; <reponame>wushuaixing/assets-monitor-react<filename>src/utils/api/monitor-info/epaper.js // 监控信息->电子报 import s from 'service'; const epaper = { // POST收藏 attention: params => s.post('/yc/monitor/electronicNewspaper/follow', params).then(res => res.data), // GET导出 exportList: '/yc/monitor/electronicNewspaper/export', // POST列表 list: params => s.post('/yc/monitor/electronicNewspaper/list', params).then(res => res.data), // POST数量 listCount: params => s.post('/yc/monitor/electronicNewspaper/listCount', params).then(res => res.data), // POST已读 全部已读 read: params => s.post('/yc/monitor/electronicNewspaper/markRead', params).then(res => res.data), // POST取消收藏 unAttention: params => s.post('/yc/monitor/electronicNewspaper/unfollow', params).then(res => res.data), }; export default epaper; <filename>frontend/n2o-framework/src/actions/createActionHelper.js import { createAction } from 'redux-actions'; /** * дефолтный мэппер пэйлоада * @param payload * @param meta */ function defaultPayload(payload = {}, meta = {}) { return payload; } /** * дефолтный мэппер меты * @param payload * @param meta */ function defaultMeta(payload = {}, meta = {}) { return meta; } /** * Обертка вокруг createAction с дефолтными мапперами * @param type * @param payloadFunc * @param metaFunc */ export default function createActionHelper( type, payloadFunc = defaultPayload, metaFunc = defaultMeta ) { return createAction(type, payloadFunc, metaFunc); } <reponame>CodePrometheus/Starry-LearnVue3 import Mock from "mockjs"; import user from "./user"; import live from "./live"; import promotion from "./promotion"; import mall from "./mall"; Mock.setup({ timeout: "300-500", }); // user Mock.mock("/api/user/login", "post", user.login); Mock.mock("/api/user/about", "get", user.getUser); // mall Mock.mock("/api/mall/category", "get", mall.getCategory); Mock.mock(/\/api\/mall\/category\/\d*/, "get", mall.getOneCategory); Mock.mock("/api/mall/banners", "get", mall.getBanners); Mock.mock("/api/mall/brand-videos", "get", mall.getBrandVideos); Mock.mock(/\/api\/mall\/brand-videos\/\d*/, "get", mall.getBrandVideosById); Mock.mock("/api/mall/recommend-category", "get", mall.getRecommendCategory); Mock.mock("/api/mall/promotions", "get", mall.getPromotions); Mock.mock("/api/mall/hot-category", "get", mall.getHotCategory); Mock.mock(/\/api\/mall\/goods\/\d*/, "get", mall.getCategoryGoods); Mock.mock(/\/api\/mall\/goods-id\/\d*/, "get", mall.getGoodsId); Mock.mock(/\/api\/mall\/goods-detail\/\d*/, "get", mall.getGoodsDetailById); // live Mock.mock("/api/live/lives", "get", live.getLives); Mock.mock(/\/api\/live\/lives\/\d*/, "get", live.getLivesById); // promotion 相关 Mock.mock("/api/promotion/hot-goods", "get", promotion.getHotGoods); Mock.mock( /\/api\/promotion\/fastbuy-goods\/.*/, "get", promotion.getFastBuyGoods ); Mock.mock(/\/api\/promotion\/goods\/\w*/, "get", promotion.getPromotionGoods); Mock.mock("/api/promotion/jjyz-goods", "get", promotion.getJjyzGoods); Mock.mock("/api/promotion/ydftx-goods", "get", promotion.getYdftxGoods); Mock.mock("/api/promotion/qdpsfx-goods", "get", promotion.getQdpsfxGoods); export default Mock; <gh_stars>0 const apiKey = 'ab2025ac279e4bc8957a173ec2ead44b' const recipe_search_endpoint = `https://api.spoonacular.com/recipes/search?apiKey=${apiKey}&query={keywords}&number=1` const recipe_info_endpoint = `https://api.spoonacular.com/recipes/{id}/information?apiKey=${apiKey}` const getRecipe = () => { let keywords = document.querySelector('#terms').value if (!keywords.trim()) return keywords = keywords.replace(' ', '+').trim() const search_endpoint = recipe_search_endpoint.replace('{keywords}', keywords) document.querySelector('#load').style.display = 'inline' document.querySelector('#recipe').style.display = 'none' initializeRecipe() document.querySelector('#error').textContent = '' fetch(search_endpoint) .then((response) => response.json()) .then((data) => { if (data.results.length === 0) { errorRtn('Data not found. Check spelling and retry.') return } const info_endpoint = recipe_info_endpoint.replace( '{id}', data.results[0].id ) fetch(info_endpoint) .then((response) => response.json()) .then((data) => { document.querySelector('#load').style.display = 'none' showData(data) }) .catch(() => errorRtn('Error fetching data')) }) .catch(() => errorRtn('Error fetching data')) } const errorRtn = (msg) => { document.querySelector('#load').style.display = 'none' const ele = document.querySelector('#error') ele.textContent = msg } const initializeRecipe = () => { const recipe = document.querySelector('#recipe') const image = recipe.querySelector('img') if (image) { recipe.removeChild(image) } recipe.querySelector('#title').textContent = '' recipe.querySelector('#serves span').textContent = '' recipe.querySelector('#readyin span').textContent = '' recipe.querySelector('#list').innerHTML = '' recipe.querySelector('#instr').textContent = '' } const showData = (data) => { document.querySelector('#recipe').style.display = 'block' document.querySelector('h2').textContent = data.title const image = document.createElement('img') image.style.width = '250px' image.style.height = '250px' image.alt = 'Image not available' image.src = data.image const info = document.querySelector('#info') document.querySelector('#recipe').insertBefore(image, info) document.querySelector('#serves span').textContent = data.servings document.querySelector('#readyin span').textContent = data.readyInMinutes + ' minutes' const list = document.querySelector('#list') data.extendedIngredients.forEach((ingr) => { const li = document.createElement('li') li.textContent = ingr.original list.appendChild(li) }) document.querySelector('#instr').textContent = data.instructions } document.querySelector('#find').addEventListener('click', getRecipe) import { flattenNames } from './lib/flatten'; import expand from './lib/expand'; import Accessors from './accessors/registry'; import findInput from './lib/find-input'; import { A } from '@ember/array'; export default function(scope, attrs) { let result = {}; flattenNames(attrs).forEach( (key) => result[key] = Accessors.read( findInput(A([scope, key]).compact().join('.')) ) ); return expand(result); } <gh_stars>10-100 // // Copyright (c) 2018 Cisco Systems // Licensed under the MIT License // /** * Auto-answer call example, filtering out not registered origins * * Integrator role: not supported, as tested as of June 2018 * - OK: registering a feedback for /Call * - KO: accepting an incoming call * * */ // // Connect to the device // const jsxapi = require('jsxapi'); // Check args if (!process.env.JSXAPI_DEVICE_URL || !process.env.JSXAPI_USERNAME) { console.log("Please specify info to connect to your device as JSXAPI_DEVICE_URL, JSXAPI_USERNAME, JSXAPI_PASSWORD env variables"); console.log("Bash example: JSXAPI_DEVICE_URL='ssh://192.168.1.32' JSXAPI_USERNAME='integrator' JSXAPI_PASSWORD='<PASSWORD>' node example.js"); process.exit(1); } // Empty passwords are supported const password = process.env.JSXAPI_PASSWORD ? process.env.JSXAPI_PASSWORD : ""; // Connect to the device console.log("connecting to your device..."); const xapi = jsxapi.connect(process.env.JSXAPI_DEVICE_URL, { username: process.env.JSXAPI_USERNAME, password: password }); xapi.on('error', (err) => { console.error(`connexion failed: ${err}, exiting`); process.exit(1); }); // // Code logic // xapi.on('ready', () => { console.log("connexion successful"); // Listen to call events xapi.status .on('Call', (call) => { switch (call.Status) { case "Ringing": console.log(`NEW call: ${call.id}`); // Filter depending the origin of the call if ((call.Direction == "Incoming") && (call.Protocol == "Spark") && (call.DisplayName == "Salon")) { // Accept incoming call console.log(`Accepting incoming call: ${call.id}`); xapi.command('Call Accept', { CallId: call.id }); } return; case "Connected": console.log(`Connected call: ${call.id}`); return; case "Disconnecting": console.log(`Disconnecting call: ${call.id}`); return; case "Idle": console.log(`Idle call: ${call.id}`); return; default: //console.log("DEBUG: ignoring event"); return; } }) }); /* eslint-disable no-console */ var strFuncController = require("../").string; strFuncController.enableAll(); console.log("\n"); console.log("5".padLeft("0", 5)); console.log(""); /* 00005 */ console.log("FUN!".padLeft("-", 9)); console.log(""); /* -----FUN! */ console.log("1".padRight(",000", 13)); console.log(""); /* 1,000,000,000 */ console.log("fix".prepend("pre")); console.log(""); /* prefix */ console.log(JSON.stringify({ "name": "Fred", "role": "Superhero", "mascot": "Platypus" }, null, 2).indent(4)); console.log(""); /* { "name": "Fred", "role": "Superhero", "mascot": "Platypus" } */ <gh_stars>10-100 import { expect } from 'chai'; import { mount, shallowMount } from '@vue/test-utils'; import localVue from '../local-vue'; import VxpLabel from '../../../src/components/VxpLabel'; import VxpDropDown from '../../../src/components/VxpDropDown'; import VxpDatePicker from '../../../src/components/VxpDatePicker'; describe('VxpDatePicker Test.', () => { const dayPlaceholder = 'Test Day'; const monthPlaceholder = 'Test Month'; const yearPlaceholder = 'Test Year'; const disabled = false; const day = 6; const month = 1; const year = 2015; const label = 'Birth Date'; const errors = ['error line 1', 'error line 2', 'error line 3']; let wrapper; wrapper = shallowMount(VxpDatePicker, { propsData: { day, month, year, dayPlaceholder, monthPlaceholder, yearPlaceholder, disabled, label, errors, }, localVue, sync: false, }); describe('The component received given props correctly.', () => { it(`should given dayPlaceHolder property is equal to ${dayPlaceholder}.`, () => { expect(wrapper.props().dayPlaceholder).to.equal(dayPlaceholder); }); it(`should given monthPlaceholder property is equal to ${monthPlaceholder}.`, () => { expect(wrapper.props().monthPlaceholder).to.equal(monthPlaceholder); }); it(`should given yearPlaceholder property is equal to ${yearPlaceholder}.`, () => { expect(wrapper.props().yearPlaceholder).to.equal(yearPlaceholder); }); it(`should disabled property is equal to ${disabled}.`, () => { expect(wrapper.props().disabled).to.equal(disabled); }); it(`should given day property is equal to ${day}.`, () => { expect(wrapper.props().day).to.equal(day); }); it(`should given month property is equal to ${month}.`, () => { expect(wrapper.props().month).to.equal(month); }); it(`should given year property is equal to ${year}.`, () => { expect(wrapper.props().year).to.equal(year); }); it(`should given label property is equal to ${label}.`, () => { expect(wrapper.props().label).to.equal(label); }); it(`should given errors property is equal to ${errors}.`, () => { expect(wrapper.props().errors).to.equal(errors); }); }); describe('Find child elements of progress bar.', () => { it('should be three dropdown inside the layout.', () => { const childCount = wrapper.findAll(VxpDropDown).length; expect(childCount).to.equal(3); }); it('should be one label inside the layout.', () => { const childCount = wrapper.findAll(VxpLabel).length; expect(childCount).to.equal(4); }); }); describe('Listen to events and Changing Props.', () => { it(`should assert event has been emitted one time`, done => { const wrapper1 = mount(VxpDatePicker, { sync: false }, localVue); wrapper1.setProps({ day: 7, month: 3, year: 2016 }); wrapper1.vm.$nextTick(() => { expect(wrapper1.emitted('dateChange').length).to.equal(1); done(); }); }); }); describe('Check days, months count.', () => { const wrapper2 = mount(VxpDatePicker, { propsData: { day, month, year, }, sync: false, localVue, }); it(`should days length should be 31`, () => { expect( wrapper2 .findAll(VxpDropDown) .at(0) .findAll('li').length, ).to.equal(31); }); it(`should months length should be 12`, () => { expect( wrapper2 .findAll(VxpDropDown) .at(1) .findAll('li').length, ).to.equal(12); }); }); describe('February should 28 days. ', () => { it(`should assert event has been emitted one time`, done => { const wrapper3 = mount(VxpDatePicker, { propsData: { day, month, year, }, sync: false, localVue, }); expect( wrapper3 .findAll(VxpDropDown) .at(0) .findAll('li').length, ).to.equal(31); wrapper3.setProps({ month: 2 }); wrapper3.vm.$nextTick(() => { expect( wrapper3 .findAll(VxpDropDown) .at(0) .findAll('li').length, ).to.equal(28); done(); }); }); }); }); <reponame>emily-nilson/resource-watch<filename>components/dashboards/table/td/NameTD.js import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'routes'; function NameTD(props) { const { row, value, index } = props; return ( <td key={index} className="main"> <Link route="admin_dashboards_detail" params={{ tab: 'dashboards', id: row.id }}> <a>{value}</a> </Link> </td> ); } NameTD.propTypes = { row: PropTypes.object, value: PropTypes.string, index: PropTypes.string }; export default NameTD; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getGlobalCssLoader = getGlobalCssLoader; var _client = require("./client"); var _fileResolve = require("./file-resolve"); function getGlobalCssLoader(ctx, postcss, preProcessors = []) { const loaders = []; if (ctx.isClient) { // Add appropriate development more or production mode style // loader loaders.push((0, _client).getClientStyleLoader({ isDevelopment: ctx.isDevelopment, assetPrefix: ctx.assetPrefix })); } // Resolve CSS `@import`s and `url()`s loaders.push({ loader: require.resolve('../../../../loaders/css-loader/src'), options: { postcss, importLoaders: 1 + preProcessors.length, // Next.js controls CSS Modules eligibility: modules: false, url: (url, resourcePath)=>(0, _fileResolve).cssFileResolve(url, resourcePath, ctx.experimental.urlImports) , import: (url, _, resourcePath)=>(0, _fileResolve).cssFileResolve(url, resourcePath, ctx.experimental.urlImports) } }); // Compile CSS loaders.push({ loader: require.resolve('../../../../loaders/postcss-loader/src'), options: { postcss } }); loaders.push(// Webpack loaders run like a stack, so we need to reverse the natural // order of preprocessors. ...preProcessors.slice().reverse()); return loaders; } //# sourceMappingURL=global.js.mapimport React from 'react'; import './Switcher.stories.css'; import { Switcher } from './Switcher'; import { Box } from '../Box/Box'; export default { title: 'Components/Layout Components/Switcher', component: Switcher, }; const BasicTemplate = (args) => ( <Switcher {...args}> <div> <Box padding="2rem" /> <Box padding="2rem" /> <Box padding="2rem" /> </div> </Switcher> ); export const Basic = BasicTemplate.bind({}); Basic.args = { threshold: `30rem` }; var searchData= [ ['ns',['ns',['../namespacefasttext.html#a1ba04862fd670674501ccacc936e1952af01a37d157918910f2035b2af81ea4e1',1,'fasttext']]] ]; (function(){ 'use strict'; const moment = require('moment'); let lastTime; exports.run = (action, seconds, actionIfWaiting) => { if (!seconds) { seconds = 60; } let secondsDiff = moment().diff(lastTime, 'seconds'); if (lastTime && secondsDiff < seconds) { actionIfWaiting(); return; } action(); lastTime = moment(); }; })();const identify = require('./identify'); module.exports = { identify, }; <filename>src/commands/Tracking/Track.js 'use strict'; const Command = require('../../models/Command.js'); const CommonFunctions = require('../../CommonFunctions.js'); const { eventTypes, rewardTypes, opts } = require('../../resources/trackables.json'); /** * Track an event or item */ class Track extends Command { constructor(bot) { super(bot, 'settings.track', 'track'); this.usages = [ { description: 'Show tracking command for tracking events', parameters: [] }, { description: 'Track an event or events', parameters: ['event(s) to track'] }, ]; this.regex = new RegExp(`^${this.call}(?:\\s+(cetus\\.day\\.[0-1]?[0-9]?[0-9]|cetus\\.night\\.[0-1]?[0-9]?[0-9]|${eventTypes.join('|')}|${rewardTypes.join('|')}|${opts.join('|')})*)?(?:\\s+in\\s+((?:\\<\\#)?\\d+(?:\\>)?|here))?`, 'i'); this.requiresAuth = true; } async run(message) { const unsplitItems = CommonFunctions.getEventsOrItems(message); const roomId = new RegExp('(?:\\<\\#)?\\d{15,}(?:\\>)?|here', 'ig'); if (unsplitItems.length === 0) { return this.failure(message); } const trackables = CommonFunctions.trackablesFromParameters(unsplitItems); if (!(trackables.events.length || trackables.items.length)) { return this.failure(message); } trackables.events = trackables.events .filter((elem, pos) => trackables.events.indexOf(elem) === pos); trackables.items = trackables.items .filter((elem, pos) => trackables.items.indexOf(elem) === pos); const channelParam = message.strippedContent.match(roomId) ? message.strippedContent.match(roomId)[0].trim().replace(/<|>|#/ig, '') : undefined; const channel = CommonFunctions.getChannel(channelParam, message); const results = []; if (trackables.events.length) { results.push(this.settings.trackEventTypes(channel, trackables.events)); } if (trackables.items.length) { results.push(this.settings.trackItems(channel, trackables.items)); } Promise.all(results); this.messageManager.notifySettingsChange(message, true, true); return this.messageManager.statuses.SUCCESS; } async failure(message) { const prefix = await this.settings.getGuildSetting(message.guild, 'prefix'); this.messageManager.embed( message, CommonFunctions.getTrackInstructionEmbed(message, prefix, this.call), true, true, ); return this.messageManager.statuses.FAILURE; } } module.exports = Track; const numero1 = 20; const numero2 = "40"; // Coercion implicita console.log(numero1 + numero2); // Coerción explicita console.log(Number(numero2)); console.log(numero1.toString()); /* * Copyright 2017 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['lbphaserutil', 'lbutil', 'lbgeometry', 'lbphysics', 'phaser', 'lbphysicslink'], function(LBPhaser, LBUtil, LBGeometry, LBPhysics, Phaser, LBPhysicsLink) { 'use strict'; /** * Manages linking a {@link https://photonstorm.github.io/phaser-ce/Phaser.Physics.P2.Body|Phaser.Physics.P2.Body} and a {@link module:LBPhysics.RigidBody}, updating * the position/rotation of the rigid body from the P2 body and applying the forces * from the rigid body to the P2 body. This also supports displaying an arrow representing * the resultant force on rigid bodies. * @constructor * @extends module:LBPhysicsLink.Link * @param {LBPhaser.Env} phaserEnv The Phaser environment we're running under. * @returns {LBPhaser.P2Link} */ LBPhaser.P2Link = function(phaserEnv) { LBPhysicsLink.Link.call(this); this.phaserEnv = phaserEnv; this.game = phaserEnv.game; this.game.physics.startSystem(Phaser.Physics.P2JS); this.game.physics.p2.world.applyGravity = false; this.fixedObjectCollisionGroup = this.game.physics.p2.createCollisionGroup(); this.dynamicObjectCollisionGroup = this.game.physics.p2.createCollisionGroup(); }; LBPhaser.P2Link.prototype = Object.create(LBPhysicsLink.Link.prototype); LBPhaser.P2Link.prototype.constructor = LBPhaser.P2Link; LBPhaser.P2Link.prototype.addFixedPhaserObject = function(object) { this.game.physics.p2.enable(object); object.body.allowGravity = false; object.body.static = true; object.body.setCollisionGroup(this.fixedObjectCollisionGroup); object.body.collides(this.dynamicObjectCollisionGroup); return this; }; // @inheritdoc.. LBPhaser.P2Link.prototype.addRigidBody = function(rigidBody, data) { LBPhysicsLink.Link.prototype.addRigidBody.call(this, rigidBody); var p2Body = LBPhaser.P2Link.createP2BodyFromData(this.game, data.phaser); rigidBody._lbP2Body = p2Body; p2Body.damping = 0; if (rigidBody.xyOutline && (rigidBody.xyOutline.length > 2)) { var xy = []; var env = this.phaserEnv; var iBegin; var iEnd; var iDelta; // We're presuming the outline is convex... if (LBGeometry.whichSideOfLine(rigidBody.xyOutline[0], rigidBody.xyOutline[1], rigidBody.xyOutline[2]) === LBGeometry.LINE_SIDE_RIGHT) { // Going clockwise... iBegin = rigidBody.xyOutline.length - 1; iEnd = -1; iDelta = -1; } else { iBegin = 0; iEnd = rigidBody.xyOutline.length; iDelta = 1; } for (var i = iBegin; i !== iEnd; i += iDelta) { xy.push([rigidBody.xyOutline[i].x, rigidBody.xyOutline[i].y]); } var convex = new p2.Convex({ vertices: xy }); p2Body.clearShapes(); var offsetX = env.toPixelsX(convex.centerOfMass[0]); var offsetY = env.toPixelsY(convex.centerOfMass[1]); var sprite = p2Body.sprite; if (sprite) { offsetX += (0.5 - sprite.anchor.x) * sprite.width; offsetY += (0.5 - sprite.anchor.y) * sprite.height; } p2Body.addShape(convex, offsetX, offsetY); } p2Body.setCollisionGroup(this.dynamicObjectCollisionGroup); p2Body.collides(this.fixedObjectCollisionGroup); p2Body.x = this.phaserEnv.toPixelsX(rigidBody.obj3D.position.x); p2Body.y = this.phaserEnv.toPixelsY(rigidBody.obj3D.position.y); p2Body.rotation = this.phaserEnv.toPixelsRotationRad(rigidBody.obj3D.rotation.z); }; // @inheritdoc.. LBPhaser.P2Link.prototype._rigidBodyRemoved = function(rigidBody) { if (rigidBody._lbP2Body) { rigidBody._lbP2Body.world.removeBody(rigidBody._lbP2Body); rigidBody._lbP2Body = undefined; } }; // @inheritdoc.. LBPhaser.P2Link.prototype.timeStep = function() { var p2 = this.game.physics.p2; return p2.useElapsedTime ? p2.game.time.physicsElapsed : p2.frameRate; }; // @inheritdoc.. LBPhaser.P2Link.prototype.update = function(dt) { this._updateFromP2(); this._applyToP2(dt); ++this.updateCount; }; /** * Called by {@link LBPhaser.P2Link#update} to update the rigid bodies from the P2 bodies. * This updates the position and orientation of the rigid body from that of the linked P2 body. * @protected * @returns {LBPhaser.P2Link} this. */ LBPhaser.P2Link.prototype._updateFromP2 = function() { this.rigidBodies.forEach(this._updateRigidBodyFromPhaser, this); return this; }; LBPhaser.P2Link.prototype._updateRigidBodyFromPhaser = function(rigidBody) { var p2Body = rigidBody._lbP2Body; if (p2Body) { // Phaser negates the coordinate system between P2 and {@link PHaser.Physics.P2}. rigidBody.setXYZ(this.phaserEnv.fromPixelsX(p2Body.x), this.phaserEnv.fromPixelsY(p2Body.y), rigidBody.obj3D.position.z); rigidBody.setZRotationRad(this.phaserEnv.ySign * p2Body.rotation, true); rigidBody.obj3D.updateMatrixWorld(); } }; /** * Called by {@link LBPhaser.P2Link#update} to apply the forces from the rigid bodies to the P2 bodies. * @protected * @param {Number} dt The simulation time step. * @returns {LBPhaser.P2Link} this. */ LBPhaser.P2Link.prototype._applyToP2 = function(dt) { this.rigidBodies.forEach(this._updateP2BodyFromLB3, { 'p2link': this, 'dt': dt }); return this; }; LBPhaser.P2Link.prototype._updateP2BodyFromLB3 = function(rigidBody) { var p2Body = rigidBody._lbP2Body; if (!p2Body) { return; } rigidBody.updateForces(this.dt); var resultant = rigidBody.getResultant(true); var mass = rigidBody.getTotalMass(); if ((mass > 0) && (mass !== p2Body.mass)) { p2Body.mass = mass; p2Body.invMass = 1./mass; p2Body.data.mass = mass; p2Body.data.invMass = p2Body.invMass; } var inertia = LBPhysics.getInertiaZZ(rigidBody.momentInertia); if ((inertia > 0) && (inertia !== p2Body.inertia)) { p2Body.inertia = inertia; p2Body.invInertia = 1./inertia; p2Body.data.inertia = p2Body.inertia; p2Body.data.invInertia = p2Body.invInertia; p2Body.data.updateSolveMassProperties(); } var x = resultant.applPoint.x - rigidBody.obj3D.position.x; var y = resultant.applPoint.y - rigidBody.obj3D.position.y; var pEnv = this.p2link.phaserEnv; resultant.force.y *= pEnv.ySign; // Phaser negates the coordinate system between P2 and {@link PHaser.Physics.P2}. p2Body.applyForce([-resultant.force.x, -resultant.force.y], pEnv.toPixelsX(x), pEnv.toPixelsY(y)); }; /** * Creates and loads a {https://photonstorm.github.io/phaser-ce/Phaser.Physics.P2.Body|Phaser.Physics.P2.Body} object based on properties in a data object. * @param {Phaser.Game} game The game to which the body will belong. * @param {object} data The data object. * @returns {Phaser.Physics.P2.Body} The created/loaded body. */ LBPhaser.P2Link.createP2BodyFromData = function(game, data) { var sprite = LBPhaser.PhysicsView.createSpriteFromData(game, data.sprite); // Enabling P2 physics resets the anchor to 0.5, 0.5 var anchorX = sprite.anchor.x; var anchorY = sprite.anchor.y; sprite.game.physics.enable(sprite, Phaser.Physics.P2JS); sprite.anchor.x = anchorX; sprite.anchor.y = anchorY; sprite.body.collideWorldBounds = true; var p2Body = sprite.body; p2Body.mass = data.mass || p2Body.mass; p2Body.clearShapes(); p2Body.addRectangle(sprite.width, sprite.height, (0.5 - anchorX) * sprite.width, (0.5 - anchorY) * sprite.height); LBUtil.copyCommonProperties(p2Body, data.p2Body, function(val) { return val !== 'sprite'; }); return p2Body; }; /** * Helper that retrieves the P2 body associated with a rigid body object. * @param {module:LBPhysics.RigidBody} object The rigid body object. * @returns {Phaser.Physics.P2.Body} The P2 body, undefined if none assigned. */ LBPhaser.P2Link.getP2Body = function(object) { return object._lbP2Body; }; return LBPhaser; });<reponame>joseprio/incremental-js-identifier<filename>incremental-js-identifier.test.js 'use strict'; const incrementalJsIdentifier = require('./incremental-js-identifier'); test('identifier is incremental', () => { const idGenerator = incrementalJsIdentifier(); expect(idGenerator()).toBe('A'); expect(idGenerator()).toBe('B'); expect(idGenerator()).toBe('C'); }); test('incrementing valid characters works as expected', () => { const idGenerator = incrementalJsIdentifier({validFirstCharacters: 'AB', validCharacters: 'CDE'}); expect(idGenerator()).toBe('A'); expect(idGenerator()).toBe('B'); expect(idGenerator()).toBe('AC'); expect(idGenerator()).toBe('BC'); expect(idGenerator()).toBe('AD'); expect(idGenerator()).toBe('BD'); expect(idGenerator()).toBe('AE'); expect(idGenerator()).toBe('BE'); expect(idGenerator()).toBe('ACC'); expect(idGenerator()).toBe('BCC'); expect(idGenerator()).toBe('ADC'); expect(idGenerator()).toBe('BDC'); expect(idGenerator()).toBe('AEC'); expect(idGenerator()).toBe('BEC'); expect(idGenerator()).toBe('ACD'); expect(idGenerator()).toBe('BCD'); expect(idGenerator()).toBe('ADD'); expect(idGenerator()).toBe('BDD'); expect(idGenerator()).toBe('AED'); expect(idGenerator()).toBe('BED'); expect(idGenerator()).toBe('ACE'); expect(idGenerator()).toBe('BCE'); expect(idGenerator()).toBe('ADE'); expect(idGenerator()).toBe('BDE'); expect(idGenerator()).toBe('AEE'); expect(idGenerator()).toBe('BEE'); expect(idGenerator()).toBe('ACCC'); }); test('arbitrary and generated identifiers work well together', () => { const idGenerator = incrementalJsIdentifier({validFirstCharacters: 'AB', validCharacters: 'CDE'}); expect(() => idGenerator(-1)).toThrow(); expect(idGenerator()).toBe('A'); expect(idGenerator()).toBe('B'); expect(() => idGenerator(0)).toThrow(); // Arbitrary ID already exists expect(() => idGenerator(1)).toThrow(); // Arbitrary ID already exists expect(idGenerator(2)).toBe('AC'); // Arbitrary ID expect(() => idGenerator(2)).toThrow(); // Arbitrary ID already exists expect(idGenerator()).toBe('BC'); // Generated ID will skip one });<filename>webpack.config.js const path = require('path'); const webpack = require('webpack'); const config = { // Use this way for running the tests // entry: path.resolve(__dirname, 'src/index.js'), // Use this way when generating the UMD for browser testing entry: path.resolve(__dirname, 'index.js'), devServer: { hot: true, inline: true, port: 3000, historyApiFallback: true, }, output: { path: path.resolve(__dirname, 'dist'), libraryTarget: 'umd', library: 'NewsWrapper' }, module: { loaders: [{ test: /\.js?$/, exclude: /node_modules/, loader: "babel-loader", query: { presets: ['react', 'es2015', 'stage-0'] } }] } } module.exports = config;import http from 'k6/http'; export default function () { const res = http.get('<3scale api stagin url from example curl request here>'); } /*** Imports ***/ /* Library imports */ import React, { Component } from "react"; import PropTypes from 'prop-types'; /* Component imports */ import CardContent from "./components/CardContent/CardContent"; /* Style imports */ import './styles.css'; import Header from "../../components/Header/Header"; import NavBar from "../../components/NavBar/NavBar"; /*** End Imports ***/ class Home extends Component { constructor(props) { super(props); this.state = { } this.homeData = { simpleCards: [ { id: 1, iconUrl: "", title: "Blog Post", description: "400 - 500 words", cardType: 1 }, { id: 2, iconUrl: "", title: "White Paper", description: "2500 - 3000 words", cardType: 1 }, { id: 3, iconUrl: "", title: "Website content", description: "250 - 300 words", cardType: 1 }, { id: 4, iconUrl: "", title: "Press Release", description: "350 - 450 words", cardType: 1 }, { id: 5, iconUrl: "", title: "Product Description", description: "400 - 500 words", cardType: 1 }, { id: 6, iconUrl: "", title: "Social Media", description: "2500 - 3000 words", cardType: 1 }, { id: 7, iconUrl: "", title: "Story Writing", description: "250 - 300 words", cardType: 1 }, { id: 8, iconUrl: "", title: "Video Script", description: "350 - 450 words", cardType: 1 }, { id: 9, iconUrl: "", title: "Newsletter", description: "250 - 300 words", cardType: 1 }, { id: 10, iconUrl: "", title: "Brochure Content", description: "350 - 450 words", cardType: 1 }, { id: 11, iconUrl: "", title: "Custom Content", description: "250 - 300 words", cardType: 1 }, { id: 12, iconUrl: "", title: "Contest", description: "350 - 450 words", cardType: 1 } ], specialCards: [ { id: 5, iconUrl: "", title: "Order from Template", description: "You can get orders from templates", cardType: 2 }, { id: 6, iconUrl: "", title: "Order Via Template", description: "Its usefull when giving bulk orders", cardType: 2 } ] } } componentWillMount() { } componentDidMount() { } // Server calls // helper function // listeners // views to be rendered getCardView = (arrayList, rowSize) => { let CardsView = [] let count = 1; let temp = {} let row = 0; for (let item of arrayList) { if (count % rowSize === 0) { temp[row].push(<CardContent {...item} />) row++; } else { if (temp[row]) { temp[row].push(<CardContent {...item} />) } else { temp[row] = []; temp[row].push(<CardContent {...item} />) } } count++; } for (var key in temp) { if (temp.hasOwnProperty(key)) { CardsView.push( <div style={{ display: "flex" }}> {temp[key]} </div> ) } } return CardsView } //finally render render() { return ( <div className="home-page-container"> <Header /> <NavBar orientation="vertical" /> <div className="content-container"> {this.getCardView(this.homeData.simpleCards, 4)} {this.getCardView(this.homeData.specialCards, 2)} </div> </div> ); } } /** * all prop types which can be passed to this component */ Home.propTypes = { }; /** * Only if default initialization is required * Default props value for this component */ Home.defaultProps = { }; export default Home;<gh_stars>0 import ReactDOM from 'react-dom' import React, { Component } from 'react' import axios from 'axios' import SideArticle from './SideArticle' class SideContainer extends React.Component { render() { return( <div className="side-container"> <h2 className="container-title">Featured Press</h2> <div className="featured-list"> <SideArticle/> <SideArticle/> <SideArticle/> <SideArticle/> <SideArticle/> <SideArticle/> <SideArticle/> </div> </div> ); } } export default SideContainer;const Discord = require("discord.js"); const client = new Discord.Client(); const ayarlar = require("./ayarlar.json"); const chalk = require("chalk"); const moment = require("moment"); var Jimp = require("jimp"); const { Client, Util } = require("discord.js"); const weather = require("weather-js"); const fs = require("fs"); const db = require("quick.db"); const http = require("http"); const express = require("express"); require("./util/eventLoader")(client); const path = require("path"); const request = require("request"); const snekfetch = require("snekfetch"); const queue = new Map(); const YouTube = require("simple-youtube-api"); const ytdl = require("ytdl-core"); const app = express(); app.get("/", (request, response) => { console.log(Date.now() + " Ping tamamdır."); response.sendStatus(200); }); app.listen(process.env.PORT); setInterval(() => { http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`); }, 280000); var prefix = ayarlar.prefix; const log = message => { console.log(`${message}`); }; client.commands = new Discord.Collection(); client.aliases = new Discord.Collection(); fs.readdir("./komutlar/", (err, files) => { if (err) console.error(err); log(`${files.length} komut yüklenecek.`); files.forEach(f => { let props = require(`./komutlar/${f}`); log(`Yüklenen komut: ${props.help.name}.`); client.commands.set(props.help.name, props); props.conf.aliases.forEach(alias => { client.aliases.set(alias, props.help.name); }); }); }); client.reload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./komutlar/${command}`)]; let cmd = require(`./komutlar/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.load = command => { return new Promise((resolve, reject) => { try { let cmd = require(`./komutlar/${command}`); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.unload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./komutlar/${command}`)]; let cmd = require(`./komutlar/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); resolve(); } catch (e) { reject(e); } }); }; client.elevation = message => { if (!message.guild) { return; } let permlvl = 0; if (message.member.hasPermission("BAN_MEMBERS")) permlvl = 2; if (message.member.hasPermission("ADMINISTRATOR")) permlvl = 3; if (message.author.id === ayarlar.sahip) permlvl = 4; return permlvl; }; var regToken = /[\<KEY>; // client.on('debug', e => { // console.log(chalk.bgBlue.green(e.replace(regToken, 'that was redacted'))); // }); client.on("warn", e => { console.log(chalk.bgYellow(e.replace(regToken, "that was redacted"))); }); client.on("error", e => { console.log(chalk.bgRed(e.replace(regToken, "that was redacted"))); }); client.on("guildMemberAdd", async member => { let member2 = member.user // let author = "₣│Ƨƛ│JaimiTR<PASSWORD>" let zaman = new Date().getTime() - member2.createdAt.getTime() var cfxzaman = []; if(zaman < 604800000) member.addRole("754022574907850773") if(zaman > 604800000) member.addRole("754022574064926731") }) client.on('guildMemberAdd', async member => { let member2 = member.user // let author = "₣│Ƨƛ│JaimiTR#8142" let zaman = new Date().getTime() - member2.createdAt.getTime() var cfxzaman = []; if(zaman < 604800000) { cfxzaman = `<a:onaysiz:754619840614105180> Şüpheli` } else { cfxzaman = `<a:onay:752086532617142405> Güvenli` } const katilim = moment.utc(member.guild.members.get(member.id).user.createdAt).format('`YYYY [Yılında] MMMM [Ayında] dddd [Gününde] (DD/MM/YYYY)`') .replace("Monday", `Pazartesi`) .replace("Tuesday", `Salı`) .replace("Wednesday", `Çarşamba`) .replace("Thursday", `Perşembe`) .replace("Friday", `Cuma`) .replace("Saturday", `Cumartesi`) .replace("Sunday", `Pazar`) .replace("January", `Ocak`) .replace("February", `Şubat`) .replace("March", `Mart`) .replace("April", `Nisan`) .replace("May", `Mayıs`) .replace("June", `Haziran`) .replace("July", `Temmuz`) .replace("August", `Ağustos`) .replace("September", `Eylül`) .replace("October", `Ekim`) .replace("November", `Kasım`) .replace("December", `Aralık`) client.channels.get("753532353112178749").send(`<a:guvenli:752086516523728927> Hoşgeldin ${member} Seninle Birlikte **${member.guild.memberCount}** Kişiyiz. \n\n<a:guvenli:752086516523728927> Müsait Olduğunuzda Teyit Kanallarına Gelerek Teyit Verebilirsiniz! \n\n<a:guvenli:752086516523728927> Tagımızı Alarak Bize Destek Olabilirsin. \`𒄬\` \n\n<a:guvenli:752086516523728927> Hesabının Açılış Tarihi ${katilim} \n\n<a:guvenli:752086516523728927> Bu Hesap **${cfxzaman}** Gözüküyor.`, new Discord.Attachment('https://cdn.discordapp.com/attachments/753532353112178749/755895787581472808/b28433c392959f923ff0d736cd89dcbd.gif')) }) client.on("message", async message => { let prefix = ayarlar.prefix if(message.content.toLowerCase() === `${prefix}fake-çık`) { client.emit( "guildMemberRemove", message.member || (await message.guild.fetchMember(message.author)) ); message.channel.send("Fake çıktın.") } }); client.on("message", async message => { let prefix = ayarlar.prefix if(message.content.toLowerCase() === `${prefix}fake`) { client.emit( "guildMemberAdd", message.member || (await message.guild.fetchMember(message.author)) ); message.channel.send("Fake girdin") } }); client.login(ayarlar.token); AFRAME.registerComponent('scene', { schema: { sceneNum: {default: 0} }, init: function () { this.el.addEventListener('click', clickFunction); function clickFunction() { var data = this.components.scene.data; var sky = document.querySelector('a-sky'); var scene = scenelist[data.sceneNum]; sky.setAttribute('src', scene.sceneref); sky.setAttribute('phi-start', scene.sceneyrot); //Set sky yaw. loadPois(scene.tooltips, data); loadPorts(scene.transports); // Clear captions document.querySelector("#captions").setAttribute('value', ""); clearInterval(sceneTimerControl); captionIndex = 0; // Stop old sound document.querySelector('#sceneNarration').components.sound.stopSound(); globalScene = data.sceneNum; globalData = data; if (scenePlayed[data.sceneNum] != true) { scenePlayed[data.sceneNum] = true; startNarration(scene.narration); loadCaptions(); } } function startNarration(narration){ var narrScene = document.querySelector('#sceneNarration'); narrScene.setAttribute('sound', { 'src': narration }); narrScene.components.sound.playSound(); console.log("THIS IS NARRATION " + narration); } function loadPois(tooltips, data){ var circles = document.querySelectorAll('a-circle'); var scene = scenelist[data.sceneNum]; var pois = document.querySelectorAll('.vidpanel'); //this is printing out an empty list console.log(pois); for (var i=0; i< circles.length; i++){ //circle positions circles[i].setAttribute('position', tooltips[i].pos); circles[i].setAttribute(('scale'), tooltips[i].scale); //vid pannel positions pois[i].setAttribute('position', scene.tooltips[i].vidPos); pois[i].setAttribute('material', { src: tooltips[i].videoAsset }); pois[i].setAttribute('sound', { src: tooltips[i].poiNarration }); } } function loadPorts(transports) { var boxes = document.querySelectorAll('.model'); for (var i=0; i< boxes.length; i++){ //I think we can reuse the same two/three box port objects and just set their data appropriately. //As long as we have exactly the same number of boxes in every scene, we need no additional logic. boxes[i].setAttribute('position', transports[i].pos); boxes[i].setAttribute('scene', "sceneNum: " + transports[i].sceneIndex); } } function loadCaptions(){ var text = document.querySelector("#captions"); var scene = scenelist[globalData.sceneNum]; // If at end of list if (scene.captions.length == captionIndex) { text.setAttribute('value', ""); clearInterval(sceneTimerControl); captionIndex = 0; return; } text.setAttribute('value', scene.captions[captionIndex].text); clearInterval(sceneTimerControl); sceneTimerControl = setInterval(loadCaptions, scene.captions[captionIndex].time); ++captionIndex; } } });// Generated by CoffeeScript 1.6.2 /* doT Express Master of Ceremonies @author <NAME> <<EMAIL>> @license http://opensource.org/licenses/MIT */ (function() { var Defines, clone, curOptions, curPath, defaults, doT, e, fs, html, mergeObjects, path, renderFile, workingPaths; fs = require("fs"); path = require("path"); doT = require("dot"); try { html = require("html"); } catch (_error) { e = _error; if (e.code !== "MODULE_NOT_FOUND") { throw e; } } workingPaths = []; curOptions = null; curPath = null; defaults = { fileExtension: "def", cacheManager: { get: function(filename) { return this.cache[filename]; }, set: function(filename, data) { return this.cache[filename] = data; }, cache: {} }, options: { templateSettings: { cache: true } } }; if (html) { defaults.options.prettyPrint = { indent_char: " ", indent_size: 1 }; } Defines = (function() { function Defines() {} Defines.prototype.include = function(filename, vars) { var cacheManager, err, returnValue, template, usingCache, _ref; returnValue = void 0; filename = filename.replace('~', (_ref = defaults.app) != null ? _ref.get("views" || '~') : void 0); if (!path.extname(filename)) { filename = "" + filename + "." + defaults.fileExtension; } if (curPath) { filename = path.resolve(curPath, filename); } curPath = path.dirname(filename); workingPaths.push(curPath); vars = typeof vars !== "object" ? curOptions : mergeObjects(true, clone(curOptions), vars); try { usingCache = curOptions.templateSettings.cache; if (usingCache) { cacheManager = defaults.cacheManager; template = cacheManager.get(filename); } if (typeof template === "undefined") { template = fs.readFileSync(filename, "utf8"); } if (usingCache) { cacheManager.set(filename, template); } returnValue = doT.template(template, curOptions.templateSettings, this)(vars); workingPaths.pop(); } catch (_error) { err = _error; workingPaths.pop(); curPath = workingPaths.length ? workingPaths[workingPaths.length - 1] : null; throw err; } curPath = workingPaths.length ? workingPaths[workingPaths.length - 1] : null; return returnValue; }; return Defines; })(); mergeObjects = function() { var arg, argLength, deep, i, key, start, t, target, val, valIsArray, valIsObject, _i, _j; target = arguments[0]; if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; start = 2; } else { deep = false; target = arguments[0] || {}; start = 1; } argLength = arguments.length; if (deep) { for (i = _i = start; start <= argLength ? _i <= argLength : _i >= argLength; i = start <= argLength ? ++_i : --_i) { arg = arguments[i]; if (!arg) { continue; } for (key in arg) { val = arg[key]; if (target === val) { continue; } t = target[key]; valIsArray = val instanceof Array; valIsObject = !valIsArray && typeof val === "object"; if (val && (valIsObject || valIsArray)) { if (valIsArray) { val = val.slice(0); } if (key in target) { if (valIsArray) { t = t instanceof Array ? t : []; } else { t = typeof t === "object" ? t : {}; } target[key] = mergeObjects(true, (valIsArray ? [] : {}), t, val); } else { target[key] = val; } } else if (val !== void 0) { target[key] = val; } } } } else { for (i = _j = start; start <= argLength ? _j <= argLength : _j >= argLength; i = start <= argLength ? ++_j : --_j) { arg = arguments[i]; for (key in arg) { val = arg[key]; if (val !== void 0) { target[key] = val; } } } } return target; }; clone = function(obj) { return mergeObjects(true, {}, obj); }; renderFile = function(filename, options, fn) { var def, err; if (typeof options === "function") { fn = options; options = {}; } if (typeof fn !== "function") { fn = (function() {}); } curOptions = mergeObjects(true, options, defaults.options, { templateSettings: doT.templateSettings }); def = new Defines(); try { if (html && curOptions.pretty) { return fn(null, html.prettyPrint(def.include(filename), curOptions.prettyPrint || {})); } else { return fn(null, def.include(filename)); } } catch (_error) { err = _error; return fn(err); } }; exports.__express = renderFile; exports.renderFile = renderFile; exports.Defines = Defines; exports.init = function(settings) { defaults = mergeObjects(true, defaults, settings); return exports; }; }).call(this); <reponame>kimlombard/kinetic24<filename>node_modules/@riotjs/compiler/src/utils/is-empty-sourcemap.js /** * True if the sourcemap has no mappings, it is empty * @param {Object} map - sourcemap json * @returns {boolean} true if empty */ export default function isEmptySourcemap(map) { return !map || !map.mappings || !map.mappings.length }'use strict'; angular.module('login', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/login', { templateUrl: 'login/login.html', controller: 'LoginController' }); }]) .controller('LoginController', ['$scope','$firebaseAuth','FirebaseService', '$window', '$location', 'User', function($scope, $firebaseSimpleLogin, FirebaseService, $window, $location, User) { $scope.SignIn = function(event) { var ref = new Firebase("https://yrma.firebaseio.com"); ref.authWithOAuthPopup("google", function(error, authData) { if (error) { Materialize.toast('Login Failed! </br> Please contact your administrator.', 3000); console.log("Login Failed!", error); } else { var thisuser = { "id":authData.google.id, "email":authData.google.email, "name":authData.google.displayName, "imageUrl":authData.google.profileImageURL }; FirebaseService.updateOrCreate("user", thisuser).then(function(response){ Materialize.toast("Hi " +response.name + "! </br> Welcome back!", 3000); User.set(response); $location.url('/profile'); }); } }, {scope: "email"} ); // Auth Logic will be here } }]); import React, {Component} from 'react'; import { connect } from 'react-redux'; import {bindActionCreators} from 'redux'; import { closeModal, selectUser, submitEditedUser, getRoles } from '../store/actions'; import AutoSuggestion from './AutoSuggestion'; import SelectTags from './SelectTags'; import { getRoleArray } from '../utility/helper'; class EditUserModal extends Component { constructor(props){ super(props); this.closeModal = this.closeModal.bind(this); this.selectRole = this.selectRole.bind(this); this.inputChangehandler = this.inputChangehandler.bind(this); this.updateEditedUser = this.updateEditedUser.bind(this); this.handleChange = this.handleChange.bind(this); this.getDefaultRole = this.getDefaultRole.bind(this); this.roles = []; } componentDidMount(){ this.props.getRoles(); } closeModal(){ this.props.closeModal('edituser'); } inputChangehandler(){ //debugger let fname = this.refs.fname.value; let lname = this.refs.lname.value; let email = this.refs.email.value; let user = {id: this.props.user.id, fistName: fname, lastName: lname, email, roles: this.roles}; this.props.selectUser(user); } updateEditedUser(){ this.props.submitEditedUser(); setTimeout(()=>{ this.closeModal(); }, 200) } selectRole(value, option){ debugger; document.querySelector('.ant-select-search__field').setAttribute("id", value); document.querySelector('.ant-select-search__field').value = 'test'; console.log(value); } getRolesArray(data){ debugger return data; } /*handleChange(value, option) { debugger console.log(`Selected:: ${value}`); console.log(`id:: ${option[0].key}`) }*/ handleChange(value, option) { let roles = this.props.roles.roles; this.roles = getRoleArray(roles, value); } getDefaultRole(roles){ let defaultRoles = roles.map((item)=>{ return item.name; }) return defaultRoles; } render() { if( !this.props.user ) { return null } else return( <div className={"modal-container " + (this.props.isModalOpen ? 'show' : 'hide')}> <div className="backdrop"></div> <div className="modal-dialog"> <div className={ "modal" }> <i className="fa fa-close close-modal-icon" onClick={this.closeModal}/> <div className="modal-header"><h3 className="modal-title">Edit User</h3><hr className="hr"/></div> <div className="modal-body"> <div className="form-group"> <label className="form-label">First Name</label> <input type="text" className="form-control" onChange={this.inputChangehandler} value={this.props.user.firstName} ref="fname"/> </div> <div className="form-group"> <label className="form-label">Last Name</label> <input type="text" className="form-control" onChange={this.inputChangehandler} value={this.props.user.lastName} ref="lname"/> </div> <div className="form-group"> <label className="form-label">Email</label> <input type="text" className="form-control" onChange={this.inputChangehandler} value={this.props.user.email} ref="email"/> </div> <div className="form-group"> <label className="form-label">Roles</label> <AutoSuggestion placeholder="Add New Role" selectRole={this.selectRole} data={this.props.roles.roles} /> </div> <SelectTags data={this.props.roles.roles} defaultData={ this.getDefaultRole(this.props.user.roles) } handleChange={this.handleChange} /> </div> <div className="modal-footer"> <hr className="hr"/> <button className="btn btn-default" onClick={this.closeModal}>Cancel</button>    <button className="btn btn-success" onClick={this.updateEditedUser}>Update</button> </div> </div> </div> </div> ) } } //export default EditUserModal; function mapDispatchToProps(dispatch){ return { closeModal: bindActionCreators(closeModal, dispatch), selectUser: bindActionCreators(selectUser, dispatch), submitEditedUser: bindActionCreators(submitEditedUser, dispatch), getRoles: bindActionCreators(getRoles, dispatch) } } function mapStateToProps(state){ console.log('state>>>>>> :: ',state); return{ isModalOpen: state.modal.editUserModal, user: state.selectedUser.user, roles: state.roles } } const _EditUserModal = connect(mapStateToProps, mapDispatchToProps )(EditUserModal); export default _EditUserModal;import http from '@/config/http' import BaseStore from '@/store/base-store' const options = { state: { layersTree: null }, getters: { layersTree (state) { return state.layersTree } }, mutations: { layersTree (state, payload) { state.layersTree = payload } }, actions: { layersTree ({commit}) { return http.get('categories/layers').then((response) => { commit('layersTree', response.data) }) } } } export default new BaseStore('categories', options) import React, { useState, useEffect } from "react"; import * as yup from "yup"; import axios from "axios"; import { useRouteMatch, Switch, Route } from "react-router-dom"; // creates new user const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/; const formSchema = yup.object().shape({ user_name: yup .string() .min(4, "4 characters minimum for user_name") .required("user_name required"), userName: yup .string() .min(5, "5 characters minimum for your user name") .required("user name required"), password: yup .string() .min(5, "password needs to be more than 5 characters long"), phone: yup.string().matches(phoneRegExp, "Phone number is not valid"), email: yup .string("@") .email("Valid Email needed") .required("must include email"), terms: yup.boolean().oneOf([true], "please validate you are human"), }); export default function RegisterForm() { const { path, url } = useRouteMatch(); const [userState, setUserState] = useState({ user_name: "", userName: "", password: "", phone: "", email: "", terms: false, }); const [errState, setErrState] = useState({ user_name: "", userName: "", password: "", phone: "", email: "", terms: "", }); const [buttonDisabled, setButtonDisabled] = useState(true); useEffect(() => { formSchema.isValid(userState).then((valid) => { setButtonDisabled(valid); }); }, [userState]); const validate = (e) => { let value = e.target.type === "checkbox" ? e.target.checked : e.target.value; yup .reach(formSchema, e.target.name) .validate(value) .then((valid) => { setErrState({ ...errState, [e.target.name]: "", }); }) .catch((err) => { setErrState({ ...errState, [e.target.name]: err.errors[0], }); }); }; const inputChange = (e) => { e.persist(); validate(e); let value = e.target.type === "checkbox" ? e.target.checked : e.target.value; setUserState({ ...userState, [e.target.name]: value }); }; const formSubmit = (e) => { e.preventDefault(); console.log("form submitted for review"); axios .post("http://localhost:9500/api/auth/register", userState) // .post("/auth/register", userState) .then((response) => console.log(response)) .catch((err) => console.log(err)); }; return ( <> <Switch> <Route path={`${path}/form-submited`}> <div className="SubmitedText"> <h4>Submited Form, you can now login in </h4> </div> </Route> <form onSubmit={formSubmit}> <ul> <label htmlFor="name"> <h4>User Name</h4> <div> <input id="user_name" type="user_name" name="user_name" placeholder="create your username" value={userState.user_name} onChange={inputChange} /> </div> {errState.user_name.length > 6 ? ( <p className="error">{errState.user_name}</p> ) : null} </label> <label htmlFor="password"> <h4>Password</h4> <div> <input id="password" type="password" name="password" placeholder="Password" value={userState.password} onChange={inputChange} /> </div> {errState.password.length > 6 ? ( <p className="error">{errState.password}</p> ) : null} </label> <label htmlFor="userName"> <h4>Your Name</h4> <div> <input id="userName" type="userName" name="userName" placeholder="Name here" value={userState.userName} onChange={inputChange} /> </div> {errState.userName.length > 5 ? ( <p className="error">{errState.userName}</p> ) : null} </label> <label htmlFor="phone"> <h4>phone</h4> <div> <input id="phone" type="phone" name="phone" placeholder="phone" value={userState.phone} onChange={inputChange} /> </div> {errState.phone.length > 6 ? ( <p className="error">{errState.phone}</p> ) : null} </label> <label htmlFor="email"> <h4>Email</h4> <div> <input id="email" type="email" name="email" placeholder="Email" value={userState.email} onChange={inputChange} /> </div> {errState.email.length > 0 ? ( <p className="error">{errState.email}</p> ) : null} </label> <label htmlFor="validate"> <div> Validate Here <input type="checkbox" id="terms" name="terms" checked={userState.terms} onChange={inputChange} /> </div> {errState.terms.length > 1 ? ( <p className="error">{errState.terms}</p> ) : null} </label> </ul> {/* <pre>{JSON.stringify(userState)}</pre> */} {/* <button onClick={validateChange} disabled={buttonDisabled}> Submit </button> */} <button type="submit" id="submit" name="submit" alert={"phone number or username taken"} disabled={!buttonDisabled} to={`${url}/form-submited`} > Submit </button> </form> </Switch> </> ); } import axios from "axios"; const axiosService = () => { let instance = axios.create(); // Set the Authorization token for any request instance.interceptors.request.use(function (config) { const token = localStorage.getItem("access_token"); config.headers.Authorization = token ? `Bearer ${token}` : ""; return config; }); return instance; }; export default axiosService(); <filename>.tmp/ember-transpiled/views/settings/users/user.js define("ghost/views/settings/users/user", ["exports"], function(__exports__) { "use strict"; var SettingsUserView = Ember.View.extend({ currentUser: Ember.computed.alias('controller.session.user'), isNotOwnProfile: Ember.computed('controller.user.id', 'currentUser.id', function () { return this.get('controller.user.id') !== this.get('currentUser.id'); }), isNotOwnersProfile: Ember.computed.not('controller.user.isOwner'), canAssignRoles: Ember.computed.or('currentUser.isAdmin', 'currentUser.isOwner'), canMakeOwner: Ember.computed.and('currentUser.isOwner', 'isNotOwnProfile', 'controller.user.isAdmin'), rolesDropdownIsVisible: Ember.computed.and('isNotOwnProfile', 'canAssignRoles', 'isNotOwnersProfile'), deleteUserActionIsVisible: Ember.computed('currentUser', 'canAssignRoles', 'controller.user', function () { if ((this.get('canAssignRoles') && this.get('isNotOwnProfile') && !this.get('controller.user.isOwner')) || (this.get('currentUser.isEditor') && (this.get('isNotOwnProfile') || this.get('controller.user.isAuthor')))) { return true; } }), userActionsAreVisible: Ember.computed.or('deleteUserActionIsVisible', 'canMakeOwner') }); __exports__["default"] = SettingsUserView; });/** * @jest-environment jsdom-global */ 'use strict'; const mockXHR = require('xhr-mock').default; const browserClient = require('../lib/browser/browser-client'); const constants = require('../lib/constants'); const tu = require('./test-utils'); const testSharedInterface = require('./test-shared-interface'); describe('shared interface tests', () => { testSharedInterface(browserClient); }); test('errors early if access token not provided', () => { tu.expectError( () => browserClient(), error => { expect(error.message).toMatch(/access token/); } ); }); // Note: there are discrepancies between the node progress events // and browser progress events. For now we are assuming // the discrepancies are not worth normalizing across these // two platforms as no one would be planning to use them // in unison. describe('test progress events', () => { let request; const { mockToken } = tu; afterEach(() => { mockXHR.teardown(); }); beforeEach(() => { mockXHR.setup(); const accessToken = mockToken(); const responseBody = { mockStyle: true }; // To mock the progress event // server needs to send the `Content-length` header // ref: https://github.com/jameslnewell/xhr-mock/tree/master/packages/xhr-mock#upload-progress mockXHR.get( `https://api.mapbox.com/styles/v1/mockuser/foo?access_token=${accessToken}`, { status: 200, headers: { 'Content-Length': JSON.stringify(responseBody).length, 'Content-Type': 'application/json; charset=utf-8' }, body: JSON.stringify(responseBody) } ); const client = browserClient({ accessToken }); request = client.createRequest({ method: 'GET', path: '/styles/v1/:ownerId/:styleId', params: { styleId: 'foo' } }); }); test('request.emitter should not emit uploadProgress events', () => { let progressUpload = []; request.emitter.on(constants.EVENT_PROGRESS_UPLOAD, resp => { progressUpload.push(Object.assign({}, resp)); }); return request.send().then(() => { expect(progressUpload).toEqual([]); }); }); test('request.emitter should emit downloadProgress events', () => { let progressDownload = []; request.emitter.on(constants.EVENT_PROGRESS_DOWNLOAD, resp => { progressDownload.push(Object.assign({}, resp)); }); return request.send().then(() => { expect(progressDownload).toEqual([ { percent: 100, total: 18, transferred: 18 } ]); }); }); }); <filename>Exercises/35.1_BizTime/routes/companies.js const express = require("express"); const router = new express.Router(); const db = require('../db'); const ExpressError = require("../ExpressError"); router.get("/", async function(req, res, next) { try{ let results = await db.query(`SELECT * FROM companies`); return res.json({companies:results.rows}); } catch(e) { return next(e); } }); router.get("/:code", async function(req, res, next) { try{ const {code} = req.params; let results = await db.query(`SELECT * FROM companies WHERE code = $1`, [code]); if(results.rows.length === 0) { throw new ExpressError(`Cant find company with code of ${code}`,404) } console.log(results.rows[0].code) let invoices = await db.query(`SELECT * FROM invoices WHERE comp_code = $1`, [results.rows[0].code]); results.rows[0].invoices = invoices.rows; return res.json({company:results.rows[0]}); } catch(e) { return next(e); } }); router.post('/', async (req,res,next) => { try { const { code,name,description } = req.body; const results = await db.query('INSERT INTO companies (code,name,description) VALUES ($1, $2, $3) RETURNING *',[code,name,description]) return res.json({company: results.rows[0]}); } catch(e) { return next(e) } }) router.put('/:oldCode', async (req,res,next) => { try { const {oldCode} = req.params; let company = await db.query(`SELECT * FROM companies WHERE code = $1`, [oldCode]); if(company.rows.length === 0) { throw new ExpressError(`Cant update company with code of ${oldCode}`,404) } const { code,name,description } = req.body; code = code || oldCode; name = name || company.name; description = description || company.description; const results = await db.query('UPDATE companies SET code=$1, name=$2, description=$3 WHERE code=$4 RETURNING code, name, description',[code,name,description,oldCode]) return res.json({company: results.rows[0]}) } catch(e) { return next(e); } }) router.delete('/:code', async (req,res,next) => { try { let company = await db.query(`SELECT * FROM companies WHERE code = $1`, [req.params.code]); if(company.rows.length === 0) { throw new ExpressError(`Cant find company with code of ${code}`,404) } db.query('DELETE FROM companies WHERE code=$1',[req.params.code]) return res.send({status:"deleted"}) } catch(e) { return next(e); } }) module.exports = router;/* VCO.Animate Basic animation ================================================== */ VCO.Animate = function(el, options) { var animation = new vcoanimate(el, options), webkit_timeout; /* // POSSIBLE ISSUE WITH WEBKIT FUTURE BUILDS var onWebKitTimeout = function() { animation.stop(true); } if (VCO.Browser.webkit) { webkit_timeout = setTimeout(function(){onWebKitTimeout()}, options.duration); } */ return animation; }; /* Based on: Morpheus https://github.com/ded/morpheus - (c) <NAME> 2011 License MIT ================================================== */ window.vcoanimate = (function() { var doc = document, win = window, perf = win.performance, perfNow = perf && (perf.now || perf.webkitNow || perf.msNow || perf.mozNow), now = perfNow ? function () { return perfNow.call(perf) } : function () { return +new Date() }, html = doc.documentElement, fixTs = false, // feature detected below thousand = 1000, rgbOhex = /^rgb\(|#/, relVal = /^([+\-])=([\d\.]+)/, numUnit = /^(?:[\+\-]=?)?\d+(?:\.\d+)?(%|in|cm|mm|em|ex|pt|pc|px)$/, rotate = /rotate\(((?:[+\-]=)?([\-\d\.]+))deg\)/, scale = /scale\(((?:[+\-]=)?([\d\.]+))\)/, skew = /skew\(((?:[+\-]=)?([\-\d\.]+))deg, ?((?:[+\-]=)?([\-\d\.]+))deg\)/, translate = /translate\(((?:[+\-]=)?([\-\d\.]+))px, ?((?:[+\-]=)?([\-\d\.]+))px\)/, // these elements do not require 'px' unitless = { lineHeight: 1, zoom: 1, zIndex: 1, opacity: 1, transform: 1}; // which property name does this browser use for transform var transform = function () { var styles = doc.createElement('a').style, props = ['webkitTransform', 'MozTransform', 'OTransform', 'msTransform', 'Transform'], i; for (i = 0; i < props.length; i++) { if (props[i] in styles) return props[i] }; }(); // does this browser support the opacity property? var opacity = function () { return typeof doc.createElement('a').style.opacity !== 'undefined' }(); // initial style is determined by the elements themselves var getStyle = doc.defaultView && doc.defaultView.getComputedStyle ? function (el, property) { property = property == 'transform' ? transform : property property = camelize(property) var value = null, computed = doc.defaultView.getComputedStyle(el, ''); computed && (value = computed[property]); return el.style[property] || value; } : html.currentStyle ? function (el, property) { property = camelize(property) if (property == 'opacity') { var val = 100 try { val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity } catch (e1) { try { val = el.filters('alpha').opacity } catch (e2) { } } return val / 100 } var value = el.currentStyle ? el.currentStyle[property] : null return el.style[property] || value } : function (el, property) { return el.style[camelize(property)] } var frame = function () { // native animation frames // http://webstuff.nfshost.com/anim-timing/Overview.html // http://dev.chromium.org/developers/design-documents/requestanimationframe-implementation return win.requestAnimationFrame || win.webkitRequestAnimationFrame || win.mozRequestAnimationFrame || win.msRequestAnimationFrame || win.oRequestAnimationFrame || function (callback) { win.setTimeout(function () { callback(+new Date()) }, 17) // when I was 17.. } }() var children = [] frame(function(timestamp) { // feature-detect if rAF and now() are of the same scale (epoch or high-res), // if not, we have to do a timestamp fix on each frame fixTs = timestamp > 1e12 != now() > 1e12 }) function has(array, elem, i) { if (Array.prototype.indexOf) return array.indexOf(elem) for (i = 0; i < array.length; ++i) { if (array[i] === elem) return i } } function render(timestamp) { var i, count = children.length // if we're using a high res timer, make sure timestamp is not the old epoch-based value. // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision if (perfNow && timestamp > 1e12) timestamp = now() if (fixTs) timestamp = now() for (i = count; i--;) { children[i](timestamp) } children.length && frame(render) } function live(f) { if (children.push(f) === 1) frame(render) } function die(f) { var rest, index = has(children, f) if (index >= 0) { rest = children.slice(index + 1) children.length = index children = children.concat(rest) } } function parseTransform(style, base) { var values = {}, m if (m = style.match(rotate)) values.rotate = by(m[1], base ? base.rotate : null) if (m = style.match(scale)) values.scale = by(m[1], base ? base.scale : null) if (m = style.match(skew)) {values.skewx = by(m[1], base ? base.skewx : null); values.skewy = by(m[3], base ? base.skewy : null)} if (m = style.match(translate)) {values.translatex = by(m[1], base ? base.translatex : null); values.translatey = by(m[3], base ? base.translatey : null)} return values } function formatTransform(v) { var s = '' if ('rotate' in v) s += 'rotate(' + v.rotate + 'deg) ' if ('scale' in v) s += 'scale(' + v.scale + ') ' if ('translatex' in v) s += 'translate(' + v.translatex + 'px,' + v.translatey + 'px) ' if ('skewx' in v) s += 'skew(' + v.skewx + 'deg,' + v.skewy + 'deg)' return s } function rgb(r, g, b) { return '#' + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1) } // convert rgb and short hex to long hex function toHex(c) { var m = c.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/) return (m ? rgb(m[1], m[2], m[3]) : c) .replace(/#(\w)(\w)(\w)$/, '#$1$1$2$2$3$3') // short skirt to long jacket } // change font-size => fontSize etc. function camelize(s) { return s.replace(/-(.)/g, function (m, m1) { return m1.toUpperCase() }) } // aren't we having it? function fun(f) { return typeof f == 'function' } function nativeTween(t) { // default to a pleasant-to-the-eye easeOut (like native animations) return Math.sin(t * Math.PI / 2) } /** * Core tween method that requests each frame * @param duration: time in milliseconds. defaults to 1000 * @param fn: tween frame callback function receiving 'position' * @param done {optional}: complete callback function * @param ease {optional}: easing method. defaults to easeOut * @param from {optional}: integer to start from * @param to {optional}: integer to end at * @returns method to stop the animation */ function tween(duration, fn, done, ease, from, to) { ease = fun(ease) ? ease : morpheus.easings[ease] || nativeTween var time = duration || thousand , self = this , diff = to - from , start = now() , stop = 0 , end = 0 function run(t) { var delta = t - start if (delta > time || stop) { to = isFinite(to) ? to : 1 stop ? end && fn(to) : fn(to) die(run) return done && done.apply(self) } // if you don't specify a 'to' you can use tween as a generic delta tweener // cool, eh? isFinite(to) ? fn((diff * ease(delta / time)) + from) : fn(ease(delta / time)) } live(run) return { stop: function (jump) { stop = 1 end = jump // jump to end of animation? if (!jump) done = null // remove callback if not jumping to end } } } /** * generic bezier method for animating x|y coordinates * minimum of 2 points required (start and end). * first point start, last point end * additional control points are optional (but why else would you use this anyway ;) * @param points: array containing control points [[0, 0], [100, 200], [200, 100]] * @param pos: current be(tween) position represented as float 0 - 1 * @return [x, y] */ function bezier(points, pos) { var n = points.length, r = [], i, j for (i = 0; i < n; ++i) { r[i] = [points[i][0], points[i][1]] } for (j = 1; j < n; ++j) { for (i = 0; i < n - j; ++i) { r[i][0] = (1 - pos) * r[i][0] + pos * r[parseInt(i + 1, 10)][0] r[i][1] = (1 - pos) * r[i][1] + pos * r[parseInt(i + 1, 10)][1] } } return [r[0][0], r[0][1]] } // this gets you the next hex in line according to a 'position' function nextColor(pos, start, finish) { var r = [], i, e, from, to for (i = 0; i < 6; i++) { from = Math.min(15, parseInt(start.charAt(i), 16)) to = Math.min(15, parseInt(finish.charAt(i), 16)) e = Math.floor((to - from) * pos + from) e = e > 15 ? 15 : e < 0 ? 0 : e r[i] = e.toString(16) } return '#' + r.join('') } // this retreives the frame value within a sequence function getTweenVal(pos, units, begin, end, k, i, v) { if (k == 'transform') { v = {} for (var t in begin[i][k]) { v[t] = (t in end[i][k]) ? Math.round(((end[i][k][t] - begin[i][k][t]) * pos + begin[i][k][t]) * thousand) / thousand : begin[i][k][t] } return v } else if (typeof begin[i][k] == 'string') { return nextColor(pos, begin[i][k], end[i][k]) } else { // round so we don't get crazy long floats v = Math.round(((end[i][k] - begin[i][k]) * pos + begin[i][k]) * thousand) / thousand // some css properties don't require a unit (like zIndex, lineHeight, opacity) if (!(k in unitless)) v += units[i][k] || 'px' return v } } // support for relative movement via '+=n' or '-=n' function by(val, start, m, r, i) { return (m = relVal.exec(val)) ? (i = parseFloat(m[2])) && (start + (m[1] == '+' ? 1 : -1) * i) : parseFloat(val) } /** * morpheus: * @param element(s): HTMLElement(s) * @param options: mixed bag between CSS Style properties & animation options * - {n} CSS properties|values * - value can be strings, integers, * - or callback function that receives element to be animated. method must return value to be tweened * - relative animations start with += or -= followed by integer * - duration: time in ms - defaults to 1000(ms) * - easing: a transition method - defaults to an 'easeOut' algorithm * - complete: a callback method for when all elements have finished * - bezier: array of arrays containing x|y coordinates that define the bezier points. defaults to none * - this may also be a function that receives element to be animated. it must return a value */ function morpheus(elements, options) { var els = elements ? (els = isFinite(elements.length) ? elements : [elements]) : [], i , complete = options.complete , duration = options.duration , ease = options.easing , points = options.bezier , begin = [] , end = [] , units = [] , bez = [] , originalLeft , originalTop if (points) { // remember the original values for top|left originalLeft = options.left; originalTop = options.top; delete options.right; delete options.bottom; delete options.left; delete options.top; } for (i = els.length; i--;) { // record beginning and end states to calculate positions begin[i] = {} end[i] = {} units[i] = {} // are we 'moving'? if (points) { var left = getStyle(els[i], 'left') , top = getStyle(els[i], 'top') , xy = [by(fun(originalLeft) ? originalLeft(els[i]) : originalLeft || 0, parseFloat(left)), by(fun(originalTop) ? originalTop(els[i]) : originalTop || 0, parseFloat(top))] bez[i] = fun(points) ? points(els[i], xy) : points bez[i].push(xy) bez[i].unshift([ parseInt(left, 10), parseInt(top, 10) ]) } for (var k in options) { switch (k) { case 'complete': case 'duration': case 'easing': case 'bezier': continue } var v = getStyle(els[i], k), unit , tmp = fun(options[k]) ? options[k](els[i]) : options[k] if (typeof tmp == 'string' && rgbOhex.test(tmp) && !rgbOhex.test(v)) { delete options[k]; // remove key :( continue; // cannot animate colors like 'orange' or 'transparent' // only #xxx, #xxxxxx, rgb(n,n,n) } begin[i][k] = k == 'transform' ? parseTransform(v) : typeof tmp == 'string' && rgbOhex.test(tmp) ? toHex(v).slice(1) : parseFloat(v) end[i][k] = k == 'transform' ? parseTransform(tmp, begin[i][k]) : typeof tmp == 'string' && tmp.charAt(0) == '#' ? toHex(tmp).slice(1) : by(tmp, parseFloat(v)); // record original unit (typeof tmp == 'string') && (unit = tmp.match(numUnit)) && (units[i][k] = unit[1]) } } // ONE TWEEN TO RULE THEM ALL return tween.apply(els, [duration, function (pos, v, xy) { // normally not a fan of optimizing for() loops, but we want something // fast for animating for (i = els.length; i--;) { if (points) { xy = bezier(bez[i], pos) els[i].style.left = xy[0] + 'px' els[i].style.top = xy[1] + 'px' } for (var k in options) { v = getTweenVal(pos, units, begin, end, k, i) k == 'transform' ? els[i].style[transform] = formatTransform(v) : k == 'opacity' && !opacity ? (els[i].style.filter = 'alpha(opacity=' + (v * 100) + ')') : (els[i].style[camelize(k)] = v) } } }, complete, ease]) } // expose useful methods morpheus.tween = tween morpheus.getStyle = getStyle morpheus.bezier = bezier morpheus.transform = transform morpheus.parseTransform = parseTransform morpheus.formatTransform = formatTransform morpheus.easings = {} return morpheus })(); <filename>src/controllers/messages-controllers.js<gh_stars>1-10 const Messages = require('../model.js'); // post messages const handlePostMessages = (req,res) => { const dbMessage = req.body Messages.create(dbMessage, (err, data) => { if(err) { res.status(500).json(err); } else { res.status(201).json(data) } }) } // get messages sync const handleGetMessages = (req,res) => { Messages.find((err, data) => { if(err) { res.status(500).json(err) } else { res.status(200).json(data) } }) } module.exports = { handleGetMessages, handlePostMessages }<filename>src/components/Hero.js import React from 'react'; import styled from 'styled-components'; import Img from 'gatsby-image'; import posed from 'react-pose'; import Typing from 'react-typing-animation'; import { useStaticQuery, graphql } from 'gatsby'; import { Link } from 'react-scroll'; /** * Animations */ const moreAnimation = posed.div({ hoverable: true, pressable: true, init: { scale: 1 }, hover: { scale: 1.2 }, press: { scale: 1.1 }, }); /** * Styled Components */ const Header = styled.header` height: 100vh; position: relative; background: ${props => props.theme.primaryBg}; color: #fff; display: flex; display: grid; justify-content: center; `; const HeroContent = styled.section` align-self: center; display: grid; justify-items: center; h1, h2 { margin: 0; line-height: 1.4; } h1 { font-size: 3.6rem; } h2 { color: ${props => props.theme.fontHeading}; font-size: 2.8rem; } div { text-align: center; } @media (max-width: ${props => props.theme.phone}) { h1 { font-size: 2.9rem; } h2 { font-size: 2.2rem; } } `; const Avatar = styled(Img)` border-radius: 50%; border: 2px solid ${props => props.theme.fontHeading}; margin-bottom: 20px; align-self: center; @media (max-width: ${props => props.theme.phone}) { width: 130px !important; height: 130px !important; } `; const More = styled(moreAnimation)` margin-top: 40px; cursor: pointer; img { margin: 0; } `; /** * Component */ const Hero = () => { const images = useStaticQuery(graphql` query { avatar: file(relativePath: { eq: "esausilva-small.jpg" }) { childImageSharp { fixed(width: 166, height: 166) { ...GatsbyImageSharpFixed_withWebp } } } more: file(relativePath: { eq: "icon-circle-down-arrow.png" }) { childImageSharp { resize(width: 31, height: 31) { src } } } } `); return ( <Header> <HeroContent> <Avatar fixed={images.avatar.childImageSharp.fixed} alt="<NAME> Photo" /> <Typing speed={40}> <h1>Hello there! I’m <NAME></h1> <h2> Full-Stack Software Engineer <br /> Brazilian Jiu-Jitsu Practitioner </h2> </Typing> <More> <Link to="navigation" spy={true} smooth={true} duration={600}> <img src={images.more.childImageSharp.resize.src} alt="See More" /> </Link> </More> </HeroContent> </Header> ); }; export default Hero; <gh_stars>1-10 import { REGISTER_SUCCESS, REGISTER_FAIL, LOGIN_SUCCESS, LOGIN_FAIL, FETCH_MEMBER_SUCCESS, FETCH_MEMBER_FAIL, SIGN_OUT, } from '../actions/memberAction'; const memberState = { isLoggedInMember: false, member: {} } const userReducer = (state = memberState, action) => { switch (action.type) { case FETCH_MEMBER_SUCCESS: return { ...state, member: action.payload, isLoggedInMember: true } case FETCH_MEMBER_FAIL: return { ...state, member: {}, isLoggedInMember: false } case LOGIN_SUCCESS: return { ...state, member: action.payload, isLoggedInMember: true } case LOGIN_FAIL: return { ...state, member: {}, isLoggedInMember: false } case REGISTER_SUCCESS: return { ...state, member: action.payload, isLoggedInMember: true } case REGISTER_FAIL: return { ...state, member: {}, isLoggedInMember: false } case SIGN_OUT : return { ...state, member: {}, isLoggedInMember: false } default: return state }; }; export default userReducer;/* global describe beforeEach it */ const { expect } = require('chai'); const request = require('supertest'); const { db, models: { Site }, } = require('../db'); const seed = require('../../script/seed'); const app = require('../app'); describe('Site routes', () => { let adminToken; before(async () => { await seed(); const response = await request(app).post('/auth/login/').send({ email: '<EMAIL>', password: '<PASSWORD>', }); const { token } = response.body; adminToken = token; }); describe('/api/sites/', () => { it('GET /api/sites', async () => { const res = await request(app) .get('/api/sites') .set({ authorization: adminToken }) .expect(200); expect(res.body).to.be.an('array'); expect(res.body.length).to.equal(5); }); it('Include user model', async () => { const res = await request(app) .get('/api/sites') .set({ authorization: adminToken }) .expect(200); expect(res.body[0]).to.have.property('users'); }); }); }); <reponame>kayman88/vsts-monitor export const isJson = (req) => { const accept = req.headers.accept; return accept && accept.indexOf('application/json') >= 0; }; <reponame>smapiot/piral-cli-integration-tests<gh_stars>1-10 const fs = require('fs'); const path = require('path'); const { spawn } = require('child_process'); const { toMatchFilesystemSnapshot } = require('jest-fs-snapshot'); const { cleanDir, cliVersion, waitForRunning, timeoutCommand, execute, sleep, isNodeV15, snapshotOptions, cleanupForSnapshot, } = require('./common'); const fsPromises = fs.promises; module.exports = ({ jest, expect, describe, it, afterAllHandlers }, bundler, port) => { const bundlerPrefix = !!bundler ? bundler + '-' : ''; const installFlag = process.version.startsWith('v15') ? '-y --legacy-peer-deps -- ' : ''; jest.setTimeout(300 * 1000); // 300 second timeout expect.extend({ toMatchFilesystemSnapshot }); describe(`${bundlerPrefix}pilet`, () => { it('build', async () => { const pathToBuildDir = path.resolve(process.cwd(), bundlerPrefix + 'bundler-pilet-build'); await cleanDir(pathToBuildDir); await execute( `npm init pilet@${cliVersion} ${installFlag}--source sample-piral@${cliVersion} --name ${'bundler-pilet-build'} -y`, { cwd: pathToBuildDir, }, ); await execute(`npm run build`, { cwd: pathToBuildDir, }); await cleanupForSnapshot(pathToBuildDir); expect(pathToBuildDir).toMatchFilesystemSnapshot(undefined, snapshotOptions); }); it('HMR', async (done) => { const pathToBuildDir = path.resolve(process.cwd(), bundlerPrefix + 'pilet'); const srcFilePath = path.resolve(pathToBuildDir, 'src', 'index.tsx'); await cleanDir(pathToBuildDir); await execute(`npm init pilet@${cliVersion} ${installFlag}--source sample-piral@${cliVersion} -y`, { cwd: pathToBuildDir, }); // fixing node15 issue if (isNodeV15) try { await execute(`timeout 60s npx pilet debug --port 2323`, { cwd: pathToBuildDir, }); } catch (error) {} // start the debug process and wait until compiled and server running const debugProcess = spawn(`${timeoutCommand} npx pilet debug --port ${port}`, { cwd: pathToBuildDir, shell: true, }); afterAllHandlers.push(() => { debugProcess.kill('SIGTERM'); debugProcess.stdout.destroy(); debugProcess.stderr.destroy(); }); const handleError = jest.fn(); debugProcess.stderr.once('data', handleError); await waitForRunning(debugProcess, port); // Go to page and check for expected pilet await page.goto(`http://localhost:${port}`, { waitUntil: 'networkidle0' }); let innerHtml = await page.$eval('.pi-tile', (element) => { return element.children[0].innerHTML; }); expect(innerHtml).toBe('Welcome to Piral!'); // Will be resolved 1s after the dev server has recompiled the changes const backendReloaded = new Promise((resolve, reject) => { timeout = setTimeout(() => reject(new Error('Server not started after 60s')), 60 * 1000); debugProcess.stdout.once('data', () => { clearTimeout(timeout); resolve(); }); }).then(() => sleep(1000)); // Update in src/index.tsx to trigger HMR const newString = `Welcome to Test${Math.floor(Math.random() * 10000)}!`; const indexFile = await fsPromises.readFile(srcFilePath); await fsPromises.writeFile(srcFilePath, indexFile.toString().replace('Welcome to Piral!', newString)); // Wait until changes have been applied and check the updated pilet await backendReloaded; innerHtml = await page.$eval('.pi-tile', (element) => { return element.children[0].innerHTML; }); expect(innerHtml).toBe(newString); // Validate, that the debug process did not output any errors and terminate the process expect(handleError).not.toBeCalled(); debugProcess.kill('SIGTERM'); debugProcess.stdout.destroy(); debugProcess.stderr.destroy(); done(); }); }); }; const assert = require('assert') const http = require('http') const path = require('path') const qs = require('querystring') const {closeWindow} = require('./window-helpers') const {remote} = require('electron') const {BrowserWindow, ipcMain, protocol, session, webContents} = remote describe('protocol module', () => { const protocolName = 'sp' const text = '<NAME>' const postData = { name: '<NAME>', type: 'string' } afterEach((done) => { protocol.unregisterProtocol(protocolName, () => { protocol.uninterceptProtocol('http', () => done()) }) }) describe('protocol.register(Any)Protocol', () => { const emptyHandler = (request, callback) => callback() it('throws error when scheme is already registered', (done) => { protocol.registerStringProtocol(protocolName, emptyHandler, (error) => { assert.equal(error, null) protocol.registerBufferProtocol(protocolName, emptyHandler, (error) => { assert.notEqual(error, null) done() }) }) }) it('does not crash when handler is called twice', (done) => { const doubleHandler = (request, callback) => { try { callback(text) callback() } catch (error) { // Ignore error } } protocol.registerStringProtocol(protocolName, doubleHandler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('sends error when callback is called with nothing', (done) => { protocol.registerBufferProtocol(protocolName, emptyHandler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: () => done('request succeeded but it should not'), error: (xhr, errorType) => { assert.equal(errorType, 'error') return done() } }) }) }) it('does not crash when callback is called in next tick', (done) => { const handler = (request, callback) => { setImmediate(() => callback(text)) } protocol.registerStringProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) }) describe('protocol.unregisterProtocol', () => { it('returns error when scheme does not exist', (done) => { protocol.unregisterProtocol('not-exist', (error) => { assert.notEqual(error, null) done() }) }) }) describe('protocol.registerStringProtocol', () => { it('sends string as response', (done) => { const handler = (request, callback) => callback(text) protocol.registerStringProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('sets Access-Control-Allow-Origin', (done) => { const handler = (request, callback) => callback(text) protocol.registerStringProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data, status, request) => { assert.equal(data, text) assert.equal(request.getResponseHeader('Access-Control-Allow-Origin'), '*') done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('sends object as response', (done) => { const handler = (request, callback) => { callback({ data: text, mimeType: 'text/html' }) } protocol.registerStringProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('fails when sending object other than string', (done) => { const handler = (request, callback) => callback(new Date()) protocol.registerBufferProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: () => done('request succeeded but it should not'), error: (xhr, errorType) => { assert.equal(errorType, 'error') done() } }) }) }) }) describe('protocol.registerBufferProtocol', () => { const buffer = new Buffer(text) it('sends Buffer as response', (done) => { const handler = (request, callback) => callback(buffer) protocol.registerBufferProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('sets Access-Control-Allow-Origin', (done) => { const handler = (request, callback) => callback(buffer) protocol.registerBufferProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data, status, request) => { assert.equal(data, text) assert.equal(request.getResponseHeader('Access-Control-Allow-Origin'), '*') done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('sends object as response', (done) => { const handler = (request, callback) => { callback({ data: buffer, mimeType: 'text/html' }) } protocol.registerBufferProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('fails when sending string', (done) => { const handler = (request, callback) => callback(text) protocol.registerBufferProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: () => done('request succeeded but it should not'), error: (xhr, errorType) => { assert.equal(errorType, 'error') done() } }) }) }) }) describe('protocol.registerFileProtocol', () => { const filePath = path.join(__dirname, 'fixtures', 'asar', 'a.asar', 'file1') const fileContent = require('fs').readFileSync(filePath) const normalPath = path.join(__dirname, 'fixtures', 'pages', 'a.html') const normalContent = require('fs').readFileSync(normalPath) it('sends file path as response', (done) => { const handler = (request, callback) => callback(filePath) protocol.registerFileProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, String(fileContent)) return done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('sets Access-Control-Allow-Origin', (done) => { const handler = (request, callback) => callback(filePath) protocol.registerFileProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data, status, request) => { assert.equal(data, String(fileContent)) assert.equal(request.getResponseHeader('Access-Control-Allow-Origin'), '*') done() }, error: (xhr, errorType, error) => { done(error) } }) }) }) it('sends object as response', (done) => { const handler = (request, callback) => callback({ path: filePath }) protocol.registerFileProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, String(fileContent)) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('can send normal file', (done) => { const handler = (request, callback) => callback(normalPath) protocol.registerFileProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, String(normalContent)) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('fails when sending unexist-file', (done) => { const fakeFilePath = path.join(__dirname, 'fixtures', 'asar', 'a.asar', 'not-exist') const handler = (request, callback) => callback(fakeFilePath) protocol.registerFileProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: () => done('request succeeded but it should not'), error: (xhr, errorType) => { assert.equal(errorType, 'error') done() } }) }) }) it('fails when sending unsupported content', (done) => { const handler = (request, callback) => callback(new Date()) protocol.registerFileProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: () => done('request succeeded but it should not'), error: (xhr, errorType) => { assert.equal(errorType, 'error') done() } }) }) }) }) describe('protocol.registerHttpProtocol', () => { it('sends url as response', (done) => { const server = http.createServer((req, res) => { assert.notEqual(req.headers.accept, '') res.end(text) server.close() }) server.listen(0, '127.0.0.1', () => { const port = server.address().port const url = 'http://127.0.0.1:' + port const handler = (request, callback) => callback({url}) protocol.registerHttpProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) }) it('fails when sending invalid url', (done) => { const handler = (request, callback) => callback({url: 'url'}) protocol.registerHttpProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: () => done('request succeeded but it should not'), error: (xhr, errorType) => { assert.equal(errorType, 'error') done() } }) }) }) it('fails when sending unsupported content', (done) => { const handler = (request, callback) => callback(new Date()) protocol.registerHttpProtocol(protocolName, handler, (error) => { if (error) return done(error) $.ajax({ url: protocolName + '://fake-host', cache: false, success: () => { done('request succeeded but it should not') }, error: (xhr, errorType) => { assert.equal(errorType, 'error') done() } }) }) }) it('works when target URL redirects', (done) => { let contents = null const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301 res.setHeader('Location', `http://${req.rawHeaders[1]}`) res.end() } else { res.end(text) } }) server.listen(0, '127.0.0.1', () => { const port = server.address().port const url = `${protocolName}://fake-host` const redirectURL = `http://127.0.0.1:${port}/serverRedirect` const handler = (request, callback) => callback({url: redirectURL}) protocol.registerHttpProtocol(protocolName, handler, (error) => { if (error) return done(error) contents = webContents.create({}) contents.on('did-finish-load', () => { assert.equal(contents.getURL(), url) server.close() contents.destroy() done() }) contents.loadURL(url) }) }) }) }) describe('protocol.isProtocolHandled', () => { it('returns true for about:', (done) => { protocol.isProtocolHandled('about', (result) => { assert.equal(result, true) done() }) }) it('returns true for file:', (done) => { protocol.isProtocolHandled('file', (result) => { assert.equal(result, true) done() }) }) it('returns true for http:', (done) => { protocol.isProtocolHandled('http', (result) => { assert.equal(result, true) done() }) }) it('returns true for https:', (done) => { protocol.isProtocolHandled('https', (result) => { assert.equal(result, true) done() }) }) it('returns false when scheme is not registered', (done) => { protocol.isProtocolHandled('no-exist', (result) => { assert.equal(result, false) done() }) }) it('returns true for custom protocol', (done) => { const emptyHandler = (request, callback) => callback() protocol.registerStringProtocol(protocolName, emptyHandler, (error) => { assert.equal(error, null) protocol.isProtocolHandled(protocolName, (result) => { assert.equal(result, true) done() }) }) }) it('returns true for intercepted protocol', (done) => { const emptyHandler = (request, callback) => callback() protocol.interceptStringProtocol('http', emptyHandler, (error) => { assert.equal(error, null) protocol.isProtocolHandled('http', (result) => { assert.equal(result, true) done() }) }) }) }) describe('protocol.intercept(Any)Protocol', () => { const emptyHandler = (request, callback) => callback() it('throws error when scheme is already intercepted', (done) => { protocol.interceptStringProtocol('http', emptyHandler, (error) => { assert.equal(error, null) protocol.interceptBufferProtocol('http', emptyHandler, (error) => { assert.notEqual(error, null) done() }) }) }) it('does not crash when handler is called twice', (done) => { var doubleHandler = (request, callback) => { try { callback(text) callback() } catch (error) { // Ignore error } } protocol.interceptStringProtocol('http', doubleHandler, (error) => { if (error) return done(error) $.ajax({ url: 'http://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('sends error when callback is called with nothing', (done) => { if (process.env.TRAVIS === 'true') return done() protocol.interceptBufferProtocol('http', emptyHandler, (error) => { if (error) return done(error) $.ajax({ url: 'http://fake-host', cache: false, success: () => done('request succeeded but it should not'), error: (xhr, errorType) => { assert.equal(errorType, 'error') done() } }) }) }) }) describe('protocol.interceptStringProtocol', () => { it('can intercept http protocol', (done) => { const handler = (request, callback) => callback(text) protocol.interceptStringProtocol('http', handler, (error) => { if (error) return done(error) $.ajax({ url: 'http://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('can set content-type', (done) => { const handler = (request, callback) => { callback({ mimeType: 'application/json', data: '{"value": 1}' }) } protocol.interceptStringProtocol('http', handler, (error) => { if (error) return done(error) $.ajax({ url: 'http://fake-host', cache: false, success: (data) => { assert.equal(typeof data, 'object') assert.equal(data.value, 1) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('can receive post data', (done) => { const handler = (request, callback) => { const uploadData = request.uploadData[0].bytes.toString() callback({data: uploadData}) } protocol.interceptStringProtocol('http', handler, (error) => { if (error) return done(error) $.ajax({ url: 'http://fake-host', cache: false, type: 'POST', data: postData, success: (data) => { assert.deepEqual(qs.parse(data), postData) done() }, error: (xhr, errorType, error) => done(error) }) }) }) }) describe('protocol.interceptBufferProtocol', () => { it('can intercept http protocol', (done) => { const handler = (request, callback) => callback(new Buffer(text)) protocol.interceptBufferProtocol('http', handler, (error) => { if (error) return done(error) $.ajax({ url: 'http://fake-host', cache: false, success: (data) => { assert.equal(data, text) done() }, error: (xhr, errorType, error) => done(error) }) }) }) it('can receive post data', (done) => { const handler = (request, callback) => { const uploadData = request.uploadData[0].bytes callback(uploadData) } protocol.interceptBufferProtocol('http', handler, (error) => { if (error) return done(error) $.ajax({ url: 'http://fake-host', cache: false, type: 'POST', data: postData, success: (data) => { assert.equal(data, $.param(postData)) done() }, error: (xhr, errorType, error) => done(error) }) }) }) }) describe('protocol.interceptHttpProtocol', () => { it('can send POST request', (done) => { const server = http.createServer((req, res) => { let body = '' req.on('data', (chunk) => { body += chunk }) req.on('end', () => { res.end(body) }) server.close() }) server.listen(0, '127.0.0.1', () => { const port = server.address().port const url = `http://127.0.0.1:${port}` const handler = (request, callback) => { const data = { url: url, method: 'POST', uploadData: { contentType: 'application/x-www-form-urlencoded', data: request.uploadData[0].bytes.toString() }, session: null } callback(data) } protocol.interceptHttpProtocol('http', handler, (error) => { if (error) return done(error) $.ajax({ url: 'http://fake-host', cache: false, type: 'POST', data: postData, success: (data) => { assert.deepEqual(qs.parse(data), postData) done() }, error: (xhr, errorType, error) => done(error) }) }) }) }) it('can use custom session', (done) => { const customSession = session.fromPartition('custom-ses', {cache: false}) customSession.webRequest.onBeforeRequest((details, callback) => { assert.equal(details.url, 'http://fake-host/') callback({cancel: true}) }) const handler = (request, callback) => { callback({ url: request.url, session: customSession }) } protocol.interceptHttpProtocol('http', handler, (error) => { if (error) return done(error) fetch('http://fake-host').then(() => { done('request succeeded but it should not') }).catch(() => { customSession.webRequest.onBeforeRequest(null) done() }) }) }) }) describe('protocol.uninterceptProtocol', () => { it('returns error when scheme does not exist', (done) => { protocol.uninterceptProtocol('not-exist', (error) => { assert.notEqual(error, null) done() }) }) it('returns error when scheme is not intercepted', (done) => { protocol.uninterceptProtocol('http', (error) => { assert.notEqual(error, null) done() }) }) }) describe('protocol.registerStandardSchemes', () => { const standardScheme = remote.getGlobal('standardScheme') const origin = `${standardScheme}://fake-host` const imageURL = `${origin}/test.png` const filePath = path.join(__dirname, 'fixtures', 'pages', 'b.html') const fileContent = '<img src="/test.png" />' let w = null let success = null beforeEach(() => { w = new BrowserWindow({show: false}) success = false }) afterEach((done) => { protocol.unregisterProtocol(standardScheme, () => { closeWindow(w).then(() => { w = null done() }) }) }) it('resolves relative resources', (done) => { const handler = (request, callback) => { if (request.url === imageURL) { success = true callback() } else { callback(filePath) } } protocol.registerFileProtocol(standardScheme, handler, (error) => { if (error) return done(error) w.webContents.on('did-finish-load', () => { assert(success) done() }) w.loadURL(origin) }) }) it('resolves absolute resources', (done) => { const handler = (request, callback) => { if (request.url === imageURL) { success = true callback() } else { callback({ data: fileContent, mimeType: 'text/html' }) } } protocol.registerStringProtocol(standardScheme, handler, (error) => { if (error) return done(error) w.webContents.on('did-finish-load', () => { assert(success) done() }) w.loadURL(origin) }) }) it('can have fetch working in it', (done) => { const content = '<html><script>fetch("http://github.com")</script></html>' const handler = (request, callback) => callback({data: content, mimeType: 'text/html'}) protocol.registerStringProtocol(standardScheme, handler, (error) => { if (error) return done(error) w.webContents.on('crashed', () => done('WebContents crashed')) w.webContents.on('did-finish-load', () => done()) w.loadURL(origin) }) }) it('can access files through the FileSystem API', (done) => { let filePath = path.join(__dirname, 'fixtures', 'pages', 'filesystem.html') const handler = (request, callback) => callback({path: filePath}) protocol.registerFileProtocol(standardScheme, handler, (error) => { if (error) return done(error) w.loadURL(origin) }) ipcMain.once('file-system-error', (event, err) => done(err)) ipcMain.once('file-system-write-end', () => done()) }) it('registers secure, when {secure: true}', (done) => { let filePath = path.join(__dirname, 'fixtures', 'pages', 'cache-storage.html') const handler = (request, callback) => callback({path: filePath}) ipcMain.once('success', () => done()) ipcMain.once('failure', (event, err) => done(err)) protocol.registerFileProtocol(standardScheme, handler, (error) => { if (error) return done(error) w.loadURL(origin) }) }) }) }) (function(){ 'use strict'; angular .module('app') .controller('RegisterController',RegisterController); RegisterController.$inject = ['$scope']; function RegisterController ($scope){ var vm = this; } })();<reponame>austindebruyn/easelbee.io<gh_stars>1-10 import { shallow } from 'avoriaz'; import sinon from 'sinon'; import Vuex from 'vuex'; import CommissionPriceCounter from './CommissionPriceCounter'; import PriceCalculator from 'logic/PriceCalculator'; import { buildQuestion, buildOption } from 'fixtures/questions'; describe('CommissionPriceCounter', function () { function factory (props = {}) { return shallow(CommissionPriceCounter, { propsData: { values: props.values || {} }, i18n: this.i18n, store: this.store }); } beforeEach(function () { this.options = { 1: buildOption() }; this.questions = { 1: buildQuestion() }; this.store = new Vuex.Store({ state: { options: this.options, questions: this.questions } }); this.sandbox = sinon.sandbox.create(); this.sandbox.stub(PriceCalculator.prototype, 'calculate') .onFirstCall().returns(17) .onSecondCall().returns(30); }); afterEach(function () { this.sandbox.restore(); }); it('should render 17', function () { const wrapper = factory.call(this); expect(wrapper.text()).to.eql('$17'); }); it('should call price calculator with options and questions', async function () { factory.call(this, { values: { question_1: 1 } }); expect(PriceCalculator.prototype.calculate).to.have.been.calledWith( this.questions, this.options, { question_1: 1 } ); }); it('should call price calculator to update', async function () { expect(PriceCalculator.prototype.calculate).to.not.have.been.called; const wrapper = factory.call(this); wrapper.setProps({ values: { question_1: 'new value' } }); expect(PriceCalculator.prototype.calculate).to.have.been.calledTwice; expect(wrapper.text()).to.eql('$30'); }); }); import {put,call,takeLatest} from 'redux-saga/effects'; import {getUser, getUserSuccess, getUserError, logoutUser} from '../actions'; import {apiGetUser, apiLogoutUser} from '../lib/api'; //WATCHER SAGA export function* watchGetUser(){ yield takeLatest(getUser, workerGetUser); } export function* watchLogoutUser(){ yield takeLatest(logoutUser, workerLogoutUser); } //WORKER SAGA export function* workerGetUser(){ try{ const resp = yield call(apiGetUser); yield put(getUserSuccess(resp)); }catch(error){ yield put(getUserError(error)); } } export function* workerLogoutUser(){ try { const resp = yield call(apiLogoutUser); } catch(error){ console.log(error); } } <gh_stars>0 "use strict"; const { of, forkJoin, range } = require("rxjs"); const { tap, mergeMap, catchError, map, mapTo, toArray, delay } = require("rxjs/operators"); const broker = require("../../tools/broker/BrokerFactory")(); const Event = require("@nebulae/event-store").Event; const eventSourcing = require("../../tools/EventSourcing")(); const MATERIALIZED_VIEW_TOPIC = "emi-gateway-materialized-view-updates"; const { ShiftDA, ServiceDA } = require("./data-access"); const MongoDB = require("../../data/MongoDB").singleton(); /** * Singleton instance */ let instance; class CronJobES { constructor() { } handlePeriodicOneMinute$() { return forkJoin( this.checkDisconnectedShifts$(), //this.checkClosedShifts$(), //this.checkServicesToClose$() ) } handlePeriodicFiveMinutes$() { return forkJoin( //this.checkDisconnectedShifts$(), //this.checkClosedShifts$(), this.checkServicesToClose$(), this.checkServicesOnBoardToComplete$() ) } handlePeriodicFifteenMinutes$() { return forkJoin( this.checkClosedShifts$(), //this.checkServicesToClose$() ) } handlePeriodicMonthly$(){ return MongoDB.createIndexesOnHistoricalCollection$() .pipe( tap(indexCreationResult => console.log(indexCreationResult)) ); } /** * Gonna to search Shift that must to be disconnected and emits event for each found to disconnect it */ checkDisconnectedShifts$() { return ShiftDA.getShiftsToDisconnect$() .pipe( // tap(shift => console.log("SHIFT TO SET AS DISCONNECTED => ", JSON.stringify(shift))), mergeMap(shift => this.generateEventStoreEvent$("ShiftDisconnected", 1, "Shift", shift._id, { ...shift }, "SYSTEM")), mergeMap(event => eventSourcing.eventStore.emitEvent$(event)), toArray(), // tap(() => console.log("ALL SHIFTS THAT MATCH WITH THE CONDITIONS WERE DISCONNECTED")) ) } /** * search the shift that must to be closed and emit an event for each item to close it */ checkClosedShifts$() { // console.log("---------- checkClosedShifts$ ------------- "); return ShiftDA.getShiftsToClose$() .pipe( // tap(shift => console.log("SHIFT TO CLOSE => ", JSON.stringify(shift))), mergeMap(shift => this.generateEventStoreEvent$("ShiftStateChanged", 1, "Shift", shift._id, { ...shift, state: "CLOSED" }, "SYSTEM")), mergeMap(event => eventSourcing.eventStore.emitEvent$(event)), toArray(), // tap(() => console.log("ALL SHIFTS WERE CLOSED")) ) } /** * Search the services that are on OnBoard state and emit an event for each service to complete it */ checkServicesOnBoardToComplete$() { return ServiceDA.findServicesOnboardToComplete$() .pipe( // tap(service => console.log("SERVICE TO COMPLETE => ", JSON.stringify(service))), mergeMap(service => this.generateEventStoreEvent$("ServiceCompleted", 1, "Service", service._id, { timestamp : Date.now() }, "SYSTEM")), mergeMap(event => eventSourcing.eventStore.emitEvent$(event)), toArray(), // tap(() => console.log("ALL SERVICES THAT MATCH WITH CONDITIONS WERE COMPLETED")) ) } checkServicesToClose$() { // console.log("-------- checkServicesToClose$ ---------"); return ServiceDA.findServicesToClose$() .pipe( // tap(service => console.log("SERVICE TO CLOSE => ", JSON.stringify(service))), mergeMap(service => this.generateEventStoreEvent$("ServiceClosed", 1, "Service", service._id, { ...service }, "SYSTEM")), mergeMap(event => eventSourcing.eventStore.emitEvent$(event)), toArray(), // tap(() => console.log("ALL SERVICES THAT MATCH WITH CONDITIONS WERE CLOSED")) ) } generateEventStoreEvent$(eventType, eventVersion, aggregateType, aggregateId, data, user) { return of(new Event({ eventType: eventType, eventTypeVersion: eventVersion, aggregateType: aggregateType, aggregateId: aggregateId, data: data, user: user })) } } /** * @returns {CronJobES} */ module.exports = () => { if (!instance) { instance = new CronJobES(); console.log(`${instance.constructor.name} Singleton created`); } return instance; }; $(function () { $("#jqGrid").jqGrid({ url: baseURL + 'test/stress/list', datatype: "json", colModel: [ {label: '用例ID', name: 'caseId', width: 50, key: true}, {label: '名称', name: 'caseName', sortable: false, width: 150}, {label: '添加时间', name: 'addTime', width: 90}, {label: '项目', name: 'project', sortable: false, width: 80}, {label: '模块', name: 'module', sortable: false, width: 80}, {label: '操作人', name: 'operator', sortable: false, width: 60}, // { label: 'cron表达式 ', name: 'cronExpression', width: 100 }, { label: '备注', name: 'remark', sortable: false, width: 110 } ], viewrecords: true, height: 385, rowNum: 10, rowList: [10, 30, 50], rownumbers: true, rownumWidth: 25, autowidth: true, multiselect: true, pager: "#jqGridPager", jsonReader: { root: "page.list", page: "page.currPage", total: "page.totalPage", records: "page.totalCount" }, prmNames: { page: "page", rows: "limit", order: "order" }, gridComplete: function () { //隐藏grid底部滚动条 $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"}); } }); new AjaxUpload('#upload', { action: baseURL + 'test/stress/upload?token=' + token, name: 'file', autoSubmit: true, responseType: "json", onSubmit: function (file, extension) { var caseId = getSelectedRow(); if (caseId == null) { return false; } // if (!(extension && /^(txt|jmx)$/.test(extension.toLowerCase()))) { // alert('只支持jmx、txt格式的用例相关文件!'); // return false; // } this.setData({caseIds: caseId}) }, // onChange: function(file, ext){ // debugger // if(!(ext && (/^(jmx)$/.test(ext))){ // alert("只支持jmx格式的文件!"); // return false // } // }, onComplete: function (file, r) { if (r.code == 0) { // alert(r.url); alert('操作成功', function () { vm.reload(); }); } else { alert(r.msg); } } }); }); var vm = new Vue({ el: '#rrapp', data: { q: { caseName: null }, showList: true, title: null, stressCase: {} }, methods: { query: function () { if (vm.q.caseName != null) { vm.reload(); } }, add: function () { vm.showList = false; vm.title = "新增"; vm.stressCase = {}; }, update: function () { var caseId = getSelectedRow(); if (caseId == null) { return; } $.get(baseURL + "test/stress/info/" + caseId, function (r) { vm.showList = false; vm.title = "修改"; vm.stressCase = r.stressCase; }); }, saveOrUpdate: function () { if (vm.validator()) { return; } var url = vm.stressCase.caseId == null ? "test/stress/save" : "test/stress/update"; $.ajax({ type: "POST", url: baseURL + url, contentType: "application/json", data: JSON.stringify(vm.stressCase), success: function (r) { if (r.code === 0) { // alert('操作成功', function(){ vm.reload(); // }); } else { alert(r.msg); } } }); }, del: function () { var caseIds = getSelectedRows(); if (caseIds == null) { return; } confirm('确定要删除选中的记录?', function () { $.ajax({ type: "POST", url: baseURL + "test/stress/delete", contentType: "application/json", data: JSON.stringify(caseIds), success: function (r) { if (r.code == 0) { alert('操作成功', function () { vm.reload(); }); } else { alert(r.msg); } } }); }); }, reload: function (event) { vm.showList = true; var page = $("#jqGrid").jqGrid('getGridParam', 'page'); $("#jqGrid").jqGrid('setGridParam', { postData: {'caseName': vm.q.caseName}, page: page }).trigger("reloadGrid"); }, validator: function () { if (isBlank(vm.stressCase.caseName)) { alert("用例名称不能为空"); return true; } if (isBlank(vm.stressCase.project)) { alert("项目名称不能为空"); return true; } if (isBlank(vm.stressCase.module)) { alert("模块名称不能为空"); return true; } if (isBlank(vm.stressCase.operator)) { alert("操作人不能为空"); return true; } } // upload: function () { // debugger // // var caseId = getSelectedRow(); // if (caseId == null) { // return; // } // ajaxUpload.submit(); // } } }); import React, { useRef, } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Col, Row, SRStatus, TextField, MultiSelection, } from '@folio/stripes-components'; import { Field, } from 'react-final-form'; import { FormattedMessage } from 'react-intl'; import { CENTRAL_SERVER_CONFIGURATION_FIELDS, } from '../../../../../../constants'; import { AddAndDeleteButtons, TableStyleList, } from '../../../../common'; import TabularListTitles from './components/TabularListTitles'; import { getSelectedLibsSet, } from '../../utils'; import css from './TabularList.css'; const { LOCAL_AGENCIES, LOCAL_AGENCY, FOLIO_LIBRARIES, } = CENTRAL_SERVER_CONFIGURATION_FIELDS; const NEW_ROW_TEMPLATE = { [LOCAL_AGENCY]: '', [FOLIO_LIBRARIES]: [], }; const TabularList = ({ librariesTypeOptions, }) => { const srsRef = useRef(); return ( <> <SRStatus ref={srsRef} /> <TableStyleList fieldArrayName={LOCAL_AGENCIES} customTitles={<TabularListTitles />} rootClassName={css.tabularContainer} > {({ fields }) => fields.map((name, index) => { const dataWithoutCurRow = fields.value.filter((_, i) => i !== index); const selectedOptsSet = getSelectedLibsSet(dataWithoutCurRow); const dataOptions = librariesTypeOptions.filter(({ value: libId }) => !selectedOptsSet.has(libId)); const isLastRow = index === fields.length - 1; return ( <Row key={index} className={classNames(css.tabularRow, index % 2 ? css.tabularRowOdd : css.tabularRowEven)} data-testid="row" > <Col className={classNames(css.tabularCol, css.tabularColFirst)}> <Field marginBottom0 required autoFocus={isLastRow && fields.length > 1} id={`${name}.${LOCAL_AGENCY}-${index}`} name={`${name}.${LOCAL_AGENCY}`} aria-label={<FormattedMessage id="ui-inn-reach.settings.central-server-configuration.local-agency.field.code" />} component={TextField} /> </Col> <Col className={css.tabularCol}> <Field marginBottom0 required id={`${name}.${FOLIO_LIBRARIES}-${index}`} name={`${name}.${FOLIO_LIBRARIES}`} component={MultiSelection} dataOptions={dataOptions} aria-label={<FormattedMessage id="ui-inn-reach.settings.central-server-configuration.local-agency.field.libraries" />} /> </Col> <AddAndDeleteButtons index={index} fields={fields} newRowTemplate={NEW_ROW_TEMPLATE} srsRef={srsRef} /> </Row> ); })} </TableStyleList> </> ); }; TabularList.propTypes = { librariesTypeOptions: PropTypes.arrayOf(PropTypes.object), }; export default TabularList; 'use strict'; var cssError = require('csserror'); var chalk = require('chalk'); module.exports = function getErrorScript(errorMessage) { var cleanErrorMessage = chalk.stripColor(errorMessage); return [ '/**********************************************************', cleanErrorMessage.split('\n').map(function (str) { return ' * ' + str; }).join('\n'), ' *********************************************************/', ';(function () {', ' var str = "' + cssError(cleanErrorMessage, true).replace(/\n/g, '\\\n').replace(/"/g, '\\"') + '";', ' var el = document.createElement("style");', ' if (el.styleSheet) {', ' el.styleSheet.cssText = str;', ' } else {', ' el.appendChild(document.createTextNode(str));', ' }', ' var firstScript = document.getElementsByTagName("script")[0];', ' firstScript.parentNode.insertBefore(el, firstScript);', '}());', '' ].join('\n'); }; <filename>.eslintrc.js /* eslint-env node */ module.exports = { root: true, env: { es6: true, browser: true, }, extends: [ 'lacussoft', ], ignorePatterns: [ 'dist/', 'public/', ], parserOptions: { ecmaVersion: 2021, sourceType: 'module', }, rules: { 'class-methods-use-this': 'off', 'no-magic-numbers': ['error', { ignore: [-1, 0, 1, 2, 3, 100, 1000] }], 'no-param-reassign': 'off', }, } require('./connect'); require('./events'); <reponame>snblickhan/text-editor<gh_stars>1-10 import React from 'react' import { Box, Button, Text } from 'grommet' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faTimesCircle } from '@fortawesome/free-solid-svg-icons' import styled from 'styled-components' import { func } from 'prop-types' const StyledText = styled(Text)` line-height: 1.75em; ` export default function UnapproveModal({ onClose, onUnapprove }) { return ( <Box background='white' elevation='small' gap='xsmall' pad='small' round='xsmall' width='medium' > <Box direction='row' justify='between'> <Text size='large'>Unapprove subject data</Text> <Button a11yTitle="Close Unapprove Subject Modal" label={<FontAwesomeIcon icon={faTimesCircle} size='xs' />} onClick={onClose} plain /> </Box> <StyledText> By unapproving this subject, the subject's data will be unavailable for future downloads until re-marked as approved. </StyledText> <StyledText>This action can be reversed at any time.</StyledText> <Box direction='row' justify='between' margin={{ top: 'small' }}> <Button a11yTitle="Close Unapprove Subject Modal" label={<Text size='small'>CLOSE AND CANCEL</Text>} onClick={onClose} plain /> <Button a11yTitle="Confirm to Unapprove Subject" label={<Text size='small'>YES, UNAPPROVE</Text>} onClick={onUnapprove} plain /> </Box> </Box> ) } UnapproveModal.propTypes = { onClose: func, onUnapprove: func } UnapproveModal.defaultProps = { onClose: () => {}, onUnapprove: () => {} } "use strict"; // https://developers.google.com/cast/docs/reference/chrome/chrome.cast.SenderApplication export default class SenderApplication { constructor (platform) { this.packageId = null; this.platform = platform; this.url = null; } }; import Vue from 'vue' import VueRouter from 'vue-router'; import App from './App.vue' import routes from './routes/index'; import store from './vuex/index'; // import './assets/iconfont/iconfont.css'; import './styles/animate.css'; import './styles/common.scss'; import './share/prototype'; //太卡了 暂时先不要了 //import '@/styles/font-family.css'; import directives from './share/directive'; import message from './plugins/message/index'; import imgViewer from './plugins/image-viewer/index'; import prototype from './share/prototype'; Vue.config.productionTip = false Vue.use(VueRouter); Vue.use(message); Vue.use(imgViewer); const router = new VueRouter({routes}) directives(Vue); new Vue({ router, store, render: h => h(App), }).$mount('#app') <reponame>lujano1493/invesment-capital let mix = require('laravel-mix'); mix.babel( [ 'resources/assets/js/plugins/scroll-element.js', 'resources/assets/js/plugins/serializeForm.js', 'resources/assets/js/plugins/jquery.doT.js', 'resources/assets/js/plugins/calc-rfc.js', 'resources/assets/js/plugins/add-forms.js', 'resources/assets/js/plugins/ajaxForm.js', 'resources/assets/js/plugins/document-view.js', 'resources/assets/js/plugins/modal-loading.js', 'node_modules/startbootstrap-sb-admin-2/vendor/datatables-plugins/dataTables.bootstrap.js', // para obtener la version 3.7 'node_modules/datatables-responsive/js/dataTables.responsive.js', 'node_modules/particles.js/particles.js', 'node_modules/startbootstrap-sb-admin-2/vendor/raphael/raphael.js', 'node_modules/startbootstrap-sb-admin-2/vendor/metisMenu/metisMenu.js', 'node_modules/startbootstrap-sb-admin-2/js/sb-admin-2.js', 'resources/assets/js/plugins/dinamic-input.js', 'resources/assets/js/plugins/jquery.chart-morris.js', 'resources/assets/js/plugins/jq.charts-investment.js', 'resources/assets/js/plugins/config-app.js', 'resources/assets/js/capital/main.js', 'resources/assets/js/capital/cuestionario.js' ], 'public/js/app-plugin.js')import * as React from "react"; import { Text, View, TextInput, Button, Alert } from "react-native"; export function AuthScreen() { return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <Text style={{ fontSize: 40, paddingBottom: 30 }}>Вход</Text> <TextInput style={{ height: 55, width: 200, borderColor: 'gray', borderWidth: 1, paddingLeft: 20, borderRadius: 5 }} placeholder="Логин" /> <TextInput style={{ height: 55, width: 200, borderColor: 'gray', borderWidth: 1, paddingLeft: 20, borderRadius: 5 }} placeholder="Пароль" secureTextEntry={ true } /> <View style={{ paddingTop: 20, width: "50%" }}> <Button title="Войти" onPress={() => { Alert.alert("Ошибка", "Неправильный логин или пароль"); }} color="#6CB50D" /> </View> </View> ); }/*! * side menu functions JavaScript Library v1.0 * * Copyright <NAME> and other contributors * Released under the MIT license * https://jquery.org/license * Date: 2021-03-02T17:08Z */ 'use strict'; function addUser() { //var dataobject = { culture: culture, returnUrl: returnUrl }; //showInformationAlert("info", "addUser", "OK"); ajaxGetHandler("/Account/AddUser", { returnUrl: "/" }, function (response) { $("#maincontainer").html(response); }, false, false); } $(function () { //$('body').on('click', '#ahrefchange_password', function (e) { // ajaxGetHandler("/Account/ChangePassword", { returnUrl: "/" }, function (data) { // _cusTriggerModal("modal-common", data); // }, false, false); //}); //$('body').on('click', '#btnchangepassword', function (e) { // try { // event.preventDefault(); // if (_cusFormValidate('frmchangepassword')) { // var dataobject = { // emailaddress: $("#emailaddress").val(), // password: <PASSWORD>").val(), // newpassword: $("#<PASSWORD>").val(), // confirmpassword: $("#confirmpassword").val() // }; // ajaxPostObjectHandler("/Account/ChangePasswordPost", dataobject, function (response) { // _cusCloseModal('modal-common'); // }, true); // } // } catch (e) { // showErrorAlert("Error", e.message, "OK"); // } //}); }); <reponame>stephangriesel/sjtyresolution-log-site-google-sheets<gh_stars>0 import React, { Component } from "react" import { Button } from "./common/Button" import { Form } from "./common/Form" import { Container } from "./common/Container" import { Input } from "./common/Input" import { Select } from "./common/Select" import axios from "axios" export default class App extends Component { constructor(props) { super(props) this.state = { date: "", tyre_position: "", truck_trailer: "", start_time: "", end_time: "", truck_registration: "", driver_name: "", odometer_reading: "", pressure_reader: "", tracking_no: "", thread_depth: "", brand: "", replacement: "", condition: "", thread_pattern: "", torque_wheel_nuts: "", tyremovement_in_order: "", tyre_used: "", comments: "", } } changeHandler = e => { this.setState({ [e.target.name]: e.target.value }) } submitHandler = e => { e.preventDefault() console.log(this.state) axios .post( "https://sheet.best/api/sheets/208a1f15-0739-4d0e-a700-16b34cb621a4", this.state ) .then(response => { console.log(response) window.location = "/success" }) } render() { const { date, tyre_position, truck_trailer, start_time, end_time, truck_registration, driver_name, odometer_reading, pressure_reading, tracking_no, thread_depth, brand, replacement, condition, thread_pattern, torque_wheel_nuts, tyremovement_in_order, tyre_used, comments, } = this.state return ( <Container fluid className="container"> <Form className="form" onSubmit={this.submitHandler}> <> <label>Date</label> <Input placeholder="Enter date" type="date" name="date" value={date} onChange={this.changeHandler} required /> </> <> <label>Tyre Position</label> <Input placeholder="Tyre Position" type="number" name="tyre_position" value={tyre_position} onChange={this.changeHandler} required /> </> <> <label>Truck or Trailer</label> <Select name="truck_trailer" onChange={this.changeHandler} required> <option>--Make selection--</option> <option value="Truck">Truck</option> <option value="Trailer">Trailer</option> </Select> </> <> <label>Start Time</label> <Input placeholder="Select start time" type="time" name="start_time" value={start_time} onChange={this.changeHandler} required /> </> <> <label>End Time</label> <Input placeholder="Select end time" type="time" name="end_time" value={end_time} onChange={this.changeHandler} required /> </> <> <label>Truck Registration</label> <Input placeholder="Enter registration" type="text" name="truck_registration" value={truck_registration} onChange={this.changeHandler} required /> </> <> <label>Driver Name</label> <Input placeholder="Enter driver name" type="text" name="driver_name" value={driver_name} onChange={this.changeHandler} required /> </> <> <label>Odometer Reading</label> <Input placeholder="Enter odometer reading" type="number" name="odometer_reading" value={odometer_reading} onChange={this.changeHandler} required /> </> <> <label>Pressure Reading</label> <Input placeholder="Enter pressure reading" type="number" name="pressure_reading" value={pressure_reading} onChange={this.changeHandler} required /> </> <> <label>Tracking No.</label> <Input placeholder="Enter tracking no." type="text" name="tracking_no" value={tracking_no} onChange={this.changeHandler} required /> </> <> <label>Thread Depth</label> <Input placeholder="Enter thread depth" type="number" name="thread_depth" value={thread_depth} onChange={this.changeHandler} required /> </> <> <label>Brand</label> <Input placeholder="Enter brand" type="text" name="brand" value={brand} onChange={this.changeHandler} required /> </> <> <label>Replacement</label> <Select name="replacement" onChange={this.changeHandler} required> <option>--YES/NO?--</option> <option value="Yes">Yes</option> <option value="No">No</option> </Select> </> <> <label>Condition</label> <Input placeholder="Enter condition" type="text" name="condition" value={condition} onChange={this.changeHandler} required /> </> <> <label>Thread Pattern</label> <Input placeholder="Enter thread patterm" type="text" name="thread_pattern" value={thread_pattern} onChange={this.changeHandler} required /> </> <> <label>Torque Wheel Nuts</label> <Select name="torque_wheel_nuts" onChange={this.changeHandler} required > <option>--YES/NO?--</option> <option value="Yes">Yes</option> <option value="No">No</option> </Select> </> <> <label>Tyre Movement In Order</label> <Input placeholder="Enter tyre movement in order" type="text" name="tyremovement_in_order" value={tyremovement_in_order} onChange={this.changeHandler} required /> </> <> <label>Tyre Used</label> <Input placeholder="What tyre was used?" type="text" name="tyre_used" value={tyre_used} onChange={this.changeHandler} required /> </> <> <label>Comments</label> <Input placeholder="Additional Comments" type="text" name="comments" value={comments} onChange={this.changeHandler} /> </> <Button type="submit">Submit</Button> </Form> </Container> ) } } <reponame>raven-arc-bot/Mai const { MessageEmbed } = require('discord.js') const fetch = require('node-fetch') const { toRomaji } = require('wanakana') module.exports = { name: 'jisho', aliases: ['weebify', 'kanji', 'nipponify'], guildOnly: true, cooldown: { time: 10000, message: "Accessing Jisho has been rate limited to 1 use per user per 10 seconds" }, group: 'utility', description:"Searches for Japanese words and Kanji on Jisho!", examples: ["jisho [word <kanji, katakana, hiragana, romaji>]"], parameters: ['word'], run: async (client, message, [ query ]) => { if (!query) return message.channel.send(`<:cancel:712586986216489011> | ${message.author}, Please provide me a word to get the definition of.`) const res = await fetch(`https://jisho.org/api/v1/search/words?keyword=${encodeURI(query)}`).then(res => res.json()).catch(()=> null) if (!res || res.meta && res.meta.status !== 200) return message.channel.send(`<:cancel:712586986216489011> | ${message.author}, Could not connect to JISHO.`) if (!res.data || !res.data.length) return message.channel.send(`<:cancel:712586986216489011> | ${message.author}, No results were found for your query: **${query}**.`) let fields = [] for ( const { slug, is_common, tags, japanese, senses } of res.data.filter( d => d.attribution.jmdict ).splice(0,3)) { fields.push({ name: '\u200b', value: `**${slug}** - ${is_common ? `Common Word` : `Uncommon Word`}\n**Kanji**: ${japanese.map( m => `${m.word ? `"${m.word}"` : ''} ${m.reading ? `*"(${m.reading})"*`:''}`).join(' • ')}\n**Romanized**: ${japanese.map( m => toRomaji(m.reading)).join(' • ')}\n**Definition**: ${senses[0].english_definitions}\n\n${senses[0].restrictions.length ? `\n**Restrictions**: ${senses[0].restrictions.join('\n')}**`:''}${senses[0].tags.length || senses[0].info.length ? `\n**Notes**: ${senses[0].tags.join(' • ')}${senses[0].info.length ? ' • ' : ''}${senses[0].info.join(' • ')}` : ''}${senses[0].see_also.length ? `\n\n**See Also**: ${senses[0].see_also.join('\n')}` : ''}`, inline: true }) } return message.channel.send( new MessageEmbed() .setAuthor(`🇯🇵 • Search Results for ${query}!`) .addFields(fields) .addField('\u200b',`[External Link](https://jisho.org/search/${query} 'https://jisho.org/search/${query}')`) .setColor('GREY') .setFooter(`🇯🇵 • Jisho.org`) ) } } import express from 'express'; import bodyParser from 'body-parser'; import { apolloExpress, graphiqlExpress } from 'apollo-server'; import { addResolveFunctionsToSchema } from 'graphql-tools'; import { generateResolvers } from 'graph-object'; import schema from '/domain/schemas'; import connectors from './connectors'; import * as models from './models'; // Initial fixtures require('./fixtures').run(connectors.MongoDB.connect()); const PORT = 8080; const app = express(); const resolvers = generateResolvers(schema, models); addResolveFunctionsToSchema(schema, resolvers); app.use('/graphql', bodyParser.json(), apolloExpress({ schema, resolvers, context: {}, formatError(error) { console.error(error.stack); return error; }, })); app.use( '/graphiql', graphiqlExpress({ endpointURL: '/graphql', }) ); app.listen(PORT, () => console.log( `GraphQL Server is now running on http://localhost:${PORT}/graphiql` )); process.on('exit', () => { console.log('Shutting down!'); for (const connector of Object.values(connectors)) { connector.close(); } }); <filename>src/icons/regular/eye.js import Icon from '../../components/Icon.vue' Icon.register({ 'regular/eye': { width: 576, height: 512, paths: [ { d: 'M569.4 231.6C513 135.9 407.8 72 288 72 168.1 72 63 136 6.6 231.6A48-48 0 0 1 6.6 280.4C63 376.1 168.2 440 288 440 407.9 440 513 376 569.4 280.4A48-48 0 0 1 569.4 231.6zM288 392C185.4 392 95.9 337.3 48 256 92.2 181.1 171.7 128.7 264.2 121 274 131.1 280 144.8 280 160 280 190.9 254.9 216 224 216S168 190.9 168 160L168 160C157.8 179 152 200.8 152 224 152 299.1 212.9 360 288 360S424 299.1 424 224C424 193 413.6 164.4 396.1 141.5 451.7 164.6 498 205.1 528 256 480.1 337.3 390.6 392 288 392z' } ] } }) <filename>src/stories/modules/NavBarItem/NavbarItemDesktop.stories.js import React from 'react'; import { MemoryRouter } from 'react-router-dom'; import { storiesOf } from '@storybook/react'; import NavBarItemDesktop from '../../../components/NavBarItemDesktop'; import logo from '../../../images/defaultLogo.svg'; const stories = storiesOf('Components/NavBarItem', module); stories .addDecorator(story => <MemoryRouter>{story()}</MemoryRouter>) .add('NavBarItemDesktop', () => ( <NavBarItemDesktop id="42" label="item label" href="#" onClick={() => {}} icon={logo} /> )); import { combineReducers } from 'redux'; import dialog from './dialog'; import modal from './modal'; export default combineReducers({ dialog, modal }); <filename>assets/components/realtorx5/js/office/default.js<gh_stars>0 Ext.onReady(function () { RealtorX5.config.connector_url = OfficeConfig.actionUrl; var grid = new RealtorX5.panel.Home(); grid.render('office-realtorx5-wrapper'); var preloader = document.getElementById('office-preloader'); if (preloader) { preloader.parentNode.removeChild(preloader); } });const { Router } = require('express'); const incidentValidator = require('./validators/incidentValidator'); const ongValidator = require('./validators/ongValidator'); const profileValidator = require('./validators/profileValidator'); const sessionValidator = require('./validators/sessionValidator'); const OngController = require('./controllers/OngController'); const SessionController = require('./controllers/SessionController'); const ProfileController = require('./controllers/ProfileController'); const IncidentController = require('./controllers/IncidentController'); const routes = Router(); routes.post('/sessions', sessionValidator.store(), SessionController.store); routes.get('/ongs', OngController.index); routes.post('/ongs', ongValidator.store(), OngController.store); routes.get('/profile', profileValidator.index(), ProfileController.index); routes.get('/incidents', incidentValidator.index(), IncidentController.index); routes.post('/incidents', incidentValidator.store(), IncidentController.store); routes.delete( '/incidents/:id', incidentValidator.destroy(), IncidentController.destroy ); module.exports = routes; <filename>app/scripts/framework/views/resizable.js import { Events } from 'framework/events'; const Resizable = { listenDrag(dragView) { this.listenTo(dragView, 'dragstart', this.dragStart); this.listenTo(dragView, 'drag', this.drag); this.listenTo(dragView, 'autosize', this.autoSize); }, dragStart(e) { this._dragInfo = this.getDragInfo(e.coord); }, drag(e) { const dragInfo = this._dragInfo; let size = dragInfo.startSize + e.offset; size = Math.max(dragInfo.min, Math.min(dragInfo.max, size)); this.$el[dragInfo.prop](size); this.emit('view-resize', size); Events.emit('page-geometry', { source: 'resizable' }); }, autoSize(e) { const dragInfo = this.getDragInfo(e.coord); if (dragInfo.auto !== undefined) { this.$el.css(dragInfo.prop, dragInfo.auto); } else { this.$el.css(dragInfo.prop, ''); } this.fixSize(dragInfo); this.emit('view-resize', null); Events.emit('page-geometry', { source: 'resizable' }); }, fixSize(cfg) { const size = this.$el[cfg.prop](); const newSize = Math.max(cfg.min, Math.min(cfg.max, size)); if (newSize !== size) { this.$el[cfg.prop](size); } }, // TODO: check size on window resize // checkSize: function() { // if (this.maxWidth) { // this.fixSize(this.getDragInfo('x')); // } // if (this.maxHeight) { // this.fixSize(this.getDragInfo('y')); // } // }, getDragInfo(coord) { const prop = coord === 'x' ? 'Width' : 'Height'; const propLower = prop.toLowerCase(); const min = this.getSizeProp('min' + prop); const max = this.getSizeProp('max' + prop); const auto = this.getSizeProp('auto' + prop); const startSize = this.$el[propLower](); return { startSize, prop: propLower, min, max, auto }; }, getSizeProp(prop) { const member = this[prop]; return typeof member === 'function' ? member.call(this) : member; } }; export { Resizable }; <reponame>stevenhorkey/react-memory-game import React,{Component} from 'react'; import "./Navbar.css" class Navbar extends Component { render() { return( <nav className="navbar navbar-expand-lg navbar-light bg-light"> <a className="navbar-brand" href="/"><h3>Clicky Game</h3></a> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> </nav> ) } } export default Navbar;const os = require('os') // platform console.log(os.platform()) // cpu arch console.log(os.arch()) // cpu core info console.log(os.cpus()) // free memory console.log(os.freemem()) // total memory console.log(os.totalmem()) // home dir console.log(os.homedir()) // uptime console.log(os.uptime()) var proc = require('child_process'); var Promise = require('bluebird'); var _ = require('lodash'); var flagMap = { count: 'c', delimeter: 'd', full: 'f', pgroup: 'g', group: 'G', 'list-name': 'l', 'list-full': 'a', newest: 'n', oldest: 'o', P: 'P', ppid: 'P', session: 's', terminal: 't', euid: 'u', uid: 'U', inverse: 'v', lightweight: 'w', exact: 'x', pidfile: 'F', logpidfile: 'L', version: 'V', help: 'h' }; exports.exec = function (options) { var args = _.compact([ options.name ]); delete options.name; args = _.compact(args.concat(_.flatten(_.map(options, function (value, flag) { if (!flagMap[flag]) { throw new Error('flag not recognized: '+ flag); } return [ '-' + flagMap[flag], ((value === true) ? '' : value) ]; })))); return new Promise(function (resolve, reject) { proc.exec('pgrep ' + args.join(' '), function (error, stdout, stderr) { if (error) return reject(error); resolve(_.compact(_.map(stdout.split('\n'), function (pid) { return parseInt(pid); }))); }); }); }; <gh_stars>0 const ROOT = "userModules/SenergyConnector"; const ZWAY_MODULE_NAME = "zway"; //TODO: configuratable zway name (zway == Z-Wave Network Access.config.name (internalName)) var Modules = { _modules: {}, }; Modules.include = function(dir /*string*/) { if(!Modules._modules[dir]) { try { executeFile(ROOT + "/lib/" + dir + "/module.js"); } catch (e) { console.log("ERROR: unable to include module:", dir, e) } } return Modules.get(dir) }; Modules.loadJson = function(fileName) { try { return fs.loadJSON(ROOT+"/"+fileName); }catch (e) { console.log("ERROR: unable to load json:", fileName, e); return {} } }; Modules.registerModule = function(dir /*string*/, initFunc /*function(module)*/){ Modules._modules[dir] = initFunc({ add: function (filename /*string (without .js)*/) { try { executeFile(ROOT+"/lib/"+dir+"/"+filename+".js"); }catch (e) { console.log("ERROR: unable to add file to module:", dir, filename, JSON.stringify(e)) } }, include: function(subdir /*string*/) { return Modules.include(dir+"/"+subdir); } }); if(!Modules._modules[dir]){ console.log("WARNING: null module "+dir); Modules._modules[dir] = {}; } }; Modules.get = function (dir /*string*/) { return Modules._modules[dir]; }; //Array.prototype.map() polyfill from https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function(callback, thisArg) { var T, A, k; if (this == null) { throw new TypeError(' this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } if (arguments.length > 1) { T = thisArg; } A = new Array(len); k = 0; while (k < len) { var kValue, mappedValue; if (k in O) { kValue = O[k]; mappedValue = callback.call(T, kValue, k, O); A[k] = mappedValue; } k++; } return A; }; } //Array.prototype.forEach() polyfill from https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function(callback, thisArg) { var T, k; if (this === null) { throw new TypeError(' this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + ' is not a function'); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } //String.prototype.startsWith() polyfill from https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position) { position = position || 0; return this.indexOf(searchString, position) === position; }; } //String.prototype.endsWith() polyfill from https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith if (!String.prototype.endsWith) { String.prototype.endsWith = function(searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; } export default { variableClash: "Correct value" }; <filename>src/lib/utils/index.js // 工具函数 // 功能: 创建一个 HTML 节点。 // @ params createElementTag { String } 必填 // @ params createElementAttritubes { Object } 必填 // @ return element { HTNML Element} /* * 示例: * createAnChildNode('image', { * width: '100px', * height: '100px', * }) * 返回值: <image width="100px" height="100px"></image> */ function createAnChildNode(createElementTag, createElementAttritubes) { const element = document.createElement(createElementTag); for (const key in createElementAttritubes) { if (Object.prototype.hasOwnProperty.call(createElementAttritubes, key)) { element[key] = createElementAttritubes[key]; } } return element; } export { // eslint-disable-next-line createAnChildNode }; <gh_stars>0 import React, { Component } from 'react'; import Layout from '../components/Layout'; import DashBoardCards from '../components/DashBoardCards' class UserDashboard extends Component { render() { return ( <Layout> <h1 className="neonPink">[USER DASHBOARD] </h1> <DashBoardCards/> </Layout> )} } export default UserDashboard;<filename>fe/src/plugins/vuetify/vuetify.js import Vue from 'vue' import Vuetify from 'vuetify/lib/framework' Vue.use(Vuetify) export default new Vuetify({ theme: { options: { customProperties: true, }, dark: true, themes: { dark: { primary: { base: '#252525', lighten5: '#919191', lighten4: '#555555', lighten3: '#434343', lighten2: '#3C3C3C', lighten1: '#2E2E2E', darken1: '#181818', darken2: '#000000' }, seconday: { base: '#E7E7E7' }, accent: '#EA9F32' } } } }); // homebridge-deconz/lib/DeconzService/AirPressure.js // Copyright © 2022 <NAME>. All rights reserved. // // Homebridge plugin for deCONZ. 'use strict' const DeconzService = require('../DeconzService') /** * @memberof DeconzService */ class AirPressure extends DeconzService.SensorsResource { constructor (accessory, resource, params = {}) { params.Service = accessory.Services.eve.AirPressureSensor super(accessory, resource, params) this.addCharacteristicDelegate({ key: 'airPressure', Characteristic: this.Characteristics.eve.AirPressure, unit: ' hPa' }) this.addCharacteristicDelegate({ key: 'elevation', Characteristic: this.Characteristics.eve.Elevation, value: 0 }) this.addCharacteristicDelegates() this.update(resource.body) } updateState (state) { if (state.pressure != null) { this.values.airPressure = Math.round(state.pressure * 10) / 10 } super.updateState(state) } } module.exports = AirPressure <gh_stars>10-100 /** @module DynamicFilters */ import ResultsContext from '../storage/resultscontext'; /** * Model representing a set of dynamic filters */ export default class DynamicFilters { constructor (data) { /** * The list of facets this model holds * @type {DisplayableFacet[]} from answers-core */ this.filters = data.filters || []; /** * The {@link ResultsContext} of the facets. * @type {ResultsContext} */ this.resultsContext = data.resultsContext; Object.freeze(this); } /** * Organize 'facets' from the answers-core into dynamic filters * @param {DisplayableFacet[]} facets from answers-core * @param {ResultsContext} resultsContext * @returns {DynamicFilters} */ static fromCore (facets = [], resultsContext = ResultsContext.NORMAL) { return new DynamicFilters({ filters: facets, resultsContext: resultsContext }); } } <reponame>fxiajavier/javascript-basics<filename>src/object/inheritance.js /** * Inheritance in JavaScript is all about setting up the prototype chain. This allows us to subclass, that is, create a "child" object that inherits most or all of a "parent" object's properties and methods. We can then implement any of the child object's unique properties and methods separately, while still retaining data and functionality from its parent. An object (instance) is secretly linked to its constructor function's prototype object through that instance's __proto__ property. You should never use the __proto__ property in any code you write. Using __proto__ in any code, or even inheriting just the prototype directly, leads to some unwanted side effects. To efficiently manage inheritance in JavaScript, an effective approach is to avoid mutating the prototype completely. Object.create() allows us to do just that, taking in a parent object and returning a new object with its __proto__ property set to that parent object. */ function Animal (name) { this.name = name } Animal.prototype.walk = function () { console.log(`${this.name} walks!`) } function Cat (name) { Animal.call(this, name) this.lives = 9 } Cat.prototype = Object.create(Animal.prototype) Cat.prototype.constructor = Cat Cat.prototype.meow = function () { console.log('Meow!') } const bambi = new Cat('Bambi') bambi.meow() bambi.walk() console.log(bambi.name) console.log(bambi instanceof Animal) <filename>lib/eventBus.js // @flow let bus = {}; type Listener = mixed => mixed; export function on(name: string, fn: Listener) { var listeners = bus[name] = bus[name] || []; listeners.push(fn); } export function off(name: string, fn: Listener) { var listeners = bus[name]; if (!listeners) { return; } for (var i = listeners.length - 1; i >= 0; i--) { if (listeners[i] === fn) { listeners.splice(i, 1); } } if (listeners.length === 0) { delete bus[name]; } } export function emit(name: string, value: mixed) { var listeners = bus[name]; if (!listeners) { return; } for (var i = 0, length = listeners.length; i < length; i++) { listeners[i](value); } } export function reset() { bus = {}; } /* Layout */ import Layout from '@/layout' export default [ { path: '/stockreturn', component: Layout, redirect: '/stockreturn/list', name: 'StockReturn', meta: { title: '申请退票', icon: 'user', roles: ['financial', 'financial_check', 'admin', 'unit'] }, children: [ { path: '/stockreturn1', component: () => import('@/views/stockreturn/stockreturn'), name: 'PageStockReturn1', meta: { title: '票据申退', roles: ['admin', 'unit'] } }, { path: '/stockreturn2', component: () => import('@/views/stockreturn/stockreturncheck'), name: 'PageStockReturn2', meta: { title: '票据申退审核', roles: ['financial', 'financial_check', 'admin'] } } ] } ] var XXX = function(root) { //节点为空或节点没有左右两个子节点,都是平衡二叉树 if(!root) return true; //root不是null,才会执行下面的判断,所以不会报错 if(!root.left && !root.right) return true; //一个二叉树节点的左右两个子树的高度,遍历所有节点 var leftDep = getTreeHeight(root.left); var rightDep = getTreeHeight(root.right); var depth = Math.abs(leftDep - rightDep); let bool = depth > 1?false:true; //如果得知某个节点的左右两个字数的绝对值大于一,那么整个树就不是平衡二叉树,return跳出遍历 //如果某个节点是平衡二叉树,继续遍历其他节点,要return这个布尔值 //左右节点的值要写成且的形式,要是两个return后面的就不执行 if(bool){ return XXX(root.left) && XXX(root.right); }else{ return false; } }; function getTreeHeight(root){ //终止条件:节点无,每次搜索到头深度就是0 if(root == null){ return 0; } //累加下一层的深度要加1 var leftDepth = getTreeHeight(root.left) + 1; var rightDepth = getTreeHeight(root.right) + 1; //返回深度 return Math.max(leftDepth,rightDepth); }; <reponame>guigail/medecine-de-ville<filename>src/components/Results/Doctor/doctor.container.js import { connect } from 'react-redux' import { result } from 'lodash' import Component from './doctor' import { select } from './doctor.actions' const mapStateToProps = (state, { doctor: { id, ...doctor } }) => ({ id, doctor, selected: result(doctor, 'ui.selected'), }) const mapDispatchToProps = dispatch => ({ selectDoctor: id => dispatch(select(id)), }) export default connect(mapStateToProps, mapDispatchToProps)(Component) <reponame>davidzoli/grunt-ejs-render /* * grunt-ejs-render * https://github.com/dwightjack/grunt-ejs-render * * Copyright (c) 2013 <NAME> * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var ejs = require('ejs'), path = require('path'), fs = require('fs'), findFile = require('find-file-in-folders'), _ = require('lodash'); _.str = require('underscore.string'); _.mixin(_.str.exports()); function render(filepath, options) { var src = ''; if (fs.existsSync(filepath)) { src = fs.readFileSync(filepath, 'utf8'); return ejs.render(src, options || null); } else { grunt.log.warn('File "' + filepath + '" not found.'); return ''; } } grunt.registerMultiTask('render', 'Renders an EJS template to plain HTML', function() { var options = this.options({ helpers: {}, partialPaths: [], "_": _ }), datapath, methods = {}; methods.renderPartial = function(filepath, data) { var fpath = findFile(filepath, '.ejs', options.partialPaths); if (fpath !== false) { return render(fpath, _.extend({}, options, {filename: fpath}, data || {})); } return ''; }; methods.formatFilename = (file, ext = '') => { var filename = path.basename(file, ext); var keyName = _.camelize( _.slugify(filename)); return keyName; } if ( _.has(options, 'data')) { if ( _.isArray(options.data) ) { datapath = [].concat(options.data); datapath = _(datapath) .map(function(filepath) { return grunt.file.expand({ filter: function(src) { return grunt.file.isFile(src) && (path.extname(src) === '.yaml' || path.extname(src) === '.json'); } }, grunt.config.process(filepath)); }) .flatten() .uniq() .valueOf(); options.data = {}; datapath.forEach(function (file) { const ext = path.extname(file); const keyName = methods.formatFilename(file, ext); const fileData = ext === '.yaml' ? grunt.file.readYAML(file) : grunt.file.readJSON(file); options.data[keyName] = fileData; }); } else if (_.isFunction(options.data)) { options.data = options.data(); } } options.helpers = _.defaults(options.helpers, methods); _.forOwn(options.helpers, function(helperFunc, helperName, helpers) { if (_.isFunction(helperFunc)) { helpers[helperName] = _.bind(helperFunc, options); } }); this.files.forEach(function(file) { var contents = file.src.map(function(filepath) { options.filename = filepath; options.foldername = path.dirname(filepath); return render(filepath, options); }).join('\n'); grunt.file.write(file.dest, contents); grunt.log.writeln('Rendered HTML file to "' + file.dest + '"'); }); }); }; // extend the default Wazimap ProfileMaps object to add mapit support var BaseProfileMaps = ProfileMaps; ProfileMaps = function() { var self = this; this.mapit_url = GeometryLoader.mapit_url; _.extend(this, new BaseProfileMaps()); this.drawAllFeatures = function() { var self = this; var geo = this.geo; var geo_level = geo.this.geo_level; var geo_code = geo.this.geo_code; var geo_version = geo.this.version; // add demarcation boundaries if (geo_level == 'country') { this.map.setView({lat: -28.4796, lng: 10.698445}, 5); } else { // draw this geometry GeometryLoader.loadGeometryForGeo(geo_level, geo_code, geo_version, function(feature) { self.drawFocusFeature(feature); }); } // peers var parents = _.keys(geo.parents); if (parents.length > 0) { self.drawSurroundingFeatures(geo_level, parents[0], null, geo_version); } // every ancestor up to just before the root geo for (var i = 0; i < parents.length-1; i++) { self.drawSurroundingFeatures(parents[i], parents[i+1], null, geo_version); } // children if (geo.this.child_level) { self.drawSurroundingFeatures(geo.this.child_level, geo_level, geo_code, geo_version); } }; // Add map shapes for a level, limited to within the parent level (eg. // wards within a municipality). this.drawSurroundingFeatures = function(level, parent_level, parent_code, parent_version) { var code, parent, self = this, url; parent_code = parent_code || this.geo.parents[parent_level].geo_code; parent_version = parent_version || this.geo.parents[parent_level].geo_version; parent = MAPIT.level_codes[parent_level] + '-' + parent_code; // code of 'level', if any? if (this.geo.this.geo_level == level) { code = this.geo.this.geo_code; } else if (this.geo.parents[level]) { code = this.geo.parents[level].geo_code; } GeometryLoader.loadGeometrySet(parent + '|' + MAPIT.level_codes[level], level, parent_version, function(geojson) { // don't include this smaller geo, we already have a shape for that geojson.features = _.filter(geojson.features, function(f) { return f.properties.code != code; }); self.drawFeatures(geojson); }); // if we're loading districts, we also want to load metros, because // districts don't give us full coverage // We also need to load the point that if (level == 'district') { GeometryLoader.loadGeometrySet(parent + '|' + MAPIT.level_codes.municipality, 'municipality', parent_version, function(geojson) { // only keep metros geojson.features = _.filter(geojson.features, function(f) { // only metro codes are three letters return f.properties.code.length == 3; }); self.drawFeatures(geojson); }); } }; }; //// [undeclaredVarEmit.ts] f: number; //// [undeclaredVarEmit.js] f: number; import { RednomicServerProxyed } from "./RednomicServerProxyed"; export class RednomicServer { constructor(options) { let RS = new RednomicServerProxyed(options); this.getHealthStatuses = RS.getHealthStatuses.bind(RS); this.getLogs = RS.getLogs.bind(RS); this.use = RS.use.bind(RS); this.isAlive = RS.isAlive.bind(RS); } } <gh_stars>1-10 /** * ChannelCountListItem * * Lists the name, game, and message count of a channel. */ import React from 'react'; import { FormattedNumber } from 'react-intl'; import ListItem from 'components/ListItem'; import ChannelLink from './ChannelLink'; import ChannelWrapper from './ChannelWrapper'; export class ChannelCountListItem extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { const item = this.props.item; // Put together the content of the repository const content = ( <ChannelWrapper> <ChannelLink href={`https://www.twitch.tv/${item.name}`} target="_blank"> {item.name} ({item.game}) </ChannelLink> <FormattedNumber value={item.message_count} /> </ChannelWrapper> ); // Render the content into a list item return ( <ListItem key={`channel-count-list-item-${item.name}`} item={content} /> ); } } ChannelCountListItem.propTypes = { item: React.PropTypes.object, }; export default ChannelCountListItem; <gh_stars>0 "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 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) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports._Async_Param_ModelCompare = exports.ModelCompare = void 0; const mobius_sim_1 = require("@design-automation/mobius-sim"); const io_1 = require("../io"); // ================================================================================================ /** * Compares two models. Used for grading models. * * Checks that every entity in this model also exists in the input_data. * * Additional entitis in the input data will not affect the score. * * Attributes at the model level are ignored except for the `material` attributes. * * For grading, this model is assumed to be the answer model, and the input model is assumed to be * the model submitted by the student. * * The order or entities in this model may be modified in the comparison process. * * For specifying the location of the GI Model, you can either specify a URL, or the name of a file in LocalStorage. * In the latter case, you do not specify a path, you just specify the file name, e.g. 'my_model.gi' * * @param __model__ * @param input_data The location of the GI Model to compare this model to. * @returns Text that summarises the comparison between the two models. */ function ModelCompare(__model__, input_data) { return __awaiter(this, void 0, void 0, function* () { const input_data_str = yield (0, io_1._getFile)(input_data); if (!input_data_str) { throw new Error('Invalid imported model data'); } const input_model = new mobius_sim_1.GIModel(); input_model.importGI(input_data_str); const result = __model__.compare(input_model, true, false, false); return result.comment; }); } exports.ModelCompare = ModelCompare; function _Async_Param_ModelCompare(__model__, input_data) { return null; } exports._Async_Param_ModelCompare = _Async_Param_ModelCompare; //# sourceMappingURL=data:application/json;base64,<KEY><gh_stars>0 'use strict'; // Declare app level module which depends on views, and components angular.module('myApp', [ 'ngRoute', 'myApp.view1', 'myApp.view2', 'myApp.version', 'twitterApp.services', ]). config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/view1'}); }]). config(function ($httpProvider) { $httpProvider.defaults.headers.common = {}; $httpProvider.defaults.headers.post = {}; $httpProvider.defaults.headers.put = {}; $httpProvider.defaults.headers.patch = {}; }); angular.module('twitterApp.services', []).factory('twitterService', function($q) { var authorizationResult = false; return { initialize: function() { //initialize OAuth.io with public key of the application OAuth.initialize('pmBTV1RV7217OgmcZoI2FkqExdE', { cache: true }); //try to create an authorization result when the page loads, // this means a returning user won't have to click the twitter button again authorizationResult = OAuth.create("twitter"); }, isReady: function() { return (authorizationResult); }, connectTwitter: function() { var deferred = $q.defer(); OAuth.popup("twitter", { cache: true }, function(error, result) { // cache means to execute the callback if the tokens are already present if (!error) { authorizationResult = result; deferred.resolve(); } else { //do something if there's an error } }); return deferred.promise; }, clearCache: function() { OAuth.clearCache('twitter'); authorizationResult = false; }, getLatestTweets: function(subreddit) { //create a deferred object using Angular's $q service var deferred = $q.defer(); var url = '/1.1/search/tweets.json?q='+subreddit+'&result_type=popular'; var promise = authorizationResult.get(url).done(function(data) { // when the data is retrieved resolve the deferred object deferred.resolve(data); }).fail(function(err) { deferred.reject(err); }); //return the promise of the deferred object return deferred.promise; } } });/* Env */ process.env.MONGO_URL = 'mongodb://localhost/noobjs_test'; /* Module dependencies */ var nock = require( 'nock' ); var async = require( 'async' ); var twitter = require( './../lib/twitter' ); /* Prepare DB */ var mongojs = require( 'mongojs' ); var db = mongojs( process.env.MONGO_URL, [ 'socialDocs', 'skyttleDocs', 'geoDocs' ] ); /* Prepare Chai */ var chai = require( 'chai' ); var expect = chai.expect; chai.use( require( 'chai-datetime' ) ); /* Prepare fixtures */ var mashapeFixture = require( './fixtures/mashape.json'); var tweetFixture = require( './fixtures/tweet.json'); tweetFixture._id = new mongojs.ObjectId(); /* DB helper function */ var clearDb = function ( done ) { async.parallel( [ function ( cb ) { db.socialDocs.remove( cb ); }, function ( cb ) { db.skyttleDocs.remove( cb ); }, function ( cb ) { db.geoDocs.remove( cb ); } ], done ); } describe( 'twitter', function () { before( clearDb ); after( clearDb ); describe.skip( '#init', function () { it( 'should establish a stream connection to twitter', function () { } ); } ); describe( '#insertIntoSocialDocs', function () { it( 'should transform the tweet fixture to a simple version and insert into socialDocs', function (done) { twitter.insertIntoSocialDocs( tweetFixture ) .then( function ( ) { db.socialDocs.findOne({}, function ( err, doc ) { expect( err ).to.not.exist; expect( doc ).to.exist; expect( doc._id.toString() ).to.equal( tweetFixture._id.toString() ); expect( doc ).to.have.property( 'text', 'Along with our new #Twitterbird, we\'ve also updated our Display Guidelines: https://t.co/Ed4omjYs ^JC' ); expect( doc ).property( 'createdAt' ).to.equalDate( new Date( tweetFixture.created_at ) ); expect( doc ).to.have.property( 'user', 'twitterapi' ); expect( doc ).to.have.property( 'originId', tweetFixture.id ); expect( doc ).to.have.property( 'type', 'tweet' ); done(); } ); } ) .catch( done ); } ); } ); describe( '#insertIntoGeoDocs', function () { it( 'should not make the insert because tweet has no geo data', function ( done ) { twitter.insertIntoGeoDocs( {}, {} ) .then( function () { db.geoDocs.findOne({}, function ( err, doc ) { expect( err ).to.not.exist; expect( doc ).to.not.exist; done(); } ); } ) .catch( done ) } ); it( 'should not make the insert because no sentiment', function ( done ) { twitter.insertIntoGeoDocs( {}, null ) .then( function () { db.geoDocs.findOne({}, function ( err, doc ) { expect( err ).to.not.exist; expect( doc ).to.not.exist; done(); } ); } ) .catch( done ) } ); it( 'should insert data into geoDocs', function ( done ) { var sentimentScores = { pos: 0, neg: 1, neu: 2 }; twitter.insertIntoGeoDocs( tweetFixture, sentimentScores ) .then( function () { db.geoDocs.findOne({}, function ( err, doc ) { expect( err ).to.not.exist; expect( doc ).to.exist; expect( doc ).to.have.property( 'type', 'tweet' ); expect( doc ).to.have.property( 'socialId' ); expect( doc.socialId.toString() ).to.equal( tweetFixture._id.toString() ); expect( doc ).to.have.property( 'analyzableText', twitter.getAnalyzableText( tweetFixture.text ) ); expect( doc ).property( 'createdAt' ).to.equalDate( new Date( tweetFixture.created_at ) ); expect( doc ).to.have.deep.property( 'location.type', 'Point' ); expect( doc ).to.have.deep.property( 'location.coordinates[0]', tweetFixture.coordinates.coordinates[0] ); expect( doc ).to.have.deep.property( 'location.coordinates[1]', tweetFixture.coordinates.coordinates[1] ); expect( doc ).to.have.property( 'neg', sentimentScores.neg ); expect( doc ).to.have.property( 'neu', sentimentScores.neu ); expect( doc ).to.have.property( 'pos', sentimentScores.pos ); done(); } ); } ) .catch( done ) } ); } ); describe('#getAnalyzableText', function () { it('should do nothing', function () { var testText = "I am a plain tweet"; expect( twitter.getAnalyzableText( testText ) ) .to.equal( testText ); }); it('should remove a url', function () { var testText = "So who's trynna go with me!! (: http://t.co/m8ETAWwClV"; expect( twitter.getAnalyzableText( testText ) ) .to.equal( "So who's trynna go with me!! (:" ); }); it('should remove a url but leave hashes intact', function () { var testText = "Of course the #FremontBridge goes up when I'm #cycling #seattlecycling at Fremont Bridge https://t.co/cn2kZ3IT7g"; expect( twitter.getAnalyzableText( testText ) ) .to.equal( "Of course the #FremontBridge goes up when I'm #cycling #seattlecycling at Fremont Bridge" ); }); it('should remove trailing checkins "@"', function () { var testText = "Of course the #FremontBridge goes up when I'm cycling #seattlecycling @ Fremont Bridge https://t.co/cn2kZ3IT7g"; expect( twitter.getAnalyzableText( testText ) ) .to.equal( "Of course the #FremontBridge goes up when I'm cycling" ); }); it('should remove parenthesis wrapped checkins', function () { var testText = "Doing this thing at this place #funTimes (@ Some Place Seattle, WA)"; expect( twitter.getAnalyzableText( testText ) ) .to.equal( "Doing this thing at this place" ); }); it('should remove truncated checkins', function () { var testText = "Doing this thing at this place #funTimes @ Some Place..."; expect( twitter.getAnalyzableText( testText ) ) .to.equal( "Doing this thing at this place" ); }); it('should remove really truncated checkins', function () { var testText = "Doing this thing at this place #funTimes @..."; expect( twitter.getAnalyzableText( testText ) ) .to.equal( "Doing this thing at this place" ); }); it('should remove urls and hashes at the end of a string', function () { var testText = "Want to work in #Seattle, WA? View our latest opening: http://t.co/LfEvwGXG5H #Healthcare #Job #Jobs #Hiring http://t.co/QtStQsY5XE"; expect( twitter.getAnalyzableText( testText ) ) .to.equal( "Want to work in #Seattle, WA? View our latest opening:" ); }); }); describe( '#insertIntoSkyttleDocs', function () { it( 'should fail silently because there is no coordinates property', function ( done ) { var mashape = nock( 'https://sentinelprojects-skyttle20.p.mashape.com' ) .post( '/' ) .reply( {} ) twitter.insertIntoSkyttleDocs( {} ) .then( function ( scores ) { expect( scores ).to.not.exist; expect( mashape.isDone() ).to.not.be.ok; nock.cleanAll(); done(); }) .catch( done ); } ); it( 'should handle a 400 error', function (done) { var mashape = nock( 'https://sentinelprojects-skyttle20.p.mashape.com' ) .post( '/' ) .reply( 400, '400 Error' ) twitter.insertIntoSkyttleDocs( tweetFixture ) .then( function () { done( new Error( 'Did not handle 500' ) ); }) .catch( function ( err ) { expect( err.message ).to.equal( '400 Error' ); done(); } ); } ); it( 'should handle a 500 error', function (done) { var mashape = nock( 'https://sentinelprojects-skyttle20.p.mashape.com' ) .post( '/' ) .reply( 500, '500 Error' ) twitter.insertIntoSkyttleDocs( tweetFixture ) .then( function () { done( new Error( 'Did not handle 500' ) ); }) .catch( function ( err ) { expect( err.message ).to.equal( '500 Error' ); done(); } ); } ); it( 'should send tweet text to mashape api', function ( done ) { var mashape = nock( 'https://sentinelprojects-skyttle20.p.mashape.com' ) .post( '/' ) .reply( 200, mashapeFixture ) twitter.insertIntoSkyttleDocs( tweetFixture ) .then( function ( sentimentScores ) { expect( sentimentScores ).to.exist; db.skyttleDocs.findOne( {}, function ( err, doc ) { expect( err ).to.not.exist; expect( doc ).to.exist; expect( doc ).to.have.property( 'socialId' ); expect( doc.socialId.toString() ).to.equal( tweetFixture._id.toString() ); expect( doc ).to.have.property( 'terms' ); expect( doc ).to.have.property( 'language' ); expect( doc ).to.have.property( 'sentiment' ); expect( doc ).to.have.property( 'sentiment_scores' ); expect( doc ).to.have.deep.property( 'sentiment_scores.neg', mashapeFixture.docs[0].sentiment_scores.neg ); expect( doc ).to.have.deep.property( 'sentiment_scores.pos', mashapeFixture.docs[0].sentiment_scores.pos ); expect( doc ).to.have.deep.property( 'sentiment_scores.neu', mashapeFixture.docs[0].sentiment_scores.neu ); done(); } ); } ) .catch( done ); } ); } ); describe( '#databaseInsert', function () { it.skip( 'should insert into the database', function (done) { // body... }) }) } );<filename>src/mesh/context/geometry.js import { assignDefaults } from '../../utils' import { ScopedContext } from '../../scope' import * as defaults from '../defaults' export function MeshGeometryContext(ctx, initialState = {}) { assignDefaults(initialState, defaults) const {geometry} = initialState return ScopedContext(ctx, { geometry() { return geometry } }) } <reponame>neorayer/eg-website var FreshMsg = { del: function(messageId) { if (!confirm("您确定要删除这条信息吗?")) return false; var params = { id : messageId } var url = '../freshMsg/message.del.json.do'; $.ajax({ type : 'post', dataType : 'json', url : url, data : params, success : function(data) { if (data.res == 'no') { alert(data.data); return; }else{ window.location.reload(); } } }); return false; }, delallmsg : function(username) { if (!confirm("您确定要全部删除?")) return false; var params = { username : username } var url = '../freshMsg/message.delall.json.do'; $.ajax({ type : 'post', dataType : 'json', url : url, data : params, success : function(data) { if (data.res == 'no') { alert(data.data); return; }else{ window.location.reload(); } } }); }, vi_user : function(username) { window.location = '../player/index.jsplayout.vi?username='+username; }, vi_album : function(username,id) { window.location = '../player/photos.jsplayout.vi?username='+username+'&id='+id; }, vi_article: function(username,id) { window.location='../player/article.jsplayout.vi?username='+username+'&id='+id; } } import { createAction } from 'redux-actions'; import history from '../history'; export const register = (user) => (dispatch) => { dispatch(registerRequest()); fetch(`http://localhost:5000/auth/register`, { method: "post", body: JSON.stringify({ ...user }), headers: { 'Content-Type': 'application/json' }}) .then(res => res.json()) .then(res => { dispatch(registerSuccess(res.user)); localStorage.setItem('token', res.token); history.push("/chat") }) .catch(err => { dispatch(registerFailed(err)) }) }; export const login = (user) => (dispatch) => { dispatch(loginRequest()); fetch(`http://localhost:5000/auth/login`, { method: "post", body: JSON.stringify({ email: user.email, password: <PASSWORD>, }), headers: { 'Content-Type': 'application/json' }}) .then(res => res.json()) .then(res => { dispatch(loginSuccess(res.user)); localStorage.setItem('token', res.token); history.push("/chat") }) .catch(err => { dispatch(loginFailed(err)) }) }; export const checkAuth = () => (dispatch) => { dispatch(checkAuthRequest()); const token = localStorage.getItem('token'); fetch(`http://localhost:5000/auth/check-token`, { headers: { 'access-token': token, }}) .then(res => res.json()) .then(res => { dispatch(checkAuthSuccess(res.user)); console.log("success"); history.push("/chat") }) .catch(err => { dispatch(checkAuthFailed(err)); history.push("/login") }) }; export const logout = createAction('[User] logout'); export const registerRequest = createAction('[User] Register request'); export const registerSuccess = createAction('[User] Register success'); export const registerFailed = createAction('[User] Register failed'); export const loginRequest = createAction('[User] Login request'); export const loginSuccess = createAction('[User] Login success'); export const loginFailed = createAction('[User] Login failed'); export const checkAuthRequest = createAction('[User] Check auth request'); export const checkAuthSuccess = createAction('[User] Check auth success'); export const checkAuthFailed = createAction('[User] Check auth failed');<filename>rain/js/script.js (function() { var carArr; carArr = []; d3.csv('/taipei.csv') .row(function(d) { if (carArr.length === 0) { return carArr.push(d.CarNo); } }) .get(function(error, rows) {}); }.call(this)); <filename>chat-backend/src/libs/CreateDefaultRoles.js const Role = require('../models/Role') const Roles = require('../config/InitialRoles') const CreateDefaultRoles = async () => { try { for (const rol of Roles) { const { Name, Description } = rol const foundRole = await Role.findOne({ Name }) if (foundRole) { console.log('[✔️ ]', ' Roles default already exists') return } const newRole = await new Role({ Name, Description }).save() console.log('[✔️ ]', `The ${newRole.Name} was successfully created`) } } catch (error) { console.log('[❌]', error.message) } } module.exports = CreateDefaultRoles require('./dist/angular-popup-menu.js'); module.exports = 'angular.popup.menu'; <gh_stars>0 const client_id = '5a244bda58b546a3b8494a6362f714ec'; const client_secret = '<KEY>'; let fs = require('fs'); let { EventLoop, screen, events } = require('term_app'); let getAuthCode = require('./spotify/getAuthCode'); let getAPIToken = require('./spotify/getAPIToken.js'); let { doApiCall } = require('./spotify/doApiCall.js'); let api = require('./spotify/api'); let { getRequiredAuths } = require('./spotify/getRequiredAuths.js'); let ui = require('./ui'); let { trackInfo } = require('./spotify/mapper'); let access_token, refresh_token; let startup = async () => { try{ let code = await getAuthCode(); let tokenData = await getAPIToken(code, 'http://localhost:8888/', client_id, client_secret); console.log(JSON.stringify(tokenData, null, 2)); access_token = tokenData.access_token; let playing = await doApiCall(api.currentlyPlaying(), access_token); console.log(JSON.stringify(playing.item.artists, null, 2)); // // console.log(trackInfo(playing)); process.exit(0); }catch(err){ console.error(err); } }; //startup(); console.log(JSON.stringify(fs.fstatSync('cache.json'), null, 2)); <gh_stars>0 const contenitore = document.querySelector("#novita .containerinterno"); function creaBoxNews(titolo, immagine, descrizione, link, data){ const divbox = document.createElement('div'); divbox.classList.add('box'); const divimgbox = document.createElement('div'); const image = document.createElement('img'); image.src = immagine; const spanx = document.createElement('span'); data = data.substring(0, 10); spanx.textContent = data; const divboxcontent = document.createElement('div'); divboxcontent.classList.add('boxcontent'); const intestazione = document.createElement('h4'); /*Eliminiamo la scritta "- Salute & benessere", che è presente di default alla fine di ogni titolo nel file JSON.*/ titolo = titolo.split("- Salute & Benessere").shift(); intestazione.textContent = titolo; const parx = document.createElement('p'); /*Limitiamo la lunghezza delle descrizioni*/ if(descrizione.length > 186){ descrizione = descrizione.substring(0,186) + '...'; } parx.textContent = descrizione; const anchor = document.createElement('a'); anchor.textContent = 'Scopri di più'; anchor.href = link; contenitore.appendChild(divbox); divbox.appendChild(divimgbox); divimgbox.appendChild(image); divimgbox.appendChild(spanx); divbox.appendChild(divboxcontent); divboxcontent.appendChild(intestazione); divboxcontent.appendChild(parx); divbox.appendChild(anchor); } function onJsonNews(json) { console.log('JSON ricevuto'); console.log(json); if (json.status == 400) { const error = document.createElement("h1"); const mex = document.createTextNode(json.detail); error.appendChild(mex); stats1.appendChild(error); return; } if(json.length == 0) { const errore = document.createElement("h1"); const messaggio = document.createTextNode("Nessun risultato!"); errore.appendChild(messaggio); library.appendChild(errore); } let i = 0; contenitore.innerHTML = ''; for(result of json) { creaBoxNews(result.title, result.image, result.description, result.url, result.published); if(i>=2){ break; } i++; } } function onResponse(response) { /*console.log('Risposta ricevuta');*/ return response.json(); } fetch("news/api/").then(onResponse).then(onJsonNews); /*------------------------------------------------------------------*/ /*Le variabili dichiarate con const non possono essere riassegnate --> per questo non lo utilizziamo*/ let today = new Date(); let yesterday = new Date(today); let dd; let mm; let yyyy; function calcolaDataOggi(){ dd = String(today.getDate()).padStart(2, '0'); mm = String(today.getMonth() + 1).padStart(2, '0'); //Gennaio corrisponde a 0 yyyy = today.getFullYear(); today = yyyy + '-' + mm + '-' + dd; } function calcolaDataIeri(){ yesterday.setDate(yesterday.getDate() - 1); dd = String(yesterday.getDate()).padStart(2, '0'); mm = String(yesterday.getMonth() + 1).padStart(2, '0'); //Gennaio corrisponde a 0 yyyy = yesterday.getFullYear(); yesterday = yyyy + '-' + mm + '-' + dd; } /* /* CREDO ABBIANO ELIMINATO I DATI const stats1 = document.querySelector("#covidupdate .statistiche"); function creaParagrafiCovid(json, ultimoindice, ultimadata){ stats1.innerHTML = ''; for (let index in PARAGRAFI_COVID) { const divx = document.createElement('div'); const parx = document.createElement('p'); parx.classList.add('coloured'); parx.textContent = PARAGRAFI_COVID[index].titolo; stats1.appendChild(divx); divx.appendChild(parx); const valore = document.createElement('p'); valore.textContent = json[ultimoindice][PARAGRAFI_COVID[index].chiave]; divx.appendChild(valore); } const ultimoaggiornamentoCovid = document.createElement('span'); const paragrafoCovid = document.createElement("p"); paragrafoCovid.textContent = 'Data di ultimo aggiornamento: ' + ultimadata; paragrafoCovid.classList.add("lastupdate"); stats1.appendChild(ultimoaggiornamentoCovid); ultimoaggiornamentoCovid.appendChild(paragrafoCovid); } function onJsonCovid(json) { console.log('JSON ricevuto'); console.log(json); if (json.status == 400) { const error = document.createElement("h1"); const mex = document.createTextNode(json.detail); error.appendChild(mex); stats1.appendChild(error); return; } const ultimoindice = (json.length)-1 const ultimadata = json[ultimoindice].data; creaParagrafiCovid(json, ultimoindice, ultimadata); } url_covid = 'https://openpuglia.org/api/?q=getdatapccovid-19®=' + 'sicilia'; console.log('URL: ' + url_covid); fetch(url_covid).then(onResponse).then(onJsonCovid); */ /*-------------------------------------------------------*/ const stats2 = document.querySelector("#coviditaliaupdate .statistiche"); function creaParagrafiCovidItalia(json, data, risultato){ stats2.innerHTML = ''; for (let index in PARAGRAFI_COVID_ITALIA) { const divx = document.createElement('div'); const parx = document.createElement('p'); parx.classList.add('coloured'); parx.textContent = PARAGRAFI_COVID_ITALIA[index].titolo; stats2.appendChild(divx); divx.appendChild(parx); const valore = document.createElement('p'); valore.textContent = risultato[PARAGRAFI_COVID_ITALIA[index].chiave]; divx.appendChild(valore); } const ultimoaggiornamentoCovidItalia = document.createElement('span'); const paragrafoCovidItalia = document.createElement("p"); data = data.substring(0, 10); paragrafoCovidItalia.textContent = 'Data di ultimo aggiornamento: ' + data; paragrafoCovidItalia.classList.add("lastupdate"); stats2.appendChild(ultimoaggiornamentoCovidItalia); ultimoaggiornamentoCovidItalia.appendChild(paragrafoCovidItalia); } function onJsonCovidItalia(json) { console.log('JSON ricevuto'); console.log(json); if (json.status == 400) { const error = document.createElement("h1"); const mex = document.createTextNode(json.detail); error.appendChild(mex); stats2.appendChild(error); return; } const results = json.Countries; if(results.length == 0) { const errore = document.createElement("h1"); const messaggio = document.createTextNode("Nessun risultato!"); errore.appendChild(messaggio); library.appendChild(errore); } for(result of results) { if(result.Country === "Italy"){ creaParagrafiCovidItalia(json, result.Date, result); } } } url_covid_italia = "https://api.covid19api.com/summary"; console.log('URL: ' + url_covid_italia); fetch(url_covid_italia).then(onResponse).then(onJsonCovidItalia); /*------------------------------------------------*/ const stats3 = document.querySelector("#vacciniupdate .statistiche"); function creaParagrafiVaccini(json, risultato){ stats3.innerHTML = ''; for (let index in PARAGRAFI_VACCINI) { const divx = document.createElement('div'); const parx = document.createElement('p'); parx.classList.add('coloured'); parx.textContent = PARAGRAFI_VACCINI[index].titolo; stats3.appendChild(divx); divx.appendChild(parx); const valore = document.createElement('p'); valore.textContent = risultato[PARAGRAFI_VACCINI[index].chiave]; divx.appendChild(valore); } } function onJsonVaccini(json) { console.log('JSON ricevuto'); console.log(json); if (json.status == 400) { const error = document.createElement("h1"); const mex = document.createTextNode(json.detail); error.appendChild(mex); stats3.appendChild(error); return; } const ultimoaggiornamentoVaccini = document.createElement('span'); const paragrafoVaccini = document.createElement("p"); calcolaDataOggi(); calcolaDataIeri(); const results = json.data; if(results.length == 0) { const errore = document.createElement("h1"); const messaggio = document.createTextNode("Nessun risultato!"); errore.appendChild(messaggio); library.appendChild(errore); } let k = 0; for(result of results) { if(result.data_somministrazione.localeCompare(today + "T00:00:00.000Z") === 0){ if (result.codice_regione_ISTAT === 19){ ++k; creaParagrafiVaccini(json, result); paragrafoVaccini.textContent = 'Data di ultimo aggiornamento: ' + today; if(k === 1){ /*ESSENDO CHE I DATI SONO MESSI IN DISORDINE, QUESTO ULTERIORE CONTROLLO MI ASSICURA CHE UNA VOLTA TROVATA LA DATA DI OGGI (CHE SARà CERTAMENTE L'ULTIMA DATO CHE I DATI VENGONO CARICATI UNA VOLTA AL GIORNO) IL CICLO SI INTERROMPA --> SE NON è PRESENTE LA DATA DI OGGI, CERTAMENTE CI SARà QUELLA DEL GIORNO PRECEDENTE, PROPRIO PER QUELLA CHE è LA STRUTTURA DEL FILE JSON.*/ k = 0; break; } } } else{ if(result.data_somministrazione.localeCompare(yesterday + "T00:00:00.000Z") === 0){ if (result.codice_regione_ISTAT === 19){ creaParagrafiVaccini(json, result); paragrafoVaccini.textContent = 'Data di ultimo aggiornamento: ' + yesterday; } } } } paragrafoVaccini.classList.add("lastupdate"); stats3.appendChild(ultimoaggiornamentoVaccini); ultimoaggiornamentoVaccini.appendChild(paragrafoVaccini); } url_vaccini= 'https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/somministrazioni-vaccini-summary-latest.json'; console.log('URL: ' + url_vaccini); fetch(url_vaccini).then(onResponse).then(onJsonVaccini);<gh_stars>1-10 import React, { useEffect } from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import HomeContainer from './containers/HomeContainer' import LeaguesContainer from './containers/LeaguesContainer' import TeamsContainer from './containers/TeamsContainer' import LeagueHeroNav from './components/LeagueHeroNav'; import ResultsContainer from './containers/ResultsContainer'; import { connect } from 'react-redux'; import { fetchLeagues } from './actions/leagues'; import { fetchTeams } from './actions/teams'; import { Container } from 'react-bootstrap'; function App({fetchLeagues, fetchTeams, leagues, teams}) { useEffect(() => { fetchLeagues() fetchTeams() },[leagues.length, teams.length]) return ( <Router> <> <LeagueHeroNav /> <Container> <Route exact path="/" render={(routerProps) => <HomeContainer {...routerProps} />} /> <Route path="/leagues" render={(routerProps) => <LeaguesContainer {...routerProps} />} /> <Route path="/teams" render={(routerProps) => <TeamsContainer {...routerProps} />} /> <Route path="/results/:query" render={(routerProps) => <ResultsContainer {...routerProps} />} /> </Container> </> </Router> ); } const mapStateToProps = (state) => { return { leagues: state.leaguesReducer.leagues, teams: state.teamsReducer.teams } } export default connect(mapStateToProps, {fetchLeagues, fetchTeams})(App)import React, { memo } from "react"; // import Table from "components/Table/Table.js"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableContainer from "@material-ui/core/TableContainer"; import Paper from "@material-ui/core/Paper"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import { makeStyles, withStyles } from "@material-ui/core/styles"; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, backgroundColor: theme.palette.background.paper, }, table: { minWidth: 700, }, })); const EmployeesList = memo(({ data, onEmpClick }) => { const classes = useStyles(); const handleClick = (id, empName) => { onEmpClick({ id, empName, }); }; return ( <TableContainer component={Paper}> <Table className={classes.table} size="small" aria-label="a dense table"> <TableHead> <TableRow> <TableCell style={{ display: "none" }}>ID</TableCell> <TableCell align="right">Name</TableCell> <TableCell align="right">One-Time Code</TableCell> <TableCell align="right">Mobile Number</TableCell> <TableCell align="right">Email</TableCell> <TableCell align="right">Actions</TableCell> </TableRow> </TableHead> <TableBody> {data.map((row) => ( <TableRow key={row[0]}> <TableCell align="right" style={{ display: "none" }}> {row[0]} </TableCell> <TableCell align="right">{row[2]}</TableCell> <TableCell align="right">{row[3]}</TableCell> <TableCell align="right">{row[4]}</TableCell> <TableCell align="right">{row[5]}</TableCell> <TableCell align="right" style={{ cursor: "pointer", color: "rgb(67, 173, 193)" }} onClick={() => handleClick(row[0], row[2])} > Adjust records </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ); }); export default EmployeesList; <reponame>mighoocool/kpc import ChildrenDemo from '~/components/progress/demos/children'; import {mount, unmount, dispatchEvent} from 'test/utils'; describe('Progress', () => { let instance; afterEach(() => { unmount(instance); }); it('change percent', () => { instance = mount(ChildrenDemo); instance.set('percent', 100); expect(instance.element.outerHTML).to.matchSnapshot(); instance.set('percent', 110); expect(instance.element.outerHTML).to.matchSnapshot(); instance.set('percent', 90); expect(instance.element.outerHTML).to.matchSnapshot(); instance.set('percent', -10); expect(instance.element.outerHTML).to.matchSnapshot(); }); }); <filename>src/components/video_detail.js import React, {Component} from 'react'; import CommentCreate from './comment_create'; import CommentIndex from './comment_index'; import { Button, Collapse } from 'react-bootstrap'; class VideoDetail extends React.Component { constructor(props) { super(props); this.state = { isAddFormOpen: false }; } render() { if(!this.props.video) { return <div>Loading....</div>; } const url='https://www.youtube.com/embed/'+ this.props.video.id.videoId; // console.log(this.props.video.id.videoId); return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div><br /> <div className="details"> <h4>{this.props.video.snippet.title}</h4> <div>{this.props.video.snippet.description}</div> </div><br /> <Button bsStyle="danger" className="form-control" bsSize="small" onClick={() => this.setState({isAddFormOpen: !this.state.isAddFormOpen})} > Add Comment </Button> <br /> <br /> <Collapse in={this.state.isAddFormOpen}> <div>{ this.state.isAddFormOpen && <CommentCreate comments={this.props.comments} addComment={this.props.addComment} videoId={this.props.video.id.videoId} closeForm={() => this.setState({isAddFormOpen: false})} /> } </div> </Collapse> <br /> <CommentIndex comments={this.props.comments} videoId={this.props.video.id.videoId} deleteComment={this.props.deleteComment} saveComment={this.props.saveComment} /> </div> ); } } export default VideoDetail;const TextMessageService = require('comtele-sdk').TextMessageService; import config from '../config/variables'; const textMessageService = new TextMessageService(config.SMS_API_KEY); export default { textMessageService };<gh_stars>1-10 // 以下的 index 指的是线性表的顺序存储结构中第 index 处的位置,是从 1 开始的 /** * 线性表顺序存储结构的插入 * @param {*} list 线性表 * @param {*} index 插入的位置 * @param {*} ele 插入的元素 */ export function listInsert(list, index, ele) { //如果插入的位置不对,返回错误 //插入的位置可以是线性表中任意一个位置或者在线性表的末端插入,也就是list.length + 1 if (index < 1 || index > list.length + 1) { return false } //若插入的位置不在表尾 if (index <= list.length) { //将要插入位置后的数据元素向右移动一位 let i = list.length - 1 for (i; i >= index - 1; i--) { list[i + 1] = list[i] } } //插入新元素 //list.length++; js可以直接通过赋值的方式给数组扩容,不存在越界,所以不需要手动加长度 list[index - 1] = ele } /** * 线性表顺序存储结构的删除 * @param {*} list 线性表 * @param {*} index 删除的位置 */ export function listDelete(list, index) { //线性表为空 if (list.length == 0) { return false } //如果删除的位置不对,返回错误 if (index < 1 || index > list.length) { return false } //取出删除位置的元素 const ele = list[index - 1] //如果删除的不是最后位置 if (index < list.length) { //将要删除的位置后的元素数据向左移动一位 let i = index for (i; i < list.length; i++) { list[i - 1] = list[i] } } list.length-- return ele } /** * 线性表顺序存储结构获取 index 处的元素 * @param {*} list * @param {*} index * @returns */ export function getElem(list, index) { if (list.length == 0 || index < 1 || index > list.length) { return false } return list[index - 1] } import React from 'react'; import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; import Code from './../../../../components/Code/Code'; import Iframe from './../../../../components/Iframe/Iframe'; import demo01 from './demos/demo-01.pug'; import demo02 from './demos/demo-02.pug'; import demo03 from './demos/demo-03.pug'; import demo04 from './demos/demo-04.pug'; import demo05 from './demos/demo-05.pug'; import demo06 from './demos/demo-06.pug'; import demo07 from './demos/demo-07.pug'; import demo08 from './demos/demo-08.pug'; import axaComponents from './axa-components.scss'; const demos = [ { title: 'Default Card', cmpt: demo01 }, { title: 'Disabled Card', cmpt: demo02 }, { title: 'Selected Card', cmpt: demo03 }, { title: 'Default selected Card', cmpt: demo04 }, { title: 'Group Card with selected', cmpt: demo05 }, { title: 'Default Group 3 Cards', cmpt: demo06 }, { title: ' Group 4 Cards with selected', cmpt: demo07 }, { title: ' Group 5 Cards with selected', cmpt: demo08 }, ]; const styles = [axaComponents]; const Card = () => ( <article className="component"> <h2 className="component__title">Card</h2> {demos.map(demo => ( <div key={demo.title}> <h3 className="af-subtitle">{demo.title}</h3> <Tabs> <TabList> <Tab>Démo</Tab> <Tab>Code</Tab> </TabList> <TabPanel> <Iframe height="500" css={styles} template={demo.cmpt} /> </TabPanel> <TabPanel> <Code template={demo.cmpt} /> </TabPanel> </Tabs> </div> ))} </article> ); export default Card; import React, { Component } from "react"; import Navigation from "./navigation/navigation"; import { Route, Switch } from "react-router"; import Signin from "./Auth/signin"; import Signup from "./Auth/signup"; import ForgotPassword from "./Auth/forgotpassword"; import CatchAll from "./catchall"; import Home from "./pages/home"; import Dashboard from "./pages/dashboard"; import About from "./pages/about"; import Contact from "./pages/contact"; import Faq from "./pages/faq"; export default class App extends Component { render() { return ( <div className="app"> <div className="background"></div> <Navigation /> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/dashboard" component={Dashboard} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> <Route path="/faq" component={Faq} /> <Route path="/signin" component={Signin} /> <Route path="/signup" component={Signup} /> <Route path="/forgotpassword" component={ForgotPassword} /> <Route component={CatchAll} /> </Switch> </div> ); } } <filename>src/particle/generators/index.js export * from './Tw2RandomIntegerAttributeGenerator'; export * from './Tw2RandomUniformAttributeGenerator'; export * from './Tw2SphereShapeAttributeGenerator'; // Return the ElementType element type of the given element. function typeForElement(el) { // TODO: handle background images that aren't just the BODY. switch (el.nodeName.toUpperCase()) { case 'INPUT': case 'IMG': return ElementTypes.image; case 'SCRIPT': return ElementTypes.script; case 'OBJECT': case 'EMBED': return ElementTypes.object; case 'VIDEO': case 'AUDIO': case 'SOURCE': return ElementTypes.media; case 'FRAME': case 'IFRAME': return ElementTypes.subdocument; case 'LINK': // favicons are reported as 'other' by onBeforeRequest. // if this is changed, we should update this too. if (/(^|\s)icon($|\s)/i.test(el.rel)) return ElementTypes.other; return ElementTypes.stylesheet; case 'BODY': return ElementTypes.background; default: return ElementTypes.NONE; } } // If url is relative, convert to absolute. function relativeToAbsoluteUrl(url) { // Author: <NAME> AdThwart if (!url) return url; // If URL is already absolute, don't mess with it if (/^[a-zA-Z\-]+\:/.test(url)) return url; if (url[0] == '/') { // Leading // means only the protocol is missing if (url[1] && url[1] == "/") return document.location.protocol + url; // Leading / means absolute path return document.location.protocol + "//" + document.location.host + url; } // Remove filename and add relative URL to it var base = document.baseURI.match(/.+\//); if (!base) return document.baseURI + "/" + url; return base[0] + url; } //Do not make the frame display a white area //Not calling .remove(); as this causes some sites to reload continuesly function removeFrame(el) { var parentEl = el.parentNode; var cols = ((parentEl.getAttribute('cols') || "").indexOf(',') > 0); if (!cols && (parentEl.getAttribute('rows') || "").indexOf(',') <= 0) return; // Figure out which column or row to hide var index = 0; while (el.previousElementSibling) { index++; el = el.previousElementSibling; } // Convert e.g. '40,20,10,10,10,10' into '40,20,10,0,10,10' var attr = (cols ? 'cols' : 'rows'); var sizes = parentEl.getAttribute(attr).split(','); sizes[index] = "0"; parentEl.setAttribute(attr, sizes.join(',')); } // Remove an element from the page. function destroyElement(el, elType) { if (el.nodeName == "FRAME") { removeFrame(el); } else if (elType != ElementTypes.script) { // There probably won't be many sites that modify all of these. // However, if we get issues, we might have to set the location and size // via the css properties position, left, top, width and height el.style.setProperty("display", "none", "important"); el.style.setProperty("visibility", "hidden", "important"); el.style.setProperty("opacity", "0", "important"); var w = (el.width === undefined ? -1 : el.width); var h = (el.height === undefined ? -1 : el.height); el.style.setProperty("background-position", w + "px " + h + "px"); el.setAttribute("width", 0); el.setAttribute("height", 0); } } // Add style rules hiding the given list of selectors. function block_list_via_css(selectors) { if (!selectors.length) return; // Issue 6480: inserting a <style> tag too quickly ignored its contents. // Use ABP's approach: wait for .sheet to exist before injecting rules. var css_chunk = document.createElement("style"); css_chunk.type = "text/css"; // Documents may not have a head (document.head || document.documentElement).insertBefore(css_chunk, null); function fill_in_css_chunk() { if (!css_chunk.sheet) { window.setTimeout(fill_in_css_chunk, 0); return; } var GROUPSIZE = 1000; // Hide in smallish groups to isolate bad selectors for (var i = 0; i < selectors.length; i += GROUPSIZE) { var line = selectors.slice(i, i + GROUPSIZE); var rule = line.join(",") + " { display:none !important; orphans: 4321 !important; }"; css_chunk.sheet.insertRule(rule); } } fill_in_css_chunk(); } function debug_print_selector_matches(selectors) { selectors. filter(function(selector) { return document.querySelector(selector); }). forEach(function(selector) { var matches = ""; var elems = document.querySelectorAll(selector); for (var i=0; i<elems.length; i++) { var el = elems[i]; matches += " " + el.nodeName + "#" + el.id + "." + el.className + "\n"; } if (SAFARI) { log("Debug: CSS '" + selector + "' hid:"); log(matches); } else BGcall("debug_report_elemhide", selector, matches); }); } function handleABPLinkClicks() { // Subscribe to the list when you click an abp: link var elems = document.querySelectorAll('[href^="abp:"], [href^="ABP:"]'); var abplinkhandler = function(event) { event.preventDefault(); var searchquery = this.href.replace(/^.+?\?/, '?'); if (searchquery) { var queryparts = parseUri.parseSearch(searchquery); var loc = queryparts.location; var reqLoc = queryparts.requiresLocation; var reqList = (reqLoc ? "url:" + reqLoc : undefined); BGcall("subscribe", {id: "url:" + loc, requires: reqList}); window.open(chrome.extension.getURL('pages/subscribe.html?' + loc), "_blank", 'scrollbars=0,location=0,resizable=0,width=450,height=140'); } }; for (var i=0; i<elems.length; i++) { elems[i].addEventListener("click", abplinkhandler, false); } } // Called at document load. // inputs: // startPurger: function to start watching for elements to remove. // stopPurger: function to stop watch for elemenst to remove, called in case // AdBlock should not be running. // success?: function called at the end if AdBlock should run on the page. function adblock_begin(inputs) { if (document.location.href === 'about:blank') // Safari does this return; if (!(document.documentElement instanceof HTMLElement)) return; // Only run on HTML pages inputs.startPurger(); var opts = { domain: document.location.hostname }; BGcall('get_content_script_data', opts, function(data) { if (data.page_is_whitelisted || data.adblock_is_paused || data.disabled_site) { inputs.stopPurger(); return; } if (data.settings.debug_logging) log = function() { if (VERBOSE_DEBUG || arguments[0] !== '[DEBUG]') console.log.apply(console, arguments); }; block_list_via_css(data.selectors); onReady(function() { if (data.settings.debug_logging) debug_print_selector_matches(data.selectors); // Chrome doesn't load bandaids.js unless the site needs a bandaid. if (typeof run_bandaids === "function") run_bandaids("new"); handleABPLinkClicks(); }); if (inputs.success) inputs.success(); }); } <filename>config/crawler.js const crawler = { maxConnections: 1, forceUTF8: true, incomingEncoding: 'utf-8', skipDuplicates: true, userAgent: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', referer: 'https://www.google.com', jQuery: false }; module.exports = { crawler };'use strict' var fs = require('fs') // dreaded pyramid/arrow pattern fs.readFile('data.js', function(err, data) { console.log("TRACER OK on data.js") fs.readFile('data2.js', function(err, data) { console.log("TRACER OK on data2.js") fs.readFile('data3.js', function(err, data) { console.log("TRACER OK on data3.js") }) }) }) "use strict"; var ToleechUser = (function () { function ToleechUser() { } return ToleechUser; }()); exports.ToleechUser = ToleechUser; //# sourceMappingURL=ToleechUser.js.map<gh_stars>0 "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 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) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.startStateMachine = void 0; const client_sfn_1 = require("@aws-sdk/client-sfn"); const startStateMachine = (stateMachineARN, offlineStateMachineARN, data, offlineMode = false) => __awaiter(void 0, void 0, void 0, function* () { let config = { region: 'ap-southeast-2' }; let params; let currentStateMachine = stateMachineARN; if (offlineMode) { currentStateMachine = offlineStateMachineARN; config = { region: 'ap-southeast-2', endpoint: 'http://localhost:8083', }; } params = { stateMachineArn: currentStateMachine, input: JSON.stringify(data), }; const client = new client_sfn_1.SFNClient(config); console.log('State Machine|Initiating...'); try { const command = new client_sfn_1.StartExecutionCommand(params); yield client.send(command); console.log('State Machine|Initiated'); } catch (err) { console.log('State Machine|Failed to Initiate', err); } }); exports.startStateMachine = startStateMachine; //# sourceMappingURL=index.js.mapconst mongoose = require("mongoose"); const timestampPlugin = require("./plugins/timestamp"); const modelName = "RoomParticipant"; let schema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, room: { type: mongoose.Schema.Types.ObjectId, ref: "Room" }, status: { type: String, default: "active" } }); schema.plugin(timestampPlugin); module.exports = mongoose.model(modelName, schema); <gh_stars>10-100 /* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ (function () { angular .module('artCuratorApp') .controller('SettingsController', SettingsController); // Inject dependencies to protect app from minification. SettingsController.$inject = ['localStorageService', 'adalAuthenticationService', '$location']; /** * The code for SettingsController. Handles the form logic for settings.html. */ function SettingsController(localStorageService, adalService, $location) { var vm = this; // If user logs out while on the settings page, this will make sure they get sent back to the root. if (!adalService.userInfo.isAuthenticated) { $location.path('/'); } var settingsKeys = ['targetFolder', 'likeMarkAsRead', 'likeRespond', 'likeResponse', 'dislikeMarkAsRead', 'dislikeRespond', 'dislikeResponse']; vm.settingsValues = {}; // Get values from localStorage for all settings. settingsKeys.forEach(function (key) { vm.settingsValues[key] = localStorageService.get(key + adalService.userInfo.userName); if (key != 'targetFolder' && key != 'likeResponse' && key != 'dislikeResponse') { vm.settingsValues[key] = localStorageService.get(key + adalService.userInfo.userName) == 'true' || localStorageService.get(key + adalService.userInfo.userName) == true; } }); vm.signedInUser = adalService.userInfo.userName; /** * Save settings on click and redirect to the main page. */ vm.saveSettings = function () { settingsKeys.forEach(function (key) { var result = localStorageService.set(key + adalService.userInfo.userName, vm.settingsValues[key]); if (!result) { console.log('Error saving :', key); vm.error = true; } }); $location.path('/'); }; /** * Log out the user and redirect to the root page. */ vm.logOut = function () { adalService.logOut(); $location.path('/'); }; }; })(); // ********************************************************* // // O365-Angular-ArtCurator, https://github.com/OfficeDev/O365-Angular-ArtCurator // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // *********************************************************<reponame>Gichia/react-todo-app import React, { Component } from 'react' import { Link } from 'react-router-dom' import Moment from 'react-moment' import Spinner from '../layout/Spinner' import axios from 'axios' class Single extends Component { state = { todo: [] } componentDidMount() { axios.get(`http://192.168.0.35:3000/notes/${this.props.match.params.id}`) .then(res => { this.setState({todo: res.data[0]}); }) .catch(err => console.log(err)) } render() { const { todo } = this.state; if (todo === undefined || todo.length === 0) { return <Spinner /> } else { return ( <React.Fragment> <div className="col-md-8"> <Link to="/" className="btn btn-dark mb-2"> <i className="fas fa-chevron-left"></i> Back </Link> <div className="card"> <div className="card-header"> Note by {todo.user_name} </div> <div className="card-body"> <blockquote className="blockquote mb-0"> <p> {todo.note} </p> <footer className="blockquote-footer"> Created On: <cite title="Source Title"> <Moment format="MM/DD/YYYY">{todo.entry_date}</Moment> </cite> </footer> </blockquote> </div> </div> </div> </React.Fragment> ) } } } export default Single; <filename>db_connectors/updateShows.js var showsSAS = require("../bmsScrappers/shows"); //api from Scrap All Shows var ShowsWithEventDetails = require("./showsWithEventDetails"); var Promise = require("bluebird"); var _ = require("underscore"); module.exports = function(redisClient,mongoDb){ if (!mongoDb) { throw Error("Mongo Data Base Not Specified"); } if (!redisClient) { throw Error("Redis Client Not Specified"); } this.insertAllShows = function(eventCode,cityCode,date,debug) { var collection = debug ? "test" : "bms"; return showsSAS(cityCode,eventCode,date).then(function(shows) { return ShowsWithEventDetails(redisClient,shows,eventCode); }).then(function(showsWithEventDetails){ if(showsWithEventDetails.length==0) return 0; else if(showsWithEventDetails.length==1) return mongoDb.collection(collection).insert(showsWithEventDetails); else return mongoDb.collection(collection).insertMany(showsWithEventDetails); }); }; this.updateAllShows = function(eventCode,cityCode,date,debug) { var collection = debug ? "test" : "bms"; return showsSAS(cityCode, eventCode, date).then(function(shows){ return shows; }).map(function (show) { return mongoDb.collection(collection) .update(_.pick(show,"showId","eventCode","city"), {$currentDate: {lastModified: true}, $set: {tickets: show.tickets}}); }) }; };import Immutable from 'immutable'; let initialState = { show_loading: '', form_login_status: '', form_adduser_status: '', form_addpoll_title: '', form_addpoll_options: Immutable.List([]), form_addpoll_status: '', poll_vote_status: '', voted_poll_ids: Immutable.List([]), edit_poll_status: '' }; export function frontend (state = Immutable.Map(initialState), action) { if (action.type === 'ACTION_SHOW_LOADING') { return state.set('show_loading', '1'); } else if (action.type === 'ACTION_HIDE_LOADING') { return state.set('show_loading', ''); } else if (action.type === 'ACTION_FORM_ADD_USER_STATUS_SUCCESS') { return state.set('form_adduser_status', action.payload); } else if (action.type === 'ACTION_FORM_ADD_USER_STATUS_FAIL') { return state.set('form_adduser_status', action.payload); } else if (action.type === 'ACTION_FRONTEND_ADD_POLL_OPTION') { let ss = state.get('form_addpoll_options'); return state.set('form_addpoll_options', ss.push(action.payload)); } else if (action.type === 'ACTION_FRONTEND_DELETE_ADD_POLL_OPTION') { let ss = state.get('form_addpoll_options'); return state.set('form_addpoll_options', ss.delete(action.payload)); } else if (action.type === 'ACTION_ADD_POLL_STATUS_SUCCESS') { // let ss = state.get('form_addpoll_options') return state.set('form_addpoll_options', Immutable.List([])) .set('form_addpoll_status', action.payload); } else if (action.type === 'ACTION_POLL_VOTE_SUCCESS') { return state.set('poll_vote_status', action.payload); } else if (action.type === 'ACTION_POLL_VOTE_FAIL') { return state.set('poll_vote_status', action.payload); } else if (action.type === 'ACTION_POLL_VOTE_ERROR') { return state.set('poll_vote_status', action.payload); } else if (action.type === 'ACTION_UPDATE_VOTED_POLLS_ID') { let ss = state.get('voted_poll_ids'); return state.set('voted_poll_ids', ss.push(action.payload)); } else if (action.type === 'ACTION_NEW_OPTION_ADDED_SUCCESS') { return state.set('edit_poll_status', action.payload); } else if (action.type === 'ACTION_NEW_OPTION_ADDED_FAIL') { return state.set('edit_poll_status', action.payload); } else if (action.type === 'ACTION_NEW_OPTION_ADDED_ERROR') { return state.set('edit_poll_status', action.payload); } else if (action.type === 'ACTION_DELETE_POLL_OPTION_SUCCESS') { return state.set('edit_poll_status', action.payload); } else if (action.type === 'ACTION_DELETE_POLL_OPTION_FAIL') { return state.set('edit_poll_status', action.payload); } else if (action.type === 'ACTION_DELETE_POLL_OPTION_ERROR') { return state.set('edit_poll_status', action.payload); } else if (action.type === 'ACTION_UPDATE_POLL_TITLE_SUCCESS') { return state.set('edit_poll_status', action.payload); } else if (action.type === 'ACTION_UPDATE_POLL_TITLE_FAIL') { return state.set('edit_poll_status', action.payload); } else if (action.type === 'ACTION_UPDATE_POLL_TITLE_ERROR') { return state.set('edit_poll_status', action.payload); } else if (action.type === 'ACTION_DELETE_POLL_SUCCESS') { return state.set('form_addpoll_status', action.payload); } else if (action.type === 'ACTION_DELETE_POLL_FAIL') { return state.set('form_addpoll_status', action.payload); } else { return state; } } <reponame>uc-cdis/gen3-qa /* This test plan has a few pre-requisites: 1. MDS (MetaData Service) must be deployed to the target environment 2. Existing data in the blobstore should not conflict with records injected by the tests */ Feature('Metadata Service - PXP-5336'); const stringify = require('json-stringify-safe'); // To be executed with GEN3_SKIP_PROJ_SETUP=true // No need to set up program / retrieve access token, etc. const { expect } = require('chai'); const { interactive, ifInteractive } = require('../../utils/interactive.js'); const { requestUserInput } = require('../../utils/apiUtil'); const TARGET_ENVIRONMENT = process.env.GEN3_COMMONS_HOSTNAME || 'qa-dcf.planx-pla.net'; const testData = { filter1: 'a=1', filter2: 'nestedData.b=2', fictitiousRecord1: { guid: '91cfab02-b87a-498b-bf0a-14180e6768b7', a: 1, }, fictitiousRecord2: { guid: '354881f3-a928-4835-9368-6c02d40f75a0', nestedData: { b: 2, }, }, }; const expectedResponses = { positiveQuery1: [ '91cfab02-b87a-498b-bf0a-14180e6768b7', ], positiveQuery2: [ '354881f3-a928-4835-9368-6c02d40f75a0', ], negativeQuery: [], validationErrorQuery: { detail: [ { loc: [ 'string', ], msg: 'string', type: 'string', }, ], }, }; async function setupCredentials(I) { if (!I.cache.USERNAME) I.cache.USERNAME = await requestUserInput('Please provide a username: '); if (!I.cache.PASSWORD) I.cache.PASSWORD = await requestUserInput('Please provide a password: '); } function getAuthHeader(username, password) { const encodedCreds = Buffer.from(`${username}:${password}`).toString('base64'); return { Accept: 'application/json', Authorization: `Basic ${encodedCreds}`, }; } async function deleteRecord(I, guid) { const deleteRes = await I.sendDeleteRequest( `https://${TARGET_ENVIRONMENT}/mds/metadata/${guid}`, getAuthHeader(I.cache.USERNAME, I.cache.PASSWORD), ).then((res) => res); if (deleteRes.status !== 200) { console.log(`WARN: Could not delete record ${guid}: ${stringify(deleteRes.data)}`); } } BeforeSuite(async ({ I }) => { console.log('Setting up dependencies...'); I.cache = {}; console.log('deleting existing test records...'); await setupCredentials(I); await deleteRecord(I, testData.fictitiousRecord1.guid); await deleteRecord(I, testData.fictitiousRecord2.guid); }); // Scenario #1 - Testing POST /mds-admin/metadata_index/{GUID}: Create record Scenario('Create records against the metadata svc blobstore - positive test @manual', ifInteractive( async ({ I }) => { await setupCredentials(I); const httpResp1 = await I.sendPostRequest( `https://${TARGET_ENVIRONMENT}/mds/metadata/${testData.fictitiousRecord1.guid}`, testData.fictitiousRecord1, getAuthHeader(I.cache.USERNAME, I.cache.PASSWORD), ).then(({ res }) => res); const httpResp2 = await I.sendPostRequest( `https://${TARGET_ENVIRONMENT}/mds/metadata/${testData.fictitiousRecord2.guid}`, testData.fictitiousRecord2, getAuthHeader(I.cache.USERNAME, I.cache.PASSWORD), ).then(({ res }) => res); const result = await interactive(` 1. [Automated] Send two HTTP POST requests with the user's credentials to create records in the metadata service's database: HTTP POST request to: https://${TARGET_ENVIRONMENT}/mds/metadata/${testData.fictitiousRecord1.guid} and https://${TARGET_ENVIRONMENT}/mds/metadata/${testData.fictitiousRecord2.guid} Manual verification: Response status request #1: ${httpResp1.status} // Expect a HTTP 201 Response status request #2: ${httpResp2.status} // Expect a HTTP 201 Response 1: ${stringify(httpResp1.data)} ExpectedResponse 1: ${expectedResponses.positiveQuery1[0]} Automated check: ${httpResp1.data.guid === expectedResponses.positiveQuery1[0]} Response 2: ${stringify(httpResp2.data)} ExpectedResponse 2: ${expectedResponses.positiveQuery2[0]} Automated check: ${httpResp2.data.guid === expectedResponses.positiveQuery2[0]} // Expect the correspondent GUIDs in both responses `); expect(result.didPass, result.details).to.be.true; }, )); // Scenario #2 - Testing GET /metadata_index: return keys from stored records Scenario('Get existing keys from metadata records - positive test @manual', ifInteractive( async ({ I }) => { await setupCredentials(I); const httpResp = await I.sendGetRequest( `https://${TARGET_ENVIRONMENT}/mds/metadata`, ).then(({ res }) => res); const result = await interactive(` 1. [Automated] Send a HTTP GET request to retrieve the GUIDs (keys only) from records stored previously HTTP GET request to: https://${TARGET_ENVIRONMENT}/mds/metadata Manual verification: Response status: ${httpResp.status} // Expect a HTTP 200 Response data: ${stringify(httpResp.data)} // Expect GUIDs ${expectedResponses.positiveQuery1} ${expectedResponses.positiveQuery2} `); expect(result.didPass, result.details).to.be.true; }, )); // Scenario #3 - Testing GET /metadata: Apply filter to retrieve specific records Scenario('Query metadata for matching records - positive test @manual', ifInteractive( async ({ I }) => { await setupCredentials(I); const httpResp1 = await I.sendGetRequest( `https://${TARGET_ENVIRONMENT}/mds/metadata?${testData.filter1}`, ).then(({ res }) => res); const httpResp2 = await I.sendGetRequest( `https://${TARGET_ENVIRONMENT}/mds/metadata?${testData.filter2}`, ).then(({ res }) => res); const result = await interactive(` 1. [Automated] Send a couple of HTTP GET requests with the user's credentials to query the metadata service: HTTP GET request to: https://${TARGET_ENVIRONMENT}/mds-admin/metadata?${testData.filter1} HTTP GET request to: https://${TARGET_ENVIRONMENT}/mds-admin/metadata?${testData.filter2} Manual verification: Result of query 1: ${testData.filter1} Response status: ${httpResp1.status} // Expect a HTTP 200 Response data: ${stringify(httpResp1.data)} // Expect a JSON payload containing the metadata service records whose parameters match the filter's criteria: ${expectedResponses.positiveQuery1} Result of query 2: ${testData.filter2} Response status: ${httpResp2.status} // Expect a HTTP 200 Response data: ${stringify(httpResp2.data)} // Expect a JSON payload containing the metadata service records whose parameters match the filter's criteria: ${expectedResponses.positiveQuery2} `); expect(result.didPass, result.details).to.be.true; }, )); const URL = require("url").URL; // keys.js figures out what set of keys to use if (process.env.NODE_ENV === "production") { // We are in prod const rtgConfig = new URL(process.env.REDISTOGO_URL); module.exports = { port: rtgConfig.port, hostname: rtgConfig.hostname, password: <PASSWORD> }; } else { // We are in dev module.exports = { host: "127.0.0.1", port: "6379" }; } import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import './index.css'; import App from './App'; import CssBaseline from '@material-ui/core/CssBaseline'; import axios from 'axios'; // global.serverAddress = "http://172.16.16.164:5000/api"; // global.serverAddress = "http://172.16.17.195:5000/api"; // global.serverAddress = "http://localhost:5000/api"; // global.streamServerAddress = "http://localhost:8001/api"; console.log("process.env",process.env) if(process.env.REACT_APP_PROJECT_MODE=="Home") global.serverAddress = process.env.REACT_APP_URL_HOME; else if(process.env.REACT_APP_PROJECT_MODE=="Office") global.serverAddress = process.env.REACT_APP_URL_OFFICE; else if(process.env.REACT_APP_PROJECT_MODE=="Server") global.serverAddress = process.env.REACT_APP_URL_SERVER; global.serverAddress+="/api" var callApi=async () => { const response = await axios({ method: 'post', url: global.serverAddress + '/users/me', headers: { "x-access-token": localStorage.getItem('token') } }); if (response.status !== 200) throw Error(response.message); return response; }; callApi().then(res=>{ console.log("res: ",res,Date.now()) global.userType =res.data.userType }) ReactDOM.render( // routes, <BrowserRouter> <React.Fragment> <CssBaseline /> <App /> </React.Fragment> </BrowserRouter> , document.getElementById('root'), ); // registerServiceWorker(); <reponame>lbke/awesome-vulcan import Users from "meteor/vulcan:users"; Users.groups.members.can([ "package.create", "package.update.own", "package.delete.own" ]); Users.groups.admins.can(["package.update.all", "package.delete.all,"]); <reponame>andres11362/pruebaujaveriana<gh_stars>0 $('#registro').click(function (e){ //indicamos el evento del boton con el id registro var $dato = $('#nombre').val(); var $dpto = $('#dpto').val(); //definimos los valores en los controles var $route = 'http://localhost:8000/municipio'; //indicamos la ruta del controlador en este caso de creacion var $token = $('#token').val(); //enviamos el valor del token de la aplicacion e.preventDefault(); //evitamos que la pagina se recargue $.ajax({ //iniciamos la peticion ajax url: $route, //definimos la ruta que sera la variable route headers: {'X-CSRF-TOKEN': $token}, //definimos el encabezado de la peticion, que sera el token type: 'POST', //tipo de peticion dataType: 'json', //tipo de datos que retornara data: {nombre: $dato, departamento_id: $dpto}, //datos que se envian success: function () { $('#msj-success').fadeIn(); //en caso que se haga la peticion se mostrara un mensaje indicando que fue correcto $('#nombre').val(""); //se limpian los valores $('#dpto').val('Selecciona departamento'); }, error: function (msj){ $('#msj').html(msj.responseJSON.nombre); //en caso de no ejecutarse la peticion creara una lista con los errores $('#msj-error').fadeIn(); //que envia en el json y los mostrara en un mensaje } }); }); /* * @Author: yinyongqian * @Description: * @Date: 2018-11-13 14:45:12 * @LastEditors: yinyongqian * @LastEditTime: 2018-11-28 10:13:02 */ // RRCTopView.js 'use strict'; import React, { Component } from "react"; import { StyleSheet, AppRegistry, DeviceEventEmitter, View, Animated, Dimensions } from 'react-native'; const { width, height } = Dimensions.get('window') let keyValue = 0; const rrcRNLoadingKey = 'rrc-rn-loading-key' export default class RRCTopView extends Component { static addAlert(element) { let key = ++keyValue; DeviceEventEmitter.emit("addOverlay-Alert", { key, element }); return key; } static addLoading(element) { let key = rrcRNLoadingKey; DeviceEventEmitter.emit("addOverlay-Loading", { key, element }); return key; } static addToast(element) { let key = ++keyValue; DeviceEventEmitter.emit("addOverlay-Toast", { key, element }); return key; } static removeLoading() { DeviceEventEmitter.emit("removeOverlay-Loading"); } static removeAlert(key) { DeviceEventEmitter.emit("removeOverlay-Alert", { key }); } static removeToast(key) { DeviceEventEmitter.emit("removeOverlay-Toast", { key }); } static removeAll() { DeviceEventEmitter.emit("removeAllOverlay-Alert", {}); } static transform(transform, animated, animatesOnly = null) { DeviceEventEmitter.emit("transformRoot-Alert", { transform, animated, animatesOnly }); } static restore(animated, animatesOnly = null) { DeviceEventEmitter.emit("restoreRoot-Alert", { animated, animatesOnly }); } constructor(props) { super(props); this.state = { elements: [], translateX: new Animated.Value(0), translateY: new Animated.Value(0), scaleX: new Animated.Value(1), scaleY: new Animated.Value(1), toastElements: [], }; } componentWillMount() { DeviceEventEmitter.addListener("addOverlay-Alert", e => this.addAlertToTopView(e)); DeviceEventEmitter.addListener("removeOverlay-Alert", e => this.removeAlertFromTopView(e)); DeviceEventEmitter.addListener("removeAllOverlay-Alert", e => this.removeAll(e)); DeviceEventEmitter.addListener("transformRoot-Alert", e => this.transform(e)); DeviceEventEmitter.addListener("restoreRoot-Alert", e => this.restore(e)); DeviceEventEmitter.addListener("addOverlay-Loading", e => this.addLoadingToTopView(e)); DeviceEventEmitter.addListener("removeOverlay-Loading", () => this.removeLoadingFromTopView()); DeviceEventEmitter.addListener("addOverlay-Toast", e => this.addToastToTopView(e)); DeviceEventEmitter.addListener("removeOverlay-Toast", (e) => this.removeLToastFromTopView(e)); } componentWillUnmount() { DeviceEventEmitter.removeAllListeners("addOverlay-Alert"); DeviceEventEmitter.removeAllListeners("removeOverlay-Alert"); DeviceEventEmitter.removeAllListeners("removeAllOverlay-Alert"); DeviceEventEmitter.removeAllListeners("transformRoot-Alert"); DeviceEventEmitter.removeAllListeners("restoreRoot-Alert"); DeviceEventEmitter.removeAllListeners("addOverlay-Loading"); DeviceEventEmitter.removeAllListeners("removeOverlay-Loading"); DeviceEventEmitter.removeAllListeners("addOverlay-Toast"); DeviceEventEmitter.removeAllListeners("removeOverlay-Toast"); } addAlertToTopView(e) { let { elements } = this.state; elements.push(e); this.setState({ elements }); } removeAlertFromTopView(e) { let { elements } = this.state; for (let i = elements.length - 1; i >= 0; --i) { if (elements[i].key === e.key) { elements.splice(i, 1); break; } } this.setState({ elements }); } removeLToastFromTopView(e) { let { toastElements } = this.state; for (let i = toastElements.length - 1; i >= 0; --i) { if (toastElements[i].key === e.key) { toastElements.splice(i, 1); break; } } this.setState({ toastElements }); } addLoadingToTopView(e) { let { elements } = this.state; for (let i = elements.length - 1; i >= 0; --i) { if (elements[i].key === rrcRNLoadingKey) { elements.splice(i, 1); } } elements.push(e); this.setState({ elements }); } removeLoadingFromTopView() { let { elements } = this.state; for (let i = elements.length - 1; i >= 0; --i) { if (elements[i].key === rrcRNLoadingKey) { elements.splice(i, 1); break; } } this.setState({ elements }); } addToastToTopView(e) { let { toastElements } = this.state; toastElements.push(e); this.setState({ toastElements }); } removeAll(e) { let { elements } = this.state; this.setState({ elements: [] }); } transform(e) { let { translateX, translateY, scaleX, scaleY } = this.state; let { transform, animated, animatesOnly } = e; let tx = 0, ty = 0, sx = 1, sy = 1; transform.map(item => { if (item && typeof item === 'object') { for (let name in item) { let value = item[name]; switch (name) { case 'translateX': tx = value; break; case 'translateY': ty = value; break; case 'scaleX': sx = value; break; case 'scaleY': sy = value; break; } } } }); if (animated) { let animates = [ Animated.spring(translateX, { toValue: tx, friction: 9 }), Animated.spring(translateY, { toValue: ty, friction: 9 }), Animated.spring(scaleX, { toValue: sx, friction: 9 }), Animated.spring(scaleY, { toValue: sy, friction: 9 }), ]; animatesOnly ? animatesOnly(animates) : Animated.parallel(animates).start(); } else { if (animatesOnly) { let animates = [ Animated.timing(translateX, { toValue: tx, duration: 1 }), Animated.timing(translateY, { toValue: ty, duration: 1 }), Animated.timing(scaleX, { toValue: sx, duration: 1 }), Animated.timing(scaleY, { toValue: sy, duration: 1 }), ]; animatesOnly(animates); } else { translateX.setValue(tx); translateY.setValue(ty); scaleX.setValue(sx); scaleY.setValue(sy); } } } restore(e) { let { translateX, translateY, scaleX, scaleY } = this.state; let { animated, animatesOnly } = e; if (animated) { let animates = [ Animated.spring(translateX, { toValue: 0, friction: 9 }), Animated.spring(translateY, { toValue: 0, friction: 9 }), Animated.spring(scaleX, { toValue: 1, friction: 9 }), Animated.spring(scaleY, { toValue: 1, friction: 9 }), ]; animatesOnly ? animatesOnly(animates) : Animated.parallel(animates).start(); } else { if (animatesOnly) { let animates = [ Animated.timing(translateX, { toValue: 0, duration: 1 }), Animated.timing(translateY, { toValue: 0, duration: 1 }), Animated.timing(scaleX, { toValue: 1, duration: 1 }), Animated.timing(scaleY, { toValue: 1, duration: 1 }), ]; animatesOnly(animates); } else { translateX.setValue(0); translateY.setValue(0); scaleX.setValue(1); scaleY.setValue(1); } } } render() { let { elements, toastElements, translateX, translateY, scaleX, scaleY } = this.state; let transform = [{ translateX }, { translateY }, { scaleX }, { scaleY }]; // 如果存在loading 只加载loading,loading结束后加载其他element let laodingItem = null; for (let i = elements.length - 1; i >= 0; --i) { if (elements[i].key === rrcRNLoadingKey) { laodingItem = elements[i].element; break; } } if (laodingItem) { return ( <View style={{ flex: 1 }}> <Animated.View style={{ flex: 1, transform: transform }}> {this.props.children} </Animated.View> <View style={styles.overlayContainer}> {laodingItem} </View> </View> ) } return ( <View style={{ flex: 1 }}> <Animated.View style={{ flex: 1, transform: transform }}> {this.props.children} </Animated.View> { elements.length > 0 || toastElements.length > 0 ? <View style={styles.overlayContainer} pointerEvents={'box-none'} > { // 如果最后一项是alert,应该查找并清除前几项中的actionSheet(如果有的话) // 目前alert和actionSheet是相容的,应该改为互斥的,即最后出现的可以打断之前出现的 elements.map((item, index) => { // 同一时刻只加载elements中最后一个element if (index == elements.length - 1) { return ( <View key={'RRCTopView' + item.key} style={styles.overlay} > {item.element} </View> ); } else { return null; } }) } { toastElements.map((item, index) => { // 同一时刻只加载elements中最后一个element if (index == toastElements.length - 1) { return ( <View key={'RRCTopView_Toast' + item.key} style={styles.overlay} pointerEvents={'box-none'} > {item.element} </View> ); } else { return null; } }) } </View> : null } </View> ); } } var styles = StyleSheet.create({ overlayContainer: { backgroundColor: 'rgba(0, 0, 0, 0)', position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center' }, overlay: { position: 'absolute', } }); if (!AppRegistry.registerComponentOld) { AppRegistry.registerComponentOld = AppRegistry.registerComponent; } AppRegistry.registerComponent = function (appKey, componentProvider) { class RootElement extends Component { render() { let Component = componentProvider(); return ( <RRCTopView> <Component {...this.props} /> </RRCTopView> ); } } return AppRegistry.registerComponentOld(appKey, () => RootElement); } import './App.css'; import { render } from 'react-dom'; import React from 'react'; import SearchBar from "../SearchBar/searchbar" import SearchResults from "../SearchResults/searchresults" import Playlist from "../Playlist/playlist" import Spotify from "../../util/Spotify"; import Navigation from "../Navigation/navigation" class App extends React.Component { constructor(props){ super(props); this.state = { searchResults: [], playlistName: "Playlist Name", playlistTracks: [] }; this.addTrack = this.addTrack.bind(this); this.removeTrack = this.removeTrack.bind(this); this.updatePlaylistName = this.updatePlaylistName.bind(this); this.savePlaylist = this.savePlaylist.bind(this); this.search = this.search.bind(this) } addTrack(track) { const keyArray = []; const savedPlaylistTracks = this.state.playlistTracks; for (let i = 0; i < this.state.playlistTracks.length; i++) { keyArray.push(this.state.playlistTracks[i].id) } if ((keyArray.includes(track.id))===false) { savedPlaylistTracks.push(track) } this.setState({playlistTracks: savedPlaylistTracks}) } removeTrack(track) { let tracks = this.state.playlistTracks; tracks = tracks.filter(currentTrack => currentTrack.id !== track.id) this.setState({playlistTracks: tracks}) } updatePlaylistName(name) { this.setState({playlistName: name}) } savePlaylist(){ const uriArray = this.state.playlistTracks.map(track => track.uri) Spotify.savePlaylist(this.state.playlistName,uriArray).then(() => { this.setState ({ playlistName: "New Playlist", playlistTracks: [] }) }) } search(term) { Spotify.search(term).then(searchResults => { this.setState({searchResults: searchResults}) }) } render() { return ( <div> <Navigation /> <div className="App"> <SearchBar onSearch={this.search} /> <div className="App-playlist" > <SearchResults searchResults={this.state.searchResults} onAdd = {this.addTrack} /> <Playlist playlistName={this.state.playlistName} playlistTracks={this.state.playlistTracks} onRemove={this.removeTrack} onNameChange={this.updatePlaylistName} onSave={this.savePlaylist} /> </div> </div> </div> ) } } export default App; import React from "react"; import styled from "styled-components"; import Button from "../components/Button"; const SaltListComp = styled.div` width: 250px; background-color: white; border-radius: 5px; margin-bottom: 30px; `; const Title = styled.h2` width: 100%; font-size: 16px; text-transform: uppercase; padding: 16px 20px; border-bottom: 1px solid #ccc; font-weight: 500; margin: 0; `; const List = styled.ul` width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; list-style: none; padding: 0; margin: 0; `; const ListItem = styled.li` width: 100%; font-size: 14px; list-style: none; border-bottom: 1px solid #ccc; padding: 10px 20px; `; const SaltList = () => { return ( <SaltListComp> <Title>Saltiest Salts Yo Mama Cats Faces ); }; export default SaltList; examples/index.js /* eslint-disable no-console */ // modules const bf = require('../main'); // configure options const options = { cwd: '.', glob: '**/example*.(js|md)', ignore: '**/node_modules', start: /\/\*{2,}/, stop: /\*\//, }; // promise bf(options).then(console.log).catch(console.error); // callback // bf(options, (err, results) => (!!err) ? console.error(err) : console.log(results)); // sync // try { // console.log(bf({ ...options, mode: 'sync' })); // } catch (err) { // console.error(err); // } import { argdown } from "@argdown/node"; argdown.defaultProcesses["wiki-plugin"] = [ "parse-input", "build-model", "build-map", "highlight-source", "colorize", "export-dot", "export-svg", "export-web-component" ]; const extensionsFolderUrl = process.argv[3]; const request = { input: process.argv[2], process: "wiki-plugin", webComponent: { webComponentScriptUrl: extensionsFolderUrl + "/Argdown/resources/argdown-map.js", webComponentPolyfillUrl: extensionsFolderUrl + "/Argdown/resources/webcomponents-loader.js", globalStylesUrl: extensionsFolderUrl + "/Argdown/resources/argdown-map.css" } }; const response = argdown.run(request); var webComponent = response.webComponent; // Clean the webComponent webComponent = webComponent.replace(//g, "") // remove comments var pieces = webComponent.split(" tag webComponent = pieces.join(" { const files = await require.context('~/site/blog', false, /\.json$/); return files .keys() .map((key) => files(key)) .sort((a, b) => new Date(b.date) - new Date(a.date)); }; const getPost = async (slug) => { const posts = await getPosts(); return posts.find((post) => post.slug === slug); }; const getProjects = async () => { const files = await require.context('~/site/projects', false, /\.json$/); return files .keys() .map((key) => files(key)) .sort((a, b) => new Date(b.date) - new Date(a.date)); }; export { getProjects, getPosts, getPost }; /* * Copyright (c) 2017. * author: daxingplay <> */ const _ = require('lodash'); /** * Configuration. */ const config = { clients: [], confidentialClients: [], tokens: [], users: [], authorizationCodes: [], }; /** * Dump the memory storage content (for debug). */ const dump = function() { console.log('clients', config.clients); console.log('confidentialClients', config.confidentialClients); console.log('tokens', config.tokens); console.log('users', config.users); }; /* * Methods used by all grant types. */ const getAccessToken = function(bearerToken) { const tokens = config.tokens.filter(function(token) { return token.accessToken === bearerToken; }); return tokens[0]; }; const getClient = function(clientId, clientSecret) { const clients = config.clients.filter(function(client) { let checkSecret = true; if (clientSecret !== null) { checkSecret = client.clientSecret === clientSecret; } return client.clientId === clientId && checkSecret; }); const confidentialClients = config.confidentialClients.filter(function(client) { return client.clientId === clientId && client.clientSecret === clientSecret; }); const ret = clients[0] || confidentialClients[0]; if (ret) { return _.assign({ id: ret.clientId }, ret); } return false; }; const saveToken = function(token, client, user) { const ret = { accessToken: token.accessToken, accessTokenExpiresAt: token.accessTokenExpiresAt, refreshToken: token.refreshToken, refreshTokenExpiresAt: token.refreshTokenExpiresAt, scope: token.scope, client: { id: client.id }, user: { id: user.id }, }; config.tokens.push(ret); return ret; }; /* * Method used only by password grant type. */ const getUser = function(username, password) { const users = config.users.filter(function(user) { return user.username === username && user.password === password; }); return users[0]; }; /* * Method used only by client_credentials grant type. */ const getUserFromClient = function(client) { // FIXME const clients = config.confidentialClients.filter(function(c) { return c.clientId === client.id; }); let user; if (clients.length) { user = { username: client.id, }; } return user; }; const saveAuthorizationCode = function (code, client, user) { const ret = _.assign({ client: { id: client.clientId }, user: { id: user.id }, }, code); config.authorizationCodes.push(ret); return ret; }; const getAuthorizationCode = function (authorizationCode) { return config.authorizationCodes.filter(o => o.authorizationCode === authorizationCode)[0]; }; const revokeAuthorizationCode = function (code) { const exist = getAuthorizationCode(code.authorizationCode); if (exist) { config.authorizationCodes = config.authorizationCodes.filter(o => o.authorizationCode !== code.authorizationCode); return true; } return false; }; /** * Export model definition object. */ exports.generateModel = (options) => { if (Array.isArray(options.clients)) { config.clients = options.clients.map(o => _.assign({}, o, { grants: ['authorization_code'], })); } if (Array.isArray(options.users)) { config.users = options.users; } return { getAccessToken, getClient, saveToken, getUser, getUserFromClient, saveAuthorizationCode, getAuthorizationCode, revokeAuthorizationCode, }; };1-10 /** * Can we use __proto__? * * @type {Boolean} */ exports.hasProto = '__proto__' in {} /** * Indicates we have a window * * @type {Boolean} */ var toString = Object.prototype.toString var inBrowser = exports.inBrowser = typeof window !== 'undefined' && toString.call(window) !== '[object Object]' /** * Defer a task to the start of the next event loop * * @param {Function} cb * @param {Object} ctx */ var defer = inBrowser ? (window.requestAnimationFrame || window.webkitRequestAnimationFrame || setTimeout) : setTimeout exports.nextTick = function (cb, ctx) { if (ctx) { defer(function () { cb.call(ctx) }, 0) } else { defer(cb, 0) } } /** * Detect if we are in IE9... * * @type {Boolean} */ exports.isIE9 = inBrowser && navigator.userAgent.indexOf('MSIE 9.0') > 0 /** * Sniff transition/animation events */ if (inBrowser && !exports.isIE9) { var isWebkitTrans = window.ontransitionend === undefined && window.onwebkittransitionend !== undefined var isWebkitAnim = window.onanimationend === undefined && window.onwebkitanimationend !== undefined exports.transitionProp = isWebkitTrans ? 'WebkitTransition' : 'transition' exports.transitionEndEvent = isWebkitTrans ? 'webkitTransitionEnd' : 'transitionend' exports.animationProp = isWebkitAnim ? 'WebkitAnimation' : 'animation' exports.animationEndEvent = isWebkitAnim ? 'webkitAnimationEnd' : 'animationend' }import merge from 'lodash/merge'; import parse from 'url-parse'; /** * Adds web environment information to the context. * * @function webContext * @memberof module:analytics * @returns {object} Context object for web applications. */ export default function () { return { web: { window: { location: parse(window.location.href, true), navigator: merge({}, window.navigator), screen: merge({}, window.screen), }, document: { title: document.title, referrer: document.referrer, }, }, }; } /* GPII Windows Personalization Framework Gruntfile Copyright 2013-2014 OCAD University Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ "use strict"; module.exports = function (grunt) { grunt.initConfig({ lintAll: { sources: { md: [ "./*.md","./gpii/*.md", "./settingsHelper/**/*.md"], js: ["./gpii/**/*.js", "./tests/**/*.js", "./*.js", "./service/src/**/*.js", "./service/tests/**/*.js"], json: ["./gpii/**/*.json", "./tests/**/*.json", "./settingsHelper/**/*.json", "./*.json"], json5: ["./gpii/**/*.json5", "./tests/**/*.json5", "./*.json5"], other: ["./.*"] } } }); grunt.loadNpmTasks("gpii-grunt-lint-all"); grunt.registerTask("lint", "Perform all standard lint checks.", ["lint-all"]); }; 1-10 // jshint esversion: 6 updateFromCookie(); function save(){ document.cookie = "firstnme="+document.getElementById("fninput").value; document.cookie = "lastname="+document.getElementById("lninput").value; updateFromCookie(); } function updateFromCookie(){ document.getElementById("cookiedata").innerHTML = decodeURIComponent(document.cookie); } koni/gatsby-starter-netlify-cms import React from 'react' import Layout from '../components/Layout'; import { Link, graphql, StaticQuery } from 'gatsby' export default () => (

    test

    { console.log(data); return ( <> {data.allMarkdownRemark.edges.map(edge => ( {edge.node.frontmatter.title} ))} ); }} />

    Footer

    ); "use strict"; const account = require("./account-router"); const auth = require("./auth-router"); const events = require("./event-router"); const user = require("./user-router"); const rankings = require("./ranking-router"); module.exports = { account, auth, events, user, rankings }; 'use strict'; var parseString = function(string) { if (typeof string !== 'string') { return null; } return string.split(";"); }; var parseArray = function(array) { if (typeof array !== 'object' || Object.prototype.toString.call(array) !== '[object Array]') { return null; } var stringImploded = ''; var length = array.length; for (var i = 0; i < length; i++) { if (typeof array[i] !== 'string' || array[i].indexOf(";") > -1) { throw "Error : " + typeof array[i] + array[i].indexOf(";"); } stringImploded += i > 0 ? ';' : ''; stringImploded += array[i]; } return stringImploded; }; var addCarat = function(string) { var regex = /(%)([^\\;]+)(%)/g; return string.replace(regex, "$1$2^$3"); }; exports.parseString = parseString; exports.parseArray = parseArray; exports.addCarat = addCarat; const mongoose = require('mongoose'); const MessageSchema = mongoose.Schema({ owner: { //[username,userid] type: Array, required: true }, parentEvent: { type: String, required: true }, parentMessage: { type: String, required: false }, body: { type: String, required: true }, likes: { //[idUsers,idUsers,...] type: Array, required: false }, createdAt:{ type: Date, required: true }, updatedAt:{ type: Date, required: false }, delete: { type: Boolean, required: true } }); const messageModel = mongoose.model('Message', MessageSchema); module.exports = messageModel;1-10 /* * This file is part of the nivo project. * * Copyright 2016-present, . * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import random from 'lodash/random' export const generateNetworkData = ({ rootNodeRadius = 12, minMidNodes = 6, maxMidNodes = 16, midNodeRadius = 8, minLeaves = 4, maxLeaves = 16, leafRadius = 4, } = {}) => { const rootNode = { id: '0', radius: rootNodeRadius, depth: 0, color: 'rgb(244, 117, 96)', } let nodes = Array.from({ length: random(minMidNodes, maxMidNodes) }, (v, k) => ({ id: `${k + 1}`, radius: midNodeRadius, depth: 1, color: 'rgb(97, 205, 187)', })) const links = [] const extraNodes = [] nodes.forEach(source => { links.push({ source: '0', target: source.id, distance: 50, }) nodes.forEach(target => { if (Math.random() < 0.04) { links.push({ source: source.id, target: target.id, distance: 70, }) } }) Array.from({ length: random(minLeaves, maxLeaves) }, (v, k) => { extraNodes.push({ id: `${source.id}.${k}`, radius: leafRadius, depth: 2, color: 'rgb(232, 193, 160)', }) links.push({ source: source.id, target: `${source.id}.${k}`, distance: 30, }) }) }) nodes.push(rootNode) nodes = nodes.concat(extraNodes) return { nodes, links } } /*! ========================================================= * BLK Design System React - v1.2.0 ========================================================= * Product Page: https://www.creative-tim.com/product/blk-design-system-react * Copyright 2020 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/blk-design-system-react/blob/main/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import axios from "axios"; import React from "react"; import classnames from "classnames"; // javascript plugin used to create scrollbars on windows // reactstrap components import { Button, Card, CardHeader, CardBody, Label, FormGroup, Input, NavItem, NavLink, Nav, Table, TabContent, TabPane, Row, Col, } from "reactstrap"; export default function ProfileForm() { const [tabs, setTabs] = React.useState(1); const [firstName, setFirstName] = React.useState(""); const [lastName, setLastName] = React.useState(""); const [email, setEmail] = React.useState(""); const [streetNumber, setStreetNumber] = React.useState(""); const [streetName, setStreetName] = React.useState(""); const [city, setCity] = React.useState(""); const [region, setRegion] = React.useState(""); const [countryCode, setCountryCode] = React.useState(""); const [postalCode, setPostalCode] = React.useState(""); const [user, setUser] = React.useState([]); const [address, setAddress] = React.useState([]); React.useEffect(() => { const userURL = "http://ec2-3-23-92-210.us-east-2.compute.amazonaws.com:5000/users/3"; axios.get(userURL).then((response) => { setUser(response.data[0]); }); const addressURL = "http://ec2-3-23-92-210.us-east-2.compute.amazonaws.com:5000/addresses/5"; axios.get(addressURL).then((response) => { setAddress(response.data[0]); }); }, [firstName, lastName, email, streetNumber, streetName, city, region, countryCode, postalCode]); function editUserOrAddress() { const editedUser = {}; if (firstName) editedUser.firstName = firstName; if (lastName) editedUser.lastName = lastName; if (email) editedUser.email = email; const editedAddress = {}; if (streetNumber) editedAddress.streetNumber = streetNumber; if (streetName) editedAddress.streetName = streetName; if (city) editedAddress.city = city; if (region) editedAddress.region = region; if (countryCode) editedAddress.countryCode = countryCode; if (postalCode) editedAddress.postalCode = postalCode; if (editedUser) { axios.put("http://ec2-3-23-92-210.us-east-2.compute.amazonaws.com:5000/users/3", editedUser ).then((response) => { console.log(response.data); }); } if (editedAddress) { axios.put("http://ec2-3-23-92-210.us-east-2.compute.amazonaws.com:5000/addresses/5", editedAddress ).then((response) => { console.log(response.data); }); } } if (!user || !address) return "No user"; return (

    Profile Info

    ', { html: val })); }); $thead.append($row); } $table.append($thead); $table.append('
    Name {user.nameFirst}
    Address {user.nameLast}
    Email {user.email}
    Street Number {address.streetNo}
    Street Name {address.streetName1}
    City {address.city}
    Region {address.region}
    Country Code {address.countryCode}
    Postal Code {address.postalCode}
    setFirstName(e.target.value)} /> setLastName(e.target.value)} /> setEmail(e.target.value)} /> setStreetName(e.target.value)} /> setCity(e.target.value)} /> setRegion(e.target.value)} /> setCountryCode(e.target.value)} /> setPostalCode(e.target.value)} /> ); }import { ActionTypes } from './action-types'; export const loginReducer = (state, action) => { switch (action.type) { case ActionTypes.FIELD: { return { ...state, serverError: '', [action.field]: action.value, validationError: { ...state.validationError, [action.field]: '', }, }; } case ActionTypes.LOGIN: { return { ...state, isLoading: true, validationError: {}, }; } case ActionTypes.SUCCESS: { return { ...state, isLoading: false, username: action.data.username, }; } case ActionTypes.CLIENT_ERROR: { return { ...state, validationError: action.errors, }; } case ActionTypes.SERVER_ERROR: { return { ...state, isLoading: false, serverError: action.error, }; } default: break; } return state; }; ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // --------------------------------------------------------------------- // Action // --------------------------------------------------------------------- ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// /** * @constructor * @private */ ZICA.Action = function() { } /** * @private */ ZICA.Action.prototype.execute = function(node) { } /** * @private */ ZICA.Action.prototype.createClone = function() { return null; } /////////ActionHandler////////// /** * @constructor * @private * @class */ ZICA.ActionHandler = function(array) //,scene { if(!array)array = []; this.Actions = array; } /** * @private */ ZICA.ActionHandler.prototype.execute = function(node) { for (var i=0; i 0) { // move animated to target TO DO !!! var anim = new ZICA.AnimatorFlyStraight({}); anim.Start = new ZICA.Vect2d(nodeToHandle.x,nodeToHandle.y); anim.End = finalpos; anim.TimeForWay = this.TimeNeededForMovementMs; anim.DeleteMeAfterEndReached = true; anim.recalculateImidiateValues(); nodeToHandle.addAnimator(anim); } else { // set position directly nodeToHandle.x = finalpos.X; nodeToHandle.y = finalpos.Y; } } } } // --------------------------------------------------------------------- // Action ChangeSceneNodeProperty // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.ChangeSceneNodeProperty = function(obj) { this.Type = 'ChangeSceneNodeProperty'; this.SceneNodeToChange = obj.SceneNodeToChange; if(obj.SceneNodeToChange == null)this.ChangeCurrentSceneNode = true; this.Property = obj.Property; this.Value = obj.Value; } /** * @private */ ZICA.Action.ChangeSceneNodeProperty.prototype.createClone = function() { var a = new ZICA.Action.ChangeSceneNodeProperty({}); a.SceneNodeToChange = this.SceneNodeToChange; a.ChangeCurrentSceneNode = this.ChangeCurrentSceneNode; a.Property = this.Property; a.Value = this.Value; return a; } /** * @private */ ZICA.Action.ChangeSceneNodeProperty.prototype.execute = function(currentNode) { if (!currentNode) return; var nodeToHandle = null; if (this.ChangeCurrentSceneNode) nodeToHandle = currentNode; else if (this.SceneNodeToChange != -1) nodeToHandle = Game.getEntityById(this.SceneNodeToChange); if (nodeToHandle) { nodeToHandle[this.Property] = this.Value; } } // --------------------------------------------------------------------- // Action ChangeSceneNodePropertyFromNode // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.ChangeSceneNodePropertyFromNode = function(obj) { this.Type = 'ChangeSceneNodePropertyFromNode'; this.SceneNodeToChange = obj.SceneNodeToChange; if(obj.SceneNodeToChange == null)this.ChangeCurrentSceneNode = true; this.Property = obj.Property; this.SceneNodeFrom = obj.SceneNodeFrom; if(obj.SceneNodeFrom == null)this.FromCurrentSceneNode = true; } /** * @private */ ZICA.Action.ChangeSceneNodePropertyFromNode.prototype.createClone = function() { var a = new ZICA.Action.ChangeSceneNodePropertyFromNode({}); a.SceneNodeToChange = this.SceneNodeToChange; a.ChangeCurrentSceneNode = this.ChangeCurrentSceneNode; a.SceneNodeFrom = this.SceneNodeFrom; a.FromCurrentSceneNode = this.FromCurrentSceneNode; a.Property = this.Property; return a; } /** * @private */ ZICA.Action.ChangeSceneNodePropertyFromNode.prototype.execute = function(currentNode) { if (!currentNode) return; var nodeFrom = null; if (this.FromCurrentSceneNode) nodeFrom = currentNode; else if (this.SceneNodeFrom != -1) nodeFrom = Game.getEntityById(this.SceneNodeFrom); var nodeToHandle = null; if (this.ChangeCurrentSceneNode) nodeToHandle = currentNode; else if (this.SceneNodeToChange != -1) nodeToHandle = Game.getEntityById(this.SceneNodeToChange); if (nodeToHandle) { nodeToHandle[this.Property] = nodeFrom[this.Property]; } } // --------------------------------------------------------------------- // Action ChangeSceneNodePropertyVariable // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.ChangeSceneNodePropertyVariable = function(obj) { this.Type = 'ChangeSceneNodePropertyVariable'; this.SceneNodeToChange = obj.SceneNodeToChange; if(obj.SceneNodeToChange == null)this.ChangeCurrentSceneNode = true; this.Property = obj.Property; this.Variable = obj.Variable; } /** * @private */ ZICA.Action.ChangeSceneNodePropertyVariable.prototype.createClone = function() { var a = new ZICA.Action.ChangeSceneNodePropertyVariable({}); a.SceneNodeToChange = this.SceneNodeToChange; a.ChangeCurrentSceneNode = this.ChangeCurrentSceneNode; a.Property = this.Property; a.Variable = this.Variable; return a; } /** * @private */ ZICA.Action.ChangeSceneNodePropertyVariable.prototype.execute = function(currentNode) { if (!currentNode) return; var nodeToHandle = null; if (this.ChangeCurrentSceneNode) nodeToHandle = currentNode; else if (this.SceneNodeToChange != -1) nodeToHandle = Game.getEntityById(this.SceneNodeToChange); if (nodeToHandle) { if(Game.hasVariable(this.Variable)) nodeToHandle[this.Property] = Game.getVariable(this.Variable); } } // --------------------------------------------------------------------- // Action ActionRestartScene // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.SwitchToScene = function(obj) { this.Scene = obj.SceneId;//obj.Scene; this.ResetScene = obj.ResetScene; this.Type = 'SwitchToScene'; } /** * @private */ ZICA.Action.SwitchToScene.prototype.createClone = function() { var a = new ZICA.Action.SwitchToScene({}); a.Scene = this.Scene; a.ResetScene = this.ResetScene; return a; } /** * @private */ ZICA.Action.SwitchToScene.prototype.execute = function(currentNode) { //var scene = Game.getSceneByName(this.Scene); var scene = Game.getScene(this.Scene); if(scene) Game.switchToScene(scene,this.ResetScene); } // --------------------------------------------------------------------- // Action ActionRestartScene // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.RestartScene = function() { this.Type = 'RestartScene'; } /** * @private */ ZICA.Action.RestartScene.prototype.createClone = function() { var a = new ZICA.Action.RestartScene(); return a; } /** * @private */ ZICA.Action.RestartScene.prototype.execute = function(currentNode) { if (Game.scene) Game.switchToScene(Game.scene, true); } // --------------------------------------------------------------------- // Action OpenWebpage // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.OpenWebpage = function(obj) { this.Type = 'OpenWebpage'; this.Webpage = obj.Webpage; this.Target = obj.Target; } /** * @private */ ZICA.Action.OpenWebpage.prototype.createClone = function() { var a = new ZICA.Action.OpenWebpage({}); a.Webpage = this.Webpage; a.Target = this.Target; return a; } /** * @private */ ZICA.Action.OpenWebpage.prototype.execute = function(currentNode) { window.open(this.Webpage, this.Target); } // --------------------------------------------------------------------- // Action OpenWebpage // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.ExitApplication = function(obj) { this.Type = 'ExitApplication'; } /** * @private */ ZICA.Action.ExitApplication.prototype.createClone = function() { var a = new ZICA.Action.ExitApplication({}); return a; } /** * @private */ ZICA.Action.ExitApplication.prototype.execute = function(currentNode) { window.close(); } // --------------------------------------------------------------------- // Action SetOrChangeAVariable // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.SetOrChangeAVariable = function(obj) { // variables set in loader var oper = ['Set(=)','Add(+)','Substract(-)','Divide(/)','Divide INT(/)','Multiply(*)','Multiply INT(*)']; this.VariableName = obj.VariableName; this.Operation = oper.indexOf(obj.Operation); this.ValueType = obj.ValueType == 'Value'?0:1; this.Value = obj.Value; this.Type = 'SetOrChangeAVariable'; } /** * @private */ ZICA.Action.SetOrChangeAVariable.prototype.createClone = function() { var a = new ZICA.Action.SetOrChangeAVariable({}); a.VariableName = this.VariableName; a.Operation = this.Operation; a.ValueType = this.ValueType; a.Value = this.Value; return a; } /** * @private */ ZICA.Action.SetOrChangeAVariable.prototype.execute = function(currentNode) { if (!currentNode) return; if (this.VariableName == null) return; var var1 = Game.hasVariable(this.VariableName); if (var1 == true) var1 = Game.getVariable(this.VariableName); else var1 = 0; var var2 = null; if (this.ValueType == 1) //EO_VARIABLE) { var2 = Game.getVariable(this.Value); if (var2 == null) return; // operand variable not existing }else var2 = this.Value; switch(this.Operation) { case 0: //EO_SET: var1 = var2; break; case 1: //EO_ADD: var1 += var2; break; case 2: //EO_SUBSTRACT: var1 -= var2; break; case 3: //EO_DIVIDE: var1 /= var2; break; case 4: //EO_DIVIDE_INT: var1 = Math.round(var1 / var2); break; case 5: //EO_MULTIPLY: var1 *= var2; break; case 6: //EO_MULTIPLY_INT: var1 = Math.round(var1 * var2); break; } Game.setVariable(this.VariableName , var1); } // --------------------------------------------------------------------- // Action IfVariable // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.IfVariable = function(obj) { var comp = ['Is equal to (=)','Is not equal to (<>)','Is bigger than (>)','Is smaller than (<)']; this.VariableName = obj.VariableName; this.ComparisonType = comp.indexOf(obj.ComparisonType); this.ValueType = obj.ValueType == 'Value'?0:1; this.Value = obj.Value; this.TheActionHandler = obj.Action; this.TheElseActionHandler = obj.Else; this.Type = 'IfVariable'; } /** * @private */ ZICA.Action.IfVariable.prototype.createClone = function() { var a = new ZICA.Action.IfVariable({}); a.VariableName = this.VariableName; a.ComparisonType = this.ComparisonType; a.ValueType = this.ValueType; a.Value = this.Value; a.TheActionHandler = this.TheActionHandler ? this.TheActionHandler.createClone() : null; a.TheElseActionHandler = this.TheElseActionHandler ? this.TheElseActionHandler.createClone() : null; return a; } /** * @private */ ZICA.Action.IfVariable.prototype.execute = function(currentNode) { if (!currentNode) return; if (this.VariableName == null) return; var var1 = Game.hasVariable(this.VariableName); if (var1 == null) // should not happen since the function above creates if not found return; var1 = Game.getVariable(this.VariableName); var var2 = null; if (this.ValueType == 1) //EO_VARIABLE) { var2 = Game.hasVariable(this.Value); if (var2 == false) // should not happen since the function above creates if not found return; var2 = Game.getVariable(this.Value); }else var2 = this.Value; var execute = false; switch(this.ComparisonType) { case 0: //EO_EQUAL: case 1: //EO_NOT_EQUAL: { execute = (var1 == var2) if (this.ComparisonType == 1) //EO_NOT_EQUAL) execute = !execute; break; } case 2: //EO_BIGGER_THAN: { execute = var1 > var2; } break; case 3: //EO_SMALLER_THAN: { execute = var1 < var2; } break; } if (execute) { if (this.TheActionHandler) this.TheActionHandler.execute(currentNode); } else { if (this.TheElseActionHandler) this.TheElseActionHandler.execute(currentNode); } } // --------------------------------------------------------------------- // Action Store Load Variable // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.ActionStoreLoadVariable = function(obj) { this.Type = 'StoreLoadVariable'; this.Load = (obj.Load == 'Load Variable')?true:false; this.VariableName = obj.VariableName; } /** * @private */ ZICA.Action.ActionStoreLoadVariable.prototype.createClone = function() { var a = new ZICA.Action.ActionStoreLoadVariable({}); a.Load = this.Load; a.VariableName = this.VariableName; return a; } ZICA.Action.ActionStoreLoadVariable.prototype.setCookie = function(cookieName, value, expdays) { var expdate = new Date(); expdate.setDate(expdate.getDate() + expdays); var cvalue = escape(value) + ("; expires=" + expdate.toUTCString()); document.cookie = cookieName + "=" + cvalue; } ZICA.Action.ActionStoreLoadVariable.prototype.getCookie = function(cookieName) { var ARRcookies = document.cookie.split(";"); for (var i=0; i= this.WeaponRange) this.__removeFlag = true; } cloned.__onCollision = function(event){ var other = event.other; if((!other.isBullet) && (other != this.shooterNode) && (other != this.bulletTemplate)){ Game.scene.lastBulletImpact = new ZICA.Vect2d(this.x,this.y); this.__removeFlag = true; if (this.ActionHandlerOnImpact) this.ActionHandlerOnImpact.execute(other); var targetanimAi = other.getAnimatorOfType('gameai'); if (targetanimAi) targetanimAi.OnHit(this.Damage, other); } } } } } else if (this.ShootType == 0) //EST_DIRECT) { for(var i = 0; i<= this.WeaponRange; i++){ var end = ray.End.clone(); end.multiplyThisWithScal(i) var point = ray.Start.add(end); point.x = point.X; point.y = point.Y; for(var ii = 0; ii<= Game.scene.children.length-1;ii++){ var node = Game.scene.children[ii]; if(Game.pointInBox(point,node)){ if((!node.isBullet) && (node != shooterNode)){ Game.scene.lastBulletImpact = new ZICA.Vect2d(point.X,point.Y); if (this.ActionHandlerOnImpact) this.ActionHandlerOnImpact.execute(node); var targetanimAi = other.getAnimatorOfType('gameai'); if (targetanimAi) targetanimAi.OnHit(this.Damage, node); i = Infinity; break; } } } } } // end direct shot } // --------------------------------------------------------------------- // Action ChangeCameraPosition // --------------------------------------------------------------------- /** * @private * @constructor * @class */ ZICA.Action.ChangeCameraPosition = function(obj) { this.UseAnimatedMovement = obj.UseAnimatedMovement;//false; this.TimeNeededForMovementMs = obj.TimeNeededForMovementMs //false; this.center = obj.Center; //this.SceneNodeToChangePosition = obj.SceneNodeToChangePosition; this.Vector = obj.Position.clone(); this.SceneNodeRelativeTo = obj.SceneNodeRelativeTo; if(obj.SceneNodeRelativeTo == null)this.RelativeToCurrentSceneNode = true; this.Type = 'ChangeCameraPosition'; } /** * @private */ ZICA.Action.ChangeCameraPosition.prototype.createClone = function() { var a = new ZICA.Action.ChangeCameraPosition({}); a.SceneNodeRelativeTo = this.SceneNodeRelativeTo; a.RelativeToCurrentSceneNode = this.RelativeToCurrentSceneNode; a.Vector = this.Vector ? this.Vector.clone() : null; a.center = this.center; a.UseAnimatedMovement = this.UseAnimatedMovement; a.TimeNeededForMovementMs = this.TimeNeededForMovementMs; return a; } /** * @private */ ZICA.Action.ChangeCameraPosition.prototype.execute = function(currentNode) { if (!currentNode) return; var nodeToHandle = Game.scene; if (nodeToHandle) { var finalpos = null; var nodeRelativeTo = null; if (this.RelativeToCurrentSceneNode) nodeRelativeTo = currentNode; else if (this.SceneNodeRelativeTo != -1) nodeRelativeTo = Game.getEntityById(this.SceneNodeRelativeTo); if (nodeRelativeTo){ var x = nodeRelativeTo.x; var y = nodeRelativeTo.y; if(this.center){ x += nodeRelativeTo.width/2; y += nodeRelativeTo.height/2; } finalpos = new ZICA.Vect2d(x + this.Vector.X,y + this.Vector.Y); } if (finalpos != null) { if (this.UseAnimatedMovement && this.TimeNeededForMovementMs > 0) { var anim = new ZICA.AnimatorFlyStraight({}); anim.Start = new ZICA.Vect2d(nodeToHandle.x,nodeToHandle.y); anim.End = finalpos; anim.TimeForWay = this.TimeNeededForMovementMs; anim.DeleteMeAfterEndReached = true; anim.recalculateImidiateValues(); nodeToHandle.addAnimator(anim); } else { // set position directly nodeToHandle.x = finalpos.X; nodeToHandle.y = finalpos.Y; } } } } 'use strict' const { secretServices } = require('@mntd/services') module.exports = async function (fastify, options) { fastify.addSchema({ $id: 'publicSecret', type: 'object', properties: { username: { type: 'string' }, name: { type: 'string' }, category: { type: 'string' }, createdAt: { type: 'string' } } }) fastify.addSchema({ $id: 'secrets', type: 'array', items: { $ref: 'publicSecret#' } }) fastify.addSchema({ $id: 'result', type: 'object', properties: { count: { type: 'integer' }, data: { $ref: 'secrets#' } } }) fastify.get( '/secrets/:username', { preValidation: fastify.auth([fastify.validateJWT]), schema: { response: { 200: 'result#' } } }, async (req, reply) => { const { username } = req.params const secrets = await secretServices.listSecrets(username) return { count: secrets.count, data: secrets.rows } } ) fastify.addSchema({ $id: 'createSecret', type: 'object', properties: { username: { type: 'string' }, name: { type: 'string' }, category: { type: 'string' }, value: { type: 'string' } }, required: ['username', 'name', 'value', 'category'] }) fastify.post( '/secrets', { preValidation: fastify.auth([fastify.validateJWT]), schema: { body: 'createSecret#', response: { 201: 'publicSecret#' } } }, async (req, reply) => { const { username, name, value, category } = req.body reply.code(201) return secretServices.createSecret(username, name, value, category) } ) // fastify.addSchema({ // $id: 'deleteSecret', // type: 'object', // properties: { // username: { type: 'string' }, // name: { type: 'string' } // }, // required: ['username', 'name'] // }) fastify.delete( '/secrets/:username/:name', { preValidation: fastify.auth([fastify.validateJWT]) // schema: { // body: 'deleteSecret#' // } }, async (req, reply) => { const { username, name } = req.params let result = await secretServices.deleteSecret(username, name) reply.send({ result }) } ) fastify.addSchema({ $id: 'publicGetSecret', type: 'object', properties: { username: { type: 'string' }, name: { type: 'string' }, category: { type: 'string' }, value: { type: 'string' }, createdAt: { type: 'string' } } }) fastify.get( '/secrets/:username/:name', { preValidation: fastify.auth([fastify.validateJWT]), schema: { response: { 200: 'publicGetSecret#' } } }, async (req, reply) => { const { username, name } = req.params const secret = await secretServices.getSecret(username, name) return secret } ) fastify.addSchema({ $id: 'updateSecret', type: 'object', properties: { value: { type: 'string' } }, required: ['value'] }) fastify.put( '/secrets/:username/:name', { preValidation: fastify.auth([fastify.validateJWT]), schema: { body: 'updateSecret#' } }, async (req, reply) => { const { username, name } = req.params const { value } = req.body let result = await secretServices.updateSecret(username, name, value) reply.send({ result }) } ) } const typeDefs = `type User { # The user's numeric ID id: Int! # The user's username username: String # Whether or not the account has purchased games gamer: Boolean # The name associated with the user display_name: String # The URL for the user's profile pic. Great for thumbnails! cover_url: String # The user's profile page URL url: String # Whether the user utilizes the press system press_user: Boolean # Whether the user has uploaded projects developer: Boolean }` export { typeDefs } alucidwolf/FED-Interview-Q-and-A // create object to be used to compose other objects var distortion = { distortion: 1, intensity: 0 }; var volume = { volume: 1 } var cabinet = { cabinet: 'maple' } var lowCut = { lowCut: 1 } var inputLevel = { inputLevel: 1 } var GuitarAmp = function (options) { return Object.assign({}, distortion, volume, cabinet, options) } var BassAmp = function BassAmp(options) { return Object.assign({}, lowCut, volume, cabinet, options) } var ChannelStrip = function ChannelStrip(options) { return Object.assign({}, inputLevel, lowCut, volume, options) } var MarshallAmp = GuitarAmp({ logo: 'gold' }); var PeaveyAmp = GuitarAmp({ logo: 'black' }); console.log(MarshallAmp); console.log(PeaveyAmp); boilerplate/api/controllers/hello/index.js 'use strict'; var gn = require('gracenode'); module.exports = function (req, res) { var msg = req.params.message || ''; gn.mod.views.hello(res, { message: msg, today: Date.now() }); }; motifmarkets/exposition var holdingAccount = { account: "" }; const accountLookupID = "accountSelector"; const accountLookupSelector = "#" + accountLookupID; const spinnerElementSelector = "#loading-spinner"; const renderElementId = "holdings-table"; const searchAccountStatementTemplate = "holding-accountsearchstatement-template"; const searchAccountTemplate = "holding-searchaccount-template"; const retrieveHoldingsTemplate = "holding-selectstatement-template"; const renderTemplateId = "holding-entry-template"; const renderNoResultsTemplateId = "holding-noresults-template"; const retrieveSymbolsTemplate = "holding-selectsymbolsstatement-template" $(async function () { // Account lookup $(accountLookupSelector).selectpicker(); $(accountLookupSelector).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { holdingAccount.account = $(e.target).val(); console.log("Holding account changed: " + previousValue + ' -> ' + holdingAccount.account); SaveSelectedAccount() RefreshHoldings(); }); await LoadStaticData(); await LoadSelectedAccount(); }); async function LoadStaticData() { // generate IQ statement var filter = ""; var iqStatement = GenerateTemplate(searchAccountStatementTemplate, filter); var qrIQ = await IqQueryPromise(iqStatement); if (!qrIQ.successful) { console.error(qrIQ.reason); return; } var results = JSON.parse(qrIQ.data); var html = GenerateTemplate(searchAccountTemplate, results); document.getElementById(accountLookupID).innerHTML = html; $(accountLookupSelector).selectpicker('refresh'); // default if (results.Rows.length > 0) { holdingAccount.account = results.Rows[0].Account; } } async function SaveSelectedAccount() { var keyValue = { key: "CurrentHoldingAccount", value: JSON.stringify(holdingAccount) } var qr = await SaveSettingsPromise(keyValue); if (!qr.successful) { console.log("Failed to save settings: " + qr.reason); } } async function LoadSelectedAccount() { var key = { key: "CurrentHoldingAccount" } var qr = await RecallSettingsPromise(key); if (!qr.successful) { console.log("Failed to load settings: " + qr.reason); return; } if (qr.data) { holdingAccount = JSON.parse(qr.data); } $(accountLookupSelector).selectpicker('val', holdingAccount.account); } async function RefreshHoldings() { try { $(spinnerElementSelector).removeClass("d-none"); // generate IQ statement var iqStatement = GenerateTemplate(retrieveHoldingsTemplate, holdingAccount); var qrIQ = await IqQueryPromise(iqStatement); if (!qrIQ.successful) { Failed(qrIQ.reason); return; } var holdingsData = JSON.parse(qrIQ.data); // now lookup symbol name var symbolData = { Rows: [], Columns: [] }; if (holdingsData.Rows.length > 0) { var iqSymbolsStatement = GenerateTemplate(retrieveSymbolsTemplate, holdingsData); var qrIQ = await IqQueryPromise(iqSymbolsStatement); if (!qrIQ.successful) { Failed(qrIQ.reason); return; } symbolData = JSON.parse(qrIQ.data); } var sanitisedHoldingData = SanitiseHoldingData(holdingsData, symbolData); if (sanitisedHoldingData.Rows.length > 0) { var html = GenerateTemplate(renderTemplateId, sanitisedHoldingData); document.getElementById(renderElementId).innerHTML = html; } else { var html = GenerateTemplate(renderNoResultsTemplateId, {}); document.getElementById(renderElementId).innerHTML = html; } console.log('Refresh holding'); } catch (err) { console.error(err); } finally { $(spinnerElementSelector).addClass("d-none"); UpdateRefreshTimestamp(); } } function SanitiseHoldingData(holdings, symbols) { var symbolLookup = {}; symbols.Rows.forEach(function (element) { // build lookup symbolLookup[element.SymbolCode.toUpperCase()] = element.Name; }); holdings.Rows.forEach(function (element) { // adjust element.Name = symbolLookup[(element.Code + '.' + element.Exchange).toUpperCase()] }); // reorder //holdings.Rows.sort(function (a, b) { return a.SymbolCode.localeCompare(b.SymbolCode); }); return holdings; } function Failed(reason) { console.warn(reason); } 'use strict'; var config = require('config'); var $ = require('jquery'); var EventEmitter = require('events').EventEmitter; var klass = require('klass'); var path = require('path'); var Hogan = require('hogan'); var Dao = require('../util/dao.js'); var UrlBuilder = require('../util/url-builder.js'); var Promise = require('bluebird'); module.exports = klass(EventEmitter).extend({ currentFile: null, page: null, lastPage: null, $currentElement: null, initialize: function (selector) { this.currentFile = null; this.$root = $(selector); this.$preload = this.$root.find('.preload'); this.$currentFileList = this.$root.find('.current-file-list'); this.$currentFileTitle = this.$root.find('.current-file-title') this.initializeTemplates(); this.bindEvents(); }, bindEvents: function () { var self = this; this.$root.on('click', 'a', function (e) { self.emit('click'); }); this.$preload.on('click', function (e) { e.preventDefault(); self.preloadThumbs(); }); }, setCurrentFile: function (filename) { this.currentFile = filename; this.$currentFileTitle.text(path.basename(filename)); }, loadPage: function (filename, page) { var self = this; if (this.currentFile != filename) { this.displayLoading(); Dao.getComicPages(filename, function (err, path, pages) { if (err) return self.displayError(err); self.setCurrentFile(filename); self.updatePages(path, pages); self.selectPage(page); self.emit('update', self.lastPage, page); }); } else { this.selectPage(page); this.emit('update', this.lastPage, page); } }, displayLoading: function () { this.$currentFileTitle.html(this.pageLoadingTemplate.render()); this.$currentFileList.empty(); }, displayError: function (err) { // TODO this.$currentFileTitle.html(err.message); }, updatePages: function (path, pages) { var self = this; this.lastPage = pages.length; this.$currentFileList.empty(); this.$currentFileList.scrollTop(0); pages.forEach(function (page, index) { var data = $.extend({}, page, {index: index + 1, path: path}); data.fileOffset = ''+data.fileOffset; data.thumbs_enabled = config.enable_thumbs; self.$currentFileList.append(self.pageRowTemplate.render(data)); }); }, selectPage: function (page) { if (this.$currentElement) { this.$currentElement.removeClass('active'); } this.page = +page; var $pageElement = this.$currentFileList.find('li').eq(page - 1); $pageElement.addClass('active'); var filename = $pageElement.attr('data-filename'); this.$currentElement = $pageElement; if (config.enable_thumbs) { this.loadThumb($pageElement).catch(function (err) { // TOOO: Handle thumbnail errors }); } this.emit('page', {path: this.currentFile, filename: filename}); }, preloadThumbs: function () { var self = this; var currentFile = this.currentFile; var promise = Promise.resolve(); this.$currentFileList.find('li').each(function (index, element) { var $element = $(element); promise = promise.then(function () { if (self.currentFile == currentFile) { return self.loadThumb($element); } }); }); promise.catch(function (err) { // TOOO: Handle thumbnail errors }); return promise; }, loadThumb: function ($pageElement) { var self = this; var $thumb = $pageElement.find('.page-thumb'); var thumb = $thumb.find('img')[0]; return new Promise(function (resolve, reject) { if ($thumb.hasClass('no-src')) { var filename = $pageElement.attr('data-filename'); thumb.src = UrlBuilder.getImageFilenameUrl(self.currentFile, filename); thumb.addEventListener('load', function (e) { $thumb.removeClass('no-src'); resolve(); }); thumb.addEventListener('error', function (e) { reject(new Error('Thumbnail image `' + thumb.src + '` could not be loaded')); }); } else { resolve(); } }); }, nextPage: function () { if (this.currentFile && this.page <= this.lastPage - 1) { window.location.hash = '#!' + this.currentFile + '::' + (this.page + 1); } }, previousPage: function () { if (this.currentFile && this.page > 1) { window.location.hash = '#!' + this.currentFile + '::' + (this.page - 1); } }, initializeTemplates: function () { this.pageRowTemplate = Hogan.compile($('#cz-template-page-row').html()); this.pageLoadingTemplate = Hogan.compile($('#cz-template-page-loading').html()); } }); Port-Activity/web0 import React from 'react'; import styled from 'styled-components'; import Icon from './Icon'; import Label from './Label'; import Input from './Input'; const SearchWrapper = styled.div` position: relative; margin-bottom: ${({ theme }) => theme.sizing.gap}; `; const StyledSearch = styled(Input)` padding-left: ${({ theme }) => theme.sizing.gap_huge}; `; const StyledSubmit = styled.button` position: absolute; left: ${({ theme }) => theme.sizing.gap_small}; top: 8px; background: none; border: none; padding: 0; cursor: pointer; outline: none; i { width: 24px; height: 24px; svg { fill: ${({ theme }) => theme.color.grey}; } } `; const Search = ({ label, ...props }) => ( {label && } ); export default Search; trantronghienit/LSFJavaHelper var searchData= [ ['previousowner',['previousOwner',['../classajn_1_1_simple_bus_listener_1_1_bus_event.html#a071d5fa4e3d860a489bd3393a527a3e0',1,'ajn::SimpleBusListener::BusEvent']]], ['prop_5faccess_5fread',['PROP_ACCESS_READ',['../namespaceajn.html#a6e8b75741c331238cb512d806fbe2957',1,'ajn']]], ['prop_5faccess_5frw',['PROP_ACCESS_RW',['../namespaceajn.html#a35e1f930e4008965043719c3bbc90792',1,'ajn']]], ['prop_5faccess_5fwrite',['PROP_ACCESS_WRITE',['../namespaceajn.html#a09445b7c25140ec3a964ecda4b81f575',1,'ajn']]] ]; 1-10 +(function (window, undefined) { window.GFImageSelect = GFImageSelect; function GFImageSelect (props) { var props = props || {}; var key = props.key; if (!key) { throw new Error('GFImageSelect: No key'); } var postId = props.postId; postId = isNaN(postId) ? 0 : Math.abs(postId); var jQuery = props.jQuery || window.jQuery; if (!jQuery) { throw new Error('GFImageSelect: No jQuery'); } jQuery(document).ready(function () { attach({ key: key, postId: postId, jQuery: jQuery }); }); } function attach (props) { var key = props.key; var postId = props.postId; var jQuery = props.jQuery; var frame; GFImageSelect._storeMediaPostId(); jQuery('#gf_image_select_button_' + key).on('click', function (event) { event.preventDefault(); var $el = jQuery(this); if (frame) { frame.uploader.uploader.param('post_id', postId); frame.open(); return; } GFImageSelect._setMediaPostId(postId); frame = wp.media({ title: $el.data('choose'), library: { type: 'image' }, button: { text: $el.data('update'), close: true }, multiple: false }); wp.media.frames.imageSelect = frame; frame.on('select', function () { var attachment = frame.state().get('selection').first(); onSelect({ attachment: attachment, key: key, jQuery: jQuery }); }); frame.on('close', function () { GFImageSelect._restoreMediaPostId(); }) frame.open(); }); var data = getData(key, jQuery); if (data && data.attachmentId && data.attachmentSrc) { initCropper({ key: key, jQuery: jQuery, // width: data.width, // height: data.height, crop: data.crop }); } }; function getData (key, jQuery) { var prefix = '#gf_image_select_' + key; var attachmentId = jQuery(prefix + '_1').val() || void 0; if (attachmentId) { attachmentId = isNaN(attachmentId) ? 0 : parseInt(attachmentId, 10) } var attachmentSrc = jQuery(prefix + '_2').val() || void 0; var width = jQuery(prefix + '_3').val() || void 0; if (width) { width = isNaN(width) ? void 0 : parseInt(width, 10) } var height = jQuery(prefix + '_4').val() || void 0; if (height) { height = isNaN(height) ? void 0 : parseInt(height, 10) } var crop = jQuery(prefix + '_5').val() || void 0; if (crop) { var arr = JSON.parse(crop); crop = { x: parseFloat(arr[0]), y: parseFloat(arr[1]), width: parseFloat(arr[2]), height: parseFloat(arr[3]), } } return { attachmentId: attachmentId, attachmentSrc: attachmentSrc, width: width, height: height, crop: crop } } function updateData (data, key, jQuery) { var prefix = '#gf_image_select_' + key; var map = { attachmentId: prefix + '_1', attachmentSrc: prefix + '_2', width: prefix + '_3', height: prefix + '_4', crop: prefix + '_5' } for (var i in data) { if (map[i]) { jQuery(map[i]).val(data[i]); } } } function onSelect (props) { var attachment = props.attachment.toJSON(); var large = attachment.sizes && attachment.sizes.large || attachment; var key = props.key; var jQuery = props.jQuery; updateData({ attachmentId: attachment.id, attachmentSrc: large.url, // width: large.width, // height: large.height }, key, jQuery) jQuery('#gf_image_select_container_' + key).addClass('gf_image_select_has_src'); jQuery('#gf_image_select_crop_' + key).attr('src', large.url); initCropper({ key: key, jQuery: jQuery, // width: large.width, // height: large.height }); } function initCropper (props) { var key = props.key; var jQuery = props.jQuery; var crop = props.crop; var el = jQuery('#gf_image_select_crop_' + key).get(0); var cropper = new Cropper(el, { viewMode: 1, aspectRatio: NaN, // aspectRatio: 16 / 9, // guides: false, // background: false, // autoCrop: false, // autoCropArea: 0.8, movable: false, rotatable: false, scalable: false, zoomable: false, minCropBoxWidth: 50, minCropBoxHeight: 50, ready: function () { var imageData = cropper.getImageData(); width = imageData.naturalWidth; height = imageData.naturalHeight; updateData({ width: width, height: height }, key, jQuery) if (crop) { cropper.setData(crop); } else { updateValue(); } }, cropend: throttle(updateValue) }); jQuery('#gf_image_select_button_crop_' + key).off('click').on('click', function (event) { jQuery('#gf_image_select_container_' + key).addClass('gf_image_select_has_crop'); if (document.createElement('canvas').getContext) { var canvas = cropper.getCroppedCanvas(); if (canvas) { jQuery('#gf_image_select_preview_' + key).html(canvas); } } updateValue(); }); jQuery('#gf_image_select_button_back_' + key).off('click').on('click', function (event) { jQuery('#gf_image_select_container_' + key).removeClass('gf_image_select_has_crop'); jQuery('#gf_image_select_preview_' + key).empty(); }); function updateValue () { var data = cropper.getData(); var crop = JSON.stringify([data.x, data.y, data.width, data.height]); updateData({ crop: crop }, key, jQuery) } } // ucs-2 string to base64 encoded ascii function utoa(str) { return window.btoa(encodeURIComponent(str)); } // base64 encoded ascii to ucs-2 string function atou(str) { return decodeURIComponent(window.atob(str)); } function throttle(fn, threshhold, scope) { threshhold || (threshhold = 250); var last; var deferTimer; return function () { var context = scope || this; var now = +new Date, args = arguments; if (last && now < last + threshhold) { clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fn.apply(context, args); }, threshhold); } else { last = now; fn.apply(context, args); } }; } GFImageSelect.prototype.constructor = GFImageSelect; GFImageSelect._restoreMediaPostId = function () { wp.media.model.settings.post.id = GFImageSelect.__media_post_id; }; GFImageSelect._storeMediaPostId = function () { if (GFImageSelect.__media_post_id === undefined) { GFImageSelect.__media_post_id = wp.media.model.settings.post.id || 0; } }; GFImageSelect._setMediaPostId = function (postId) { GFImageSelect._storeMediaPostId(); wp.media.model.settings.post.id = postId; }; })(window); cpt-chewieeee/z-ui-kit export Hexagon from '../HexagonList' export Maze from '../Maze' export IconButton from '../buttons/IconButton' export Header from '../headers/Header' export FancyInput from '../inputs/FancyInput' export TextButton from '../buttons/TextButton''use strict' const test = require('japa') const path = require('path') const ace = require('@adonisjs/ace') const { ioc, registrar, resolver } = require('@adonisjs/fold') const { Helpers, Config } = require('@adonisjs/sink') const fs = require('fs') test.group('Commands', group => { group.before(async () => { resolver.appNamespace('App') ioc.autoload(path.join(__dirname, './app'), 'App') registrar .providers([ '@adonisjs/framework/providers/AppProvider', '@adonisjs/redis/providers/RedisProvider', path.join(__dirname, '../../providers/KueProvider'), path.join(__dirname, '../../providers/CommandsProvider') ]) .register() ioc.bind('Adonis/Src/Helpers', () => { return new Helpers(__dirname) }) ioc.alias('Adonis/Src/Helpers', 'Helpers') ioc.bind('Adonis/Src/Config', () => { const config = new Config() config.set('kue', { connection: 'kue' }) config.set('redis', { connection: 'local', local: { host: '127.0.0.1', port: 6379, db: 0, keyPrefix: '' }, kue: { host: '127.0.0.1', port: 6379, db: 0, keyPrefix: 'q' } }) config.set('app', { logger: { transport: 'console', console: { driver: 'console' } } }) return config }) ioc.alias('Adonis/Src/Config', 'Config') await registrar.boot() }) group.beforeEach(() => { ioc.restore() }) test('kue:listen', async assert => { const Kue = use('Adonis/Addons/Kue') const Job = ioc.use('App/GoodJob') await ace.call('kue:listen') const data = { test: 'data' } const job = Kue.dispatch(Job.key, data) const result = await job.result assert.equal(result, 'test result') assert.equal(job.type, Job.key) assert.equal(job.data, data) }) test('Create a job', async assert => { await ace.call('make:job', { name: 'Test' }) assert.isTrue( fs.existsSync(path.join(__dirname, '../../app/Jobs/Test.js')) ) }) test('Create a job with the same name', async assert => { await ace.call('make:job', { name: 'Test' }) const filePath = path.join(__dirname, '../../app/Jobs/Test.js') assert.isTrue(fs.existsSync(filePath)) fs.unlinkSync(filePath) }) }) routes/routes.js const express = require("express"); const { Mensajes } = require("../models"); const validateForm = require("../services/validateForm"); const router = express.Router(); router.get("/", (req, res) => { res.render("index"); }); router.post("/form", async (req, res) => { try { const validate = validateForm(req.body); if (validate.length > 0) { res.status(400).json({ status: "error", data: validate }); } else { const data = await Mensajes.create(req.body); res.status(201).json({ status: "ok", data: data.dataValues }); } } catch (error) { throw error; } }); module.exports = router; /// Group attribute. A group is as far as the smallest distance of /// any two members is far. Groups with 1 or 0 objects are not far. FarAttribute = function(group) { this.perceive(group); } FarAttribute.prototype.key = "far"; FarAttribute.prototype.targetType = 'group'; FarAttribute.prototype.arity = 1; FarAttribute.prototype.constant = false; FarAttribute.prototype.perceive = function(group) { this.group = group; if (group.objs.length < 2) this.val = NaN; else { this.val = Infinity; for (var i=1; i dist) this.val = dist; } } } FarAttribute.prototype.get_activity = function() { return isNaN(this.val) ? 0 : FarRelationship.membership(this.val); } FarAttribute.prototype.get_label = function() { return 'far'; } 'use strict'; const Node = require('./node') class BinaryTree { constructor(root = null) { this.root = root; } fizzBuzzTree(tree) { console.log(tree); const result =[]; let FBT = (node) => { if(tree){ if (node.left) { FBT(node.left); } if (node.value % 15 === 0) { node.value = 'FizzBuzz'; result.push('FizzBuzz') } else if (node.value % 5 === 0) { node.value = 'Buzz'; result.push('Buzz') } else if (node.value % 3 === 0) { node.value = 'Fizz'; result.push('Fizz') } else{ result.push(node.value) } if (node.right) { FBT(node.right); } }; } FBT(tree); if(result) return result ; }; } let one = new Node(2); let two = new Node(7); let three = new Node(5); let four = new Node(2); let five = new Node(6); let six = new Node(9); let seven = new Node(5); let eight = new Node(15); let nine = new Node(4); one.left = two; one.right = three; two.left = four; two.right = five five.left = seven; five.right = eight; three.right = six; six.left = nine; let tree = new BinaryTree(); const check = tree.fizzBuzzTree(one) console.log(check); module.exports = {BinaryTree};wab/2.14/widgets/ThreatAnalysis/setting/nls/sl/strings.js1-10 define({ "transparencyLabel": "Prosojnost", "outline": "Obroba", "fill": "Polnilo (barva se uporablja le, če je slog nastavljen na enobarvno polnilo)", "style": "Slog", "mandatoryLabel": "Obvezna razdalja za evakuacijo", "mandatoryButtonLabel": "Konfiguriraj nastavitve za obvezno razdaljo za evakuacijo", "safeLabel": "Varna razdalja za evakuacijo", "safeButtonLabel": "Konfiguriraj nastavitve za varno razdaljo za evakuacijo", "selectOpLayerLabel": "Izberi operativni sloj za rezultate", "selectDefaultMeasurementLabel": "Izberi privzeto mersko enoto", "helpIconTooltip": "Seznam operativnega sloja je poseljen s sloji iz trenutne spletne karte, ki so poligonske geometrijske vrste.", "lineStyles": { "esriSLSDash": "Črtica", "esriSLSDashDot": "Črtica pika", "esriSLSDashDotDot": "Črtica pika pika", "esriSLSDot": "Pika", "esriSLSLongDash": "Dolga črtica", "esriSLSLongDashDot": "Dolga črtica pika", "esriSLSNull": "Brez vrednosti", "esriSLSShortDash": "Kratka črtica", "esriSLSShortDashDot": "Kratka črtica pika", "esriSLSShortDashDotDot": "Kratka črtica pika pika", "esriSLSShortDot": "Kratka pika", "esriSLSSolid": "Enobarvno" }, "fillStyles": { "esriSFSBackwardDiagonal": "Nazaj", "esriSFSCross": "Križ", "esriSFSDiagonalCross": "Diagonalno", "esriSFSForwardDiagonal": "Naprej", "esriSFSHorizontal": "Horizontalno", "esriSFSNull": "Brez vrednosti", "esriSFSSolid": "Enobarvno", "esriSFSVertical": "Vertikalno" } });const _Buffer = require('safe-buffer').Buffer const Cryptojs = require('crypto-js') //base58所包含的字符 与base64不同的是,其中去除了容易引起误解的字符如O和0、l和I、/ + const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; /** * Base58编码 * 这是一个依照bitcoin中Base58Check编码实现的js版base58编码工具 */ module.exports = Base58 = function () { //申请长度256的int8数组 const BASE_MAP = new Uint8Array(256); //将BASE_MAP数组所有元素初始化为255 for (let j = 0; j < BASE_MAP.length; j++) { BASE_MAP[j] = 255; } //将ALPHABET中的字符对应到索引 for (let i = 0; i < ALPHABET.length; i++) { let x = ALPHABET.charAt(i); let xc = x.charCodeAt(0); if (BASE_MAP[xc] !== 255) throw new TypeError(x + 'is ambiguous') BASE_MAP[xc] = i; } let BASE = ALPHABET.length; let LEADER = ALPHABET.charAt(0); var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up //iFACTOR数学含义 //iFACTOR用于计算经过base58编码后,字符串所需要的空间大小 //因为输出的每个字符都是从58个字符中选择出来的,及每一个字符代表的信息量为log(2)58 //而我们输入的字节流长度是固定(byte_length * 8)bit = (byte_length * log(2)256) //需要预留的输出字符空间长度就为 (byte_length * log(2)256) / log(2)58 = byte_length * 1.37 + 1 var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up /** * encode * @param {*} source * @returns */ function encode(source) { //判断传入的source是否为Buffer if (Array.isArray(source) || source instanceof Uint8Array) source = _Buffer.from(source); if (!_Buffer.isBuffer(source)) throw new TypeError('Expected Buffer'); if (source.length === 0) return ''; let zeroes = 0; let length = 0; let pbegin = 0; let pend = source.length; //将pbegin定位到除开头为零的元素上 while (pbegin !== pend && source[pbegin] === 0) { pbegin++; //对资源开头存在零进行计数 zeroes++; } // Allocate enough space in big-endian base58 representation. //编码所得结果字符大小 let size = Math.floor((pend - pbegin) * iFACTOR + 1); //申请字符空间大小为size的uint8字符数组 let b58 = new Uint8Array(size); //遍历buffer中的每个元素(得到的会是对应十六进制转为十进制),将十进制转换为58进制 while (pbegin !== pend) { let carry = source[pbegin]; //得到buffer中的值,这里得到的值为10进制。0x80 —> 128 let i = 0; for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) { carry += Math.floor((256 * b58[it])); b58[it] = Math.floor((carry % BASE)); carry = Math.floor((carry / BASE)); } if (carry !== 0) throw new Error('Non-zero carry') length = i; pbegin++; } //跳过开头所有的为零的字符 let it = size - length; while (it !== size && b58[it] === 0) { it++ } //将开头为零的数量还原 let str = LEADER.repeat(zeroes); while (it < size) { str += ALPHABET.charAt(b58[it]); ++it; } return str } /** * decodeUnsafe * @param {*} source * @returns */ function decodeUnsafe(source) { if (typeof source !== 'string') throw new TypeError('Expected String'); if (source.length === 0) return _Buffer.alloc(0); let psz = 0; // Skip leading spaces. if (source[psz] === ' ') return let zeroes = 0; let length = 0; // Skip and count leading '1's. while (source[psz] === LEADER) { zeroes++; psz++; } let size = (((source.length - psz) * FACTOR) + 1) >>> 0; let b256 = new Uint8Array(size); while (source[psz]) { let carry = BASE_MAP[source.charCodeAt(psz)]; if (carry === 255) return let i = 0; for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) { carry += (BASE * b256[it]) >>> 0 b256[it] = (carry % 256) >>> 0 carry = (carry / 256) >>> 0 } if (carry !== 0) throw new Error('Non-zero carry') length = i; psz++; } // Skip trailing spaces. if (source[psz] === ' ') return let it = size - length while (it !== size && b256[it] === 0) it++; let vch = _Buffer.allocUnsafe(zeroes + (size - it)); vch.fill(0x00, 0, zeroes) let j = zeroes; while (it !== size) { vch[j++] = b256[it++] } return vch } /** * decode * @param {*} string * @returns */ function decode(string) { var buffer = decodeUnsafe(string) if (buffer) { let privateSuffix = buffer.toString('hex').slice(-8); let privateKey = buffer.toString('hex').slice(0,-8); let checkPrefix = Cryptojs.SHA256(Cryptojs.SHA256(privateKey).toString()).toString().slice(0,8); if(checkPrefix === privateSuffix){ return buffer }else{ throw new Error('Incorrect private key') } } throw new Error('Non-base' + BASE + ' character') } return { encode, decode, decodeUnsafe } }() 1000+ import React from 'react'; import classnames from 'classnames'; import Layout from '@theme/Layout'; import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import useBaseUrl from '@docusaurus/useBaseUrl'; import styles from './styles.module.css'; const features = [ { title: <>Runs on Kubernetes, imageUrl: 'https://kubernetes.io/images/nav_logo.svg', description: ( <> Kilo can be installed on any Kubernetes cluster, allowing nodes located in different clouds or in different coutries to form a single cluster. ), clip: true, width: "215px", }, { title: <>Built on WireGuard, imageUrl: 'https://www.wireguard.com/img/wireguard.svg', description: ( <> Kilo uses WireGuard, a performant and secure VPN, to create a mesh between the different nodes in a cluster. ), clip: true, width: "187px", }, { title: <>Advanced Features, imageUrl: 'img/kilo.svg', description: ( <> Kilo brings advanced networking functionality to Kubernetes clusters, like accessing Pods via VPN and creating multi-cluster services. ), }, ]; function Feature({imageUrl, title, description, clip, width}) { const imgUrl = useBaseUrl(imageUrl); const imgStyle = {}; if (width) { imgStyle.width = width; } return (

    {imgUrl && (
    {title}
    )}

    {title}

    {description}

    ); } function Home() { const context = useDocusaurusContext(); const {siteConfig = {}} = context; return (

    {siteConfig.title}

    {siteConfig.tagline}

    Get Started
    {features && features.length && (
    {features.map((props, idx) => ( ))}
    )}
    ); } export default Home; function pathSumThreeWays(arr) { var len = arr.length var solution = new Int32Array(len) for (var i = 0; i < len; i++) { solution[i] = arr[i][len - 1]; } for (var i = len - 2; i > -1; i--) { // go down solution[0] += arr[0][i]; for (var j = 1; j < len; j++) { solution[j] = Math.min(solution[j - 1] + arr[j][i], solution[j] + arr[j][i]); } //go up for (var j = len - 2; j > -1; j--) { solution[j] = Math.min(solution[j], solution[j+1] + arr[j][i]); } } return Math.min(...solution) } // Only change code above this line const testMatrix = [ [131, 673, 234, 103, 18], [201, 96, 342, 965, 150], [630, 803, 746, 422, 111], [537, 699, 497, 121, 956], [805, 732, 524, 37, 331] ]; pathSumThreeWays(testMatrix); /** JavaScript singleton design pattern for storing game session data */ var GameSession = function () { 'use strict' if (!GameSession.instance) { console.log('Singleton.instance is undefined. Creating singleton...') var _text = 'private' var public_members = { text: 'public', // Game information layout: null, tileset: null, colours: null, theme: null, beginnerMode: false, enabledHints: false, practiceGame: false, timer: null, sound: true, // Layout information sizeX: 0, sizeY: 0, scale: 0, offsetX: 0, offsetY: 0, logText: function () { // Console log the public member variable console.info('Singleton>>Public Member: ' + this.text) // Console log the private member variable console.info('Singleton>>Private Member: ' + _text) }, toString: function () { return '[object Singleton]' }, setInstance: function () { GameSession.instance = this } } // Set the instance as a reference to the public_members object public_members.setInstance() return public_members } else { //console.warn('Singleton already has an instance, here it is: ' + GameSession.instance) return GameSession.instance } } gameSession = new GameSession() 'use strict'; var url = require('url'); var gulp = require('gulp'); var gutil = require('gulp-util'); var babelify = require('babelify'); var browserify = require('browserify'); var watchify = require('watchify'); var cacheify = require('cacheify'); var levelup = require('levelup'); var source = require('vinyl-source-stream'); var less = require('gulp-less'); var connect = require('gulp-connect'); var autoprefixer = require('autoprefixer'); var LessPluginAutoPrefix = require('less-plugin-autoprefix'); var autoprefix = new LessPluginAutoPrefix({ browsers: ['last 2 versions'] }); var levelDb = levelup('./.cache'); var jsWatcher; var srcRoot = 'site'; var port = 3089; var watchPaths = { site: { jsSrc: 'site/js/index.js', jsDest: 'site/js/', jsFile: 'bundle.js', less: 'site/style/less/**/*.less', css: 'site/style/css/', }, dragResize: { jsSrc: './src/js/drag-resize/drag-resize.js', jsDest: 'src/js/', jsFile: 'drag-resize.js', less: 'src/style/less/drag-resize.less', css: 'src/style/css/', moduleName: 'drag-resize' } }; var browserifyOpts = { entries: [watchPaths.site.jsSrc], debug: true, insertGlobals: true, detectGlobals: false }; gulp.task('connect', function () { connect.server({ root: [srcRoot, './'], port: port, livereload: { port: port * 10 }, fallback: './index.html' }); }); gulp.task('watch-html', function () { gulp.watch('./index.html', function () { return gulp.src('./**/*.html') .pipe(connect.reload()); }); }); gulp.task('watch-less', function () { var parseLess = function () { return gulp.src(watchPaths.site.less) .pipe(less({ plugins: [autoprefix] })) .pipe(gulp.dest(watchPaths.site.css)) .pipe(connect.reload()); }; parseLess(); gulp.watch(watchPaths.site.less, parseLess); }); gulp.task('builder-drag-resize-less', function () { var conf = watchPaths.dragResize; var parseLess = function () { return gulp.src(conf.less) .pipe(less({ plugins: [autoprefix] })) .pipe(gulp.dest(conf.css)) .pipe(connect.reload()); }; parseLess(); gulp.watch(conf.less, parseLess); }); gulp.task('builder-drag-resize', function () { var conf = watchPaths.dragResize; var opts = { debug: true, insertGlobals: true, detectGlobals: false }; var dragResizeWatcher; var dragResizeBundle = function () { return dragResizeWatcher.bundle() .on('error', function (err) { console.log(err.message); console.log(err.stack); }) .pipe(source(conf.jsFile)) .pipe(gulp.dest(conf.jsDest)) .pipe(connect.reload()); }; var babelifyTrans = cacheify(babelify.configure({ presets: ["es2015", "stage-0", "react"], plugins: ['external-helpers'] }), levelDb); var bundler = browserify(opts) .require(conf.jsSrc, {expose: conf.moduleName}) .external(['react', 'react-dom']) .transform(babelifyTrans); dragResizeWatcher = watchify(bundler) .on('update', dragResizeBundle) .on('log', gutil.log); dragResizeBundle(); }); var bundle = function () { return jsWatcher.bundle() .on('error', function (err) { console.log(err.message); console.log(err.stack); }) .pipe(source(watchPaths.site.jsFile)) .pipe(gulp.dest(watchPaths.site.jsDest)) .pipe(connect.reload()); }; var babelifyTrans = cacheify(babelify.configure({ presets: ["es2015", "stage-0", "react"], plugins: ['external-helpers'] }), levelDb); var bundler = browserify(browserifyOpts) .external(['react', 'react-dom', 'drag-resize']) .transform(babelifyTrans); jsWatcher = watchify(bundler) .on('update', bundle) .on('log', gutil.log); gulp.task('build', ['builder-drag-resize', 'builder-drag-resize-less']); gulp.task('watch-js', bundle); gulp.task('watch', ['watch-js', 'watch-html', 'watch-less']) gulp.task('default', ['connect', 'watch']); var handlers = { "dialogs": requestDialogs, "messages" : requestMessages, } function findPage(identificator) { var page = pageStack.currentPage for (var i=0;i 0) { page.listAlias.positionViewAtIndex(Math.min(data.unreadCount(), 20), ListView.Contain) } else if (page.listAlias.visibleArea.yPosition > 0.99 && page.offsetBottom === -1) { page.listAlias.positionViewAtEnd() }*/ if (page.offsetBottom > data.offset() || page.offsetBottom === -1) { page.offsetBottom = data.offset(); } if (page.offsetTop < data.offset() + data.count() || page.offsetTop === -1) { page.offsetTop = data.offset() + data.count() } page.ready = true } function requestDialogs(data) { var page = findDialogPage() if (!page) { console.log("ERROR: cannot find dialog page") return } console.log("appending dialogs to a existing model") if (page.listAlias.model.count() === 0) { page.listAlias.model.appendDialogs(vk.getStorage(), page.downloadCount) } page.ready = true } function requestData(handler, name) { if (handlers[name] === undefined) { console.log("cannot find function for handler with name",name) return; } handlers[name](handler) } volcain-io/fewd-arcade-game-master /* Effects.js * @descprition This is simply an effects utility bases on Promises. * It eases the process of handling effects, so that they can be used in the game. */ (() => { /* * @description This is used to hide an element. * @param {selectors} is a string containing one or more CSS selectors separated by commas * @param {all} indicates to select all elementy. default is false. */ function hide(selectors, all = false) { return new Promise((resolve, reject) => { const elem = all ? document.querySelectorAll(selectors) : document.querySelector(selectors); if (elem) { if (all) { elem.forEach(item => item.classList.add('hide')); } else { elem.classList.add('hide'); } resolve(); } reject(new Error(`No match found for ${elem}`)); }); } /* * @description This is used to remove an element. * @param {selectors} is a string containing one or more CSS selectors separated by commas * @param {all} indicates to select all elementy. default is false. */ function remove(selectors, all = false) { return new Promise((resolve, reject) => { const elem = all ? document.querySelectorAll(selectors) : document.querySelector(selectors); if (elem) { if (all) { elem.forEach(item => item.classList.add('remove')); } else { elem.classList.add('remove'); } resolve(); } reject(new Error(`No match found for ${elem}`)); }); } /* * @description This is used to show an element. * @param {selectors} is a string containing one or more CSS selectors separated by commas * @param {all} indicates to select all elementy. default is false. */ function show(selectors, all = false) { return new Promise((resolve, reject) => { const elem = all ? document.querySelectorAll(selectors) : document.querySelector(selectors); if (elem) { if (all) { elem.forEach(item => item.classList.remove('hide', 'remove')); } else { elem.classList.remove('hide', 'remove'); } resolve(); } reject(new Error(`No match found for ${selectors}`)); }); } /* This object defines the publicly accessible functions available to * developers by creating a global Effects object. */ window.Effects = { hide, remove, show }; })(); client/src/store/reducers/polls.js0 import { SET_POLLS, SET_CURRENT_POLL } from '../actionsTypes'; export const polls = (state = [], action) => { switch (action.type) { case SET_POLLS: return action.polls; default: return state; } } export const currentPolls = (state = {}, action) => { switch (action.type) { case SET_CURRENT_POLL: return action.poll; default: return state; } }exports.expirationTime = 31536000; exports.secret = process.env.SECRET; var fs = require('fs'); var path = require('path'); var inquirer = require('inquirer'); function getDirectories(srcpath) { if(!fs.existsSync(srcpath)) { return []; } return fs.readdirSync(srcpath).filter(function(file) { return fs.statSync(path.join(srcpath, file)).isDirectory(); }); }; exports.getModuleList = function(srcpath) { var modules = getDirectories(srcpath); modules.push(new inquirer.Separator()); modules.push('new module'); return modules; };import React from 'react'; import { resolve } from '../styles'; import { withRouter } from 'react-router'; import AssetManager from '../utils/AssetManager'; import SiteStyles from '../styles/Site.less'; import IsometricMap from '../components/IsometricMap'; /* eslint no-console: 0 */ /* eslint arrow-body-style: 0 */ /* eslint react/jsx-no-bind: 0 */ class Home extends React.Component { static displayName = 'Home'; static propTypes = { classes: React.PropTypes.object, router: React.PropTypes.shape({ push: React.PropTypes.func.isRequired, }).isRequired, }; static defaultProps = { classes: SiteStyles, }; constructor(props) { super(props); this.assetManager = new AssetManager(); this.assetManager.downloadAll(); this.sounds = this.assetManager.assets; // this.background = ~~(Math.random() * 3); } componentDidMount() { this.isometric = new IsometricMap(this.container); setTimeout(() => { this.startLoop(); setTimeout(() => { this.stopLoop(); }, 28000); }, 400); } componentWillUnmount() { this.isometric.cancelAnimation(); this.stopLoop(); } onClick = (path) => { this.stopLoop(); const { router } = this.props; router.push(path); }; startLoop = () => { const checkSound = this.sounds.isoloop.data.playing(); if (!checkSound) { this.sounds.isoloop.data.play(); this.sounds.isoloop.data.fade(0, 0.4, 6000); } }; stopLoop = () => { this.sounds.isoloop.data.fade(0.4, 0, 6000); setTimeout(() => { this.sounds.isoloop.data.stop(); }, 6000); }; render() { const { classes } = this.props; return (
    { this.container = c; }} >
    ); } } export default withRouter(Home); SainathPoojary/Awesome-Chrome-Extensions !(function (e) { function t(t) { for ( var s, i, a = t[0], l = t[1], c = t[2], d = 0, f = []; d < a.length; d++ ) (i = a[d]), Object.prototype.hasOwnProperty.call(n, i) && n[i] && f.push(n[i][0]), (n[i] = 0); for (s in l) Object.prototype.hasOwnProperty.call(l, s) && (e[s] = l[s]); for (u && u(t); f.length; ) f.shift()(); return o.push.apply(o, c || []), r(); } function r() { for (var e, t = 0; t < o.length; t++) { for (var r = o[t], s = !0, a = 1; a < r.length; a++) { var l = r[a]; 0 !== n[l] && (s = !1); } s && (o.splice(t--, 1), (e = i((i.s = r[0])))); } return e; } var s = {}, n = { 1: 0 }, o = []; function i(t) { if (s[t]) return s[t].exports; var r = (s[t] = { i: t, l: !1, exports: {} }); return e[t].call(r.exports, r, r.exports, i), (r.l = !0), r.exports; } (i.m = e), (i.c = s), (i.d = function (e, t, r) { i.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: r }); }), (i.r = function (e) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e, "__esModule", { value: !0 }); }), (i.t = function (e, t) { if ((1 & t && (e = i(e)), 8 & t)) return e; if (4 & t && "object" == typeof e && e && e.__esModule) return e; var r = Object.create(null); if ( (i.r(r), Object.defineProperty(r, "default", { enumerable: !0, value: e }), 2 & t && "string" != typeof e) ) for (var s in e) i.d( r, s, function (t) { return e[t]; }.bind(null, s) ); return r; }), (i.n = function (e) { var t = e && e.__esModule ? function () { return e.default; } : function () { return e; }; return i.d(t, "a", t), t; }), (i.o = function (e, t) { return Object.prototype.hasOwnProperty.call(e, t); }), (i.p = ""); var a = (window.webpackJsonp = window.webpackJsonp || []), l = a.push.bind(a); (a.push = t), (a = a.slice()); for (var c = 0; c < a.length; c++) t(a[c]); var u = l; o.push([12, 0]), r(); })([ , function (e, t, r) { "use strict"; Object.defineProperty(t, "__esModule", { value: !0 }); var s = r(3); (t.fetchDomainString = s.fetchDomainString), (t.fetchUrlString = s.fetchUrlString), (t.isUrlInList = s.isUrlInList), (t.isEmpty = s.isEmpty), (t.isSystemDarkMode = s.isSystemDarkMode); var n = r(4); t.permission = n.permission; var o = r(5); t.runtime = o.runtime; var i = r(6); t.tabs = i.tabs; }, function (e, t, r) { "use strict"; Object.defineProperty(t, "__esModule", { value: !0 }); t.config = { cssFilePath: "app/app.css", storageDomainList: "domainList", storageExcludedUrlList: "excludedUrlList", domainList: [], excludedUrlList: [], defaultDomainList: ["github.com", "gist.github.com"], defaultExcludedUrlList: ["github.com/marketplace"], useSystemPrefersScheme: !1, uninstallQuestionnaire: "", }; }, function (e, t, r) { "use strict"; Object.defineProperty(t, "__esModule", { value: !0 }); t.fetchDomainString = (e) => { if (!e) return ""; let t = e.match( /([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?/g ); return null === t ? "" : t[0]; }; t.fetchUrlString = (e) => { if (!e) return ""; let t = e.match( /([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\/.*)?$/g ); return null === t ? "" : t[0]; }; t.isUrlInList = (e, t, r = !1) => { var s = !1; return ( t.forEach((t) => { let n = new RegExp(`^${t}${r ? "\\w*" : "(/+|$)"}`, "g"); s = !(!s && !e.match(n)); }), s ); }; t.isEmpty = (e) => null == e || 0 === Object.getOwnPropertyNames(e).length; t.isSystemDarkMode = () => window.matchMedia("(prefers-color-scheme: dark)").matches; }, function (e, t, r) { "use strict"; Object.defineProperty(t, "__esModule", { value: !0 }); const s = r(0), n = { set: (e, t, r) => { r || (r = (r) => { console.log(`${e} set ${t} is ${r ? "granted" : "not granted"}.`); }), s.browser.permissions .request({ origins: [e], permissions: [t] }) .then(r); }, remove: (e, t, r) => { r || (r = (r) => { console.log( `${e} set '${t}' permission is ${ r ? "removed" : "not removed" }.` ); }), s.browser.permissions .remove({ origins: [e], permissions: [t] }) .then(r); }, isSupport: (e, t, r) => { r || (r = (r) => { console.log(`${r ? "Yes" : "Not"}, ${e} has '${t}' permission.`); }), s.browser.permissions .contains({ origins: [e], permissions: [t] }) .then(r); }, print: () => { s.browser.permissions.getAll().then((e) => console.table(e)); }, }; t.permission = n; }, function (e, t, r) { "use strict"; Object.defineProperty(t, "__esModule", { value: !0 }); const s = r(0), n = { setUninstallURL: (e) => { s.browser.runtime.setUninstallURL(e).then(() => { console.log("We are sorry to see you go! :("); }); }, }; t.runtime = n; }, function (e, t, r) { "use strict"; Object.defineProperty(t, "__esModule", { value: !0 }); const s = r(0), n = { getCurrentTab: () => s.browser.tabs .query({ active: !0, currentWindow: !0 }) .then((e) => e[0]), addTab: (e) => { s.browser.tabs.create({ active: !0, url: "http://" + e }); }, }; t.tabs = n; }, , , , , , function (e, t, r) { "use strict"; Object.defineProperty(t, "__esModule", { value: !0 }); const s = r(2), n = r(1), o = r(0); r(13); const i = () => { o.browser.tabs.onUpdated.addListener((e, t, r) => { if ("loading" === t.status) { if (navigator.userAgent.includes("Firefox") && !t.url) return; o.browser.storage.sync .get([s.config.storageDomainList, s.config.storageExcludedUrlList]) .then((e) => { if (!r) return; if (!r.url) return; if (n.isUrlInList(n.fetchUrlString(r.url), e.excludedUrlList)) return; console.clear(), console.log("Current URL: " + r.url), console.log("Domain List:"), console.table(e.domainList), console.log("Excluded URL List:"), console.table(e.excludedUrlList); e.themeBasedOn; n.isUrlInList(n.fetchDomainString(r.url), e.domainList) && o.browser.tabs.insertCSS(r.id, { file: s.config.cssFilePath, runAt: "document_start", }); }); } }); }; n.runtime.setUninstallURL(s.config.uninstallQuestionnaire), o.browser.storage ? (console.log("Storage Mode"), o.browser.storage.sync .get([s.config.storageDomainList, s.config.storageExcludedUrlList]) .then((e) => { if (!n.isEmpty(e)) return e; o.browser.storage.sync.set({ domainList: s.config.defaultDomainList, excludedUrlList: s.config.defaultExcludedUrlList, }); }) .then(i)) : (console.log("ContentScripts Mode"), o.browser.contentScripts .register({ matches: ['"https://github.com/*', "https://gist.github.com/*"], runAt: "document_start", js: [ { file: "app/content_script.js" }, { file: "app/vendor.js" }, ], css: [{ file: "app/app.css" }], }) .catch((e) => console.log(e))); }, ]); const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ const scripts = ['app', 'login', 'register', 'create-room', 'room', 'add-video']; const styles = ['app']; const libs = ['axios', 'hls.js', 'laravel-echo', 'pusher-js', 'vue']; scripts.forEach(script => mix.ts(`resources/ts/${script}.ts`, 'public/js')); styles.forEach(style => mix.sass(`resources/sass/${style}.scss`, 'public/css')); mix.extract(libs).version(); const axios = require('axios'); import modalVerMais from '../modalVerMais/modalVerMais.vue'; import modalEditar from '../modalEditar/modalEditar.vue'; import modalExcluir from '../modalExcluir/modalExcluir.vue'; const columns = [{ title: 'Nome do Evento', dataIndex: 'nome', width: 200, }, { title: 'Data do Evento', dataIndex: 'data', width: 200, }, { title: 'Status do Evento', dataIndex: 'status', }, { title: 'Action', key: 'operation', fixed: 'right', width: 200, scopedSlots: { customRender: 'action' }, }, ]; export default { components: { modalVerMais, modalEditar, modalExcluir }, methods: { openModal(data) { this.modalData = data this.modalVisible = true }, pegar_tabela(name) { axios.get('http://localhost:3000/api/' + name) .then((response) => { console.log("Listou " + name); console.log(response.data); this.res_localizar = response.data }) .catch(function (error) { console.log(error); }) }, }, data() { return { res_localizar: [], columns: [], tabelas: [], modalVisible: false, modalData: '' } } }const ThunderClient = require('../src/thunder-client'); const sinon = require('sinon'); const chai = require('chai'); const request = require('request'); const expect = chai.expect; // Constant test values const baseUrl = 'http://localhost:8080'; const apiKey = 'apiKey'; const apiSecret = 'apiSecret'; const email = ''; const password = ''; const token = 'generated-token'; const user = { email: email, password: password }; describe('', () => { sinon.stub(request, 'defaults').returns(request); const thunder = new ThunderClient(baseUrl, apiKey, apiSecret); afterEach(() => { sinon.restore(); }); describe('#createUser()', () => { it('uses the correct request data', () => { sinon.stub(request, 'post').callsFake(function(ops, callback) { expect(ops.url).to.equal('/users'); expect(ops.json).to.be.true; expect(ops.body).to.deep.equal(user); callback(null, { statusCode: 201 }, user); }); thunder.createUser(user, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(201); }); }); it('calls back on request error', () => { sinon.stub(request, 'post').callsFake(function(ops, callback) { callback(new Error('A create error occurred.')); }); thunder.createUser(user, (err, statusCode, result) => { expect(result).to.be.undefined; expect(statusCode).to.be.undefined; expect(err.message).to.equal('A create error occurred.'); }); }); it('calls back on status code error', () => { sinon.stub(request, 'post').callsFake(function(ops, callback) { callback(null, { statusCode: 400 }, 'Bad create request'); }); thunder.createUser(user, (err, statusCode, result) => { expect(err.message).to.equal('The status code 400 does not match expected 201'); expect(result).to.equal('Bad create request'); expect(statusCode).to.equal(400); }); }); }); describe('#getUser()', () => { it('uses the correct request data', () => { sinon.stub(request, 'get').callsFake(function(ops, callback) { expect(ops.url).to.equal('/users'); expect(ops.qs).to.deep.equal({ email: email }); expect(ops.headers).to.deep.equal({ password: password }); callback(null, { statusCode: 200 }, user); }); thunder.getUser(email, password, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(200); }); }); it('calls back on request error', () => { sinon.stub(request, 'get').callsFake(function(ops, callback) { callback(new Error('A get error occurred.')); }); thunder.getUser(email, password, (err, statusCode, result) => { expect(result).to.be.undefined; expect(statusCode).to.be.undefined; expect(err.message).to.equal('A get error occurred.'); }); }); it('calls back on status code error', () => { sinon.stub(request, 'get').callsFake(function(ops, callback) { callback(null, { statusCode: 400 }, 'Bad get request'); }); thunder.getUser(email, password, (err, statusCode, result) => { expect(err.message).to.equal('The status code 400 does not match expected 200'); expect(result).to.equal('Bad get request'); expect(statusCode).to.equal(400); }); }); }); describe('#updateUser()', () => { it('uses the correct request data for an email update', () => { sinon.stub(request, 'put').callsFake(function(ops, callback) { expect(ops.url).to.equal('/users'); expect(ops.qs).to.deep.equal({ email: email }); expect(ops.headers).to.deep.equal({ password: password }); expect(ops.body).to.deep.equal(user); expect(ops.json).to.be.true; callback(null, { statusCode: 200 }, user); }); thunder.updateUser(email, password, user, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(200); }); }); it('uses the correct query param data for a general update', () => { sinon.stub(request, 'put').callsFake(function(ops, callback) { expect(ops.qs).to.deep.equal({}); callback(null, { statusCode: 200 }, user); }); thunder.updateUser(null, password, user, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(200); }); }); it('calls back on request error', () => { sinon.stub(request, 'put').callsFake(function(ops, callback) { callback(new Error('An update error occurred.')); }); thunder.updateUser(email, password, user, (err, statusCode, result) => { expect(result).to.be.undefined; expect(statusCode).to.be.undefined; expect(err.message).to.equal('An update error occurred.'); }); }); it('calls back on status code error', () => { sinon.stub(request, 'put').callsFake(function(ops, callback) { callback(null, { statusCode: 400 }, 'Bad update request'); }); thunder.updateUser(email, password, user, (err, statusCode, result) => { expect(err.message).to.equal('The status code 400 does not match expected 200'); expect(result).to.equal('Bad update request'); expect(statusCode).to.equal(400); }); }); }); describe('#deleteUser()', () => { it('uses the correct request data', () => { sinon.stub(request, 'delete').callsFake(function(ops, callback) { expect(ops.url).to.equal('/users'); expect(ops.qs).to.deep.equal({ email: email }); expect(ops.headers).to.deep.equal({ password: password }); callback(null, { statusCode: 200 }, user); }); thunder.deleteUser(email, password, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(200); }); }); it('calls back on request error', () => { sinon.stub(request, 'delete').callsFake(function(ops, callback) { callback(new Error('A delete error occurred.')); }); thunder.deleteUser(email, password, (err, statusCode, result) => { expect(result).to.be.undefined; expect(statusCode).to.be.undefined; expect(err.message).to.equal('A delete error occurred.'); }); }); it('calls back on status code error', () => { sinon.stub(request, 'delete').callsFake(function(ops, callback) { callback(null, { statusCode: 400 }, 'Bad delete request'); }); thunder.deleteUser(email, password, (err, statusCode, result) => { expect(err.message).to.equal('The status code 400 does not match expected 200'); expect(result).to.equal('Bad delete request'); expect(statusCode).to.equal(400); }); }); }); describe('#sendEmail()', () => { it('uses the correct request data', () => { sinon.stub(request, 'post').callsFake(function(ops, callback) { expect(ops.url).to.equal('/verify'); expect(ops.qs).to.deep.equal({ email: email }); expect(ops.headers).to.deep.equal({ password: password }); callback(null, { statusCode: 200 }, user); }); thunder.sendEmail(email, password, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(200); }); }); it('calls back on request error', () => { sinon.stub(request, 'post').callsFake(function(ops, callback) { callback(new Error('A send email error occurred.')); }); thunder.sendEmail(email, password, (err, statusCode, result) => { expect(result).to.be.undefined; expect(statusCode).to.be.undefined; expect(err.message).to.equal('A send email error occurred.'); }); }); it('calls back on status code error', () => { sinon.stub(request, 'post').callsFake(function(ops, callback) { callback(null, { statusCode: 400 }, 'Bad send email request'); }); thunder.sendEmail(email, password, (err, statusCode, result) => { expect(err.message).to.equal('The status code 400 does not match expected 200'); expect(result).to.equal('Bad send email request'); expect(statusCode).to.equal(400); }); }); }); describe('#verifyUser()', () => { it('uses the correct default request data', () => { sinon.stub(request, 'get').callsFake(function(ops, callback) { expect(ops.url).to.equal('/verify'); expect(ops.qs).to.deep.equal({ email: email, token: token, response_type: 'json' }); callback(null, { statusCode: 200 }, user); }); thunder.verifyUser(email, token, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(200); }); }); it('uses the correct request data when HTML is specified', () => { sinon.stub(request, 'get').callsFake(function(ops, callback) { expect(ops.url).to.equal('/verify'); expect(ops.qs).to.deep.equal({ email: email, token: token, response_type: 'html' }); callback(null, { statusCode: 200 }, user); }); thunder.verifyUser(email, token, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(200); }, 'html'); }); it('uses the correct request data when JSON is specified', () => { sinon.stub(request, 'get').callsFake(function(ops, callback) { expect(ops.url).to.equal('/verify'); expect(ops.qs).to.deep.equal({ email: email, token: token, response_type: 'json' }); callback(null, { statusCode: 200 }, user); }); thunder.verifyUser(email, token, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(200); }, 'json'); }); it('calls back on bad responseType error', () => { thunder.verifyUser(email, token, (err, statusCode, result) => { expect(result).to.be.undefined; expect(statusCode).to.be.undefined; expect(err.message).to.equal('The response type badType is not accepted.' + '\nUse either "html" or "json".'); }, 'badType'); }); it('calls back on request error', () => { sinon.stub(request, 'get').callsFake(function(ops, callback) { callback(new Error('A verify error occurred.')); }); thunder.verifyUser(email, token, (err, statusCode, result) => { expect(result).to.be.undefined; expect(statusCode).to.be.undefined; expect(err.message).to.equal('A verify error occurred.'); }); }); it('calls back on status code error', () => { sinon.stub(request, 'get').callsFake(function(ops, callback) { callback(null, { statusCode: 400 }, 'Bad verify request'); }); thunder.verifyUser(email, token, (err, statusCode, result) => { expect(err.message).to.equal('The status code 400 does not match expected 200'); expect(result).to.equal('Bad verify request'); expect(statusCode).to.equal(400); }); }); }); describe('#resetVerificationStatus()', () => { it('uses the correct request data', () => { sinon.stub(request, 'post').callsFake(function(ops, callback) { expect(ops.url).to.equal('/verify/reset'); expect(ops.qs).to.deep.equal({ email: email }); expect(ops.headers).to.deep.equal({ password: password }); callback(null, { statusCode: 200 }, user); }); thunder.resetVerificationStatus(email, password, (err, statusCode, result) => { expect(result).to.deep.equal(user); expect(statusCode).to.equal(200); }); }); it('calls back on request error', () => { sinon.stub(request, 'post').callsFake(function(ops, callback) { callback(new Error('A send email error occurred.')); }); thunder.resetVerificationStatus(email, password, (err, statusCode, result) => { expect(result).to.be.undefined; expect(statusCode).to.be.undefined; expect(err.message).to.equal('A send email error occurred.'); }); }); it('calls back on status code error', () => { sinon.stub(request, 'post').callsFake(function(ops, callback) { callback(null, { statusCode: 400 }, 'Bad reset verification status request'); }); thunder.resetVerificationStatus(email, password, (err, statusCode, result) => { expect(err.message).to.equal('The status code 400 does not match expected 200'); expect(result).to.equal('Bad reset verification status request'); expect(statusCode).to.equal(400); }); }); }); }); cagov/ca-design-system-gutenberg-blocks import { WebComponent, MultipleWebComponent, MultipleWebComponentLongPage } from "./storybook-web-component"; import { html } from "lit-html"; import './index.scss'; export default { title: "@cagov/accordion", argTypes: { // backgroundColor: { control: "color" }, // onClick: { action: "onClick" }, accordionLabel: { control: { type: "string" } }, accordionContent: { control: { type: "string", disable: true } }, accordions: { control: { type: "array", disable: true } }, expanded: { control: { type: "boolean", disable: true } }, }, decorators: [], }; const Template = (args) => WebComponent(args); export const BasicAccordion = Template.bind({}); BasicAccordion.storyName = "Basic Accordion"; BasicAccordion.args = { expanded: false, accordionLabel: "What are the similarities and differences between Influenza (flu) and COVID-19?", accordionContent: html`

    Influenza (flu) and COVID-19 are both contagious respiratory illnesses, but they’re caused by different viruses. COVID-19 is caused by a new coronavirus (called SARS-CoV-2) and flu is caused by influenza viruses

    The symptoms of flu and COVID-19 are similar. It is hard to tell the difference between them without testing.

    Cases of COVID-19 and flu can have anything from no symptoms (asymptomatic) to severe symptoms. Common symptoms that COVID-19 and flu share include:

    • Fever or chills
    • Cough
    • Shortness of breath or difficulty breathing
    • Fatigue (tiredness)
    • Sore throat
    • Runny or stuffy nose
    • Muscle pain or body aches
    • Headache
    • Vomiting and diarrhea (more common in children than adults)

    The major difference between them is COVID-19 may include change in or loss of taste or smell.

    The CDC has more information about similarities and differences between the flu and COVID-19.

    `, }; export const BasicAccordionOpen = Template.bind({}); BasicAccordionOpen.storyName = "Basic Accordion, open"; BasicAccordionOpen.args = { expanded: true, accordionLabel: "Open accordion", accordionContent: html`

    Accordion content

    `, }; export const MultipleAccordions = MultipleWebComponent.bind({}); MultipleAccordions.storyName = "Three accordions, middle item open"; MultipleAccordions.args = { accordions: [ { accordionLabel: "Minimum wage increases on January 1, 2020", accordionContent: html`
    PlaceRate
    Alameda
    Berkeley
    Emeryville
    link inside of closed accordion`, expanded: false, }, { accordionLabel: "Minimum wage increases on July 1, 2020", accordionContent: html`
    PlaceRate
    Alameda$15/hour
    BerkeleyThe rate will increase from $15.59/hour based on the Consumer Price Index.
    Emeryville$16.42/hour (estimated). The rate will increase based on the Consumer Price Index
    link inside of open accordion`, expanded: true, }, { accordionLabel: "Accordion with plain text", accordionContent: html`

    Vivamus rhoncus dictum turpis et ullamcorper. Pellentesque turpis lectus, dignissim in semper rutrum, consequat ut dui. Curabitur ut ullamcorper purus. In venenatis dui faucibus justo mattis fermentum. Quisque erat quam, convallis vel eleifend eget, volutpat et ex. Donec vestibulum elit purus, sit amet interdum lorem feugiat at. Pellentesque vel augue in nisi dignissim congue a nec est. Phasellus tellus risus, egestas vel tincidunt vitae, suscipit eu ante. Quisque feugiat erat sit amet facilisis congue. Donec eget dolor pretium, ultrices purus sed, interdum sem. Sed quis scelerisque est. Vestibulum ligula dui, dignissim eu egestas et, tincidunt eget sem. Quisque ac finibus risus. Fusce cursus rutrum mauris, in laoreet ligula tempus rhoncus. Phasellus porta lorem tortor. Maecenas magna risus, varius accumsan leo et, condimentum posuere est.

    `, expanded: false, }, ] }; export const MultipleAccordionsLongPage = MultipleWebComponentLongPage.bind({}); MultipleAccordionsLongPage.storyName = "Three accordions, all closed, on a tall page"; MultipleAccordionsLongPage.args = { accordions: [ { accordionLabel: "Accordion1 label", accordionContent: html`

    Second generation vaccines were developed to reduce the risks from live vaccines. These are subunit vaccines, consisting of specific protein antigens (such as tetanus or diphtheria toxoid) or recombinant protein components (such as the hepatitis B surface antigen). They can generate TH and antibody responses, but not killer T cell responses.

    RNA vaccines and DNA vaccines are examples of third generation vaccines.mRNA vaccines such as BNT162b2 were developed in the year 2020 with the help of Operation Warp Speed and massively deployed to combat the coronavirus pandemic.

    Since at least 2013, scientists were trying to develop synthetic 3rd-generation vaccines by reconstructing the outside structure of a virus; it was hoped that this will help prevent vaccine resistance.

    Source: Boom text generator

    `, expanded: false, }, { accordionLabel: "Accordion2 label", accordionContent: html`

    The filing of patents on vaccine development processes can also be viewed as an obstacle to the development of new vaccines. Because of the weak protection offered through a patent on the final product, the protection of the innovation regarding vaccines is often made through the patent of processes used in the development of new vaccines as well as the protection of secrecy.

    Vaccine production has several stages. First, the antigen itself is generated. Viruses are grown either on primary cells such as chicken eggs (e.g., for influenza) or on continuous cell lines such as cultured human cells (e.g., for hepatitis A).

    The final stage in vaccine manufacture before distribution is fill and finish, which is the process of filling vials with vaccines and packaging them for distribution. Although this is a conceptually simple part of the vaccine manufacture process, it is often a bottleneck in the process of distributing and administering vaccines.

    Source: Boom text generator

    `, expanded: false, }, { accordionLabel: "Accordion3 label", accordionContent: html`

    International research on vaccines and medicines in COVID-19 is underway by government organisations, academic groups, and industry researchers.

    As of December 2020

    Repurposed antiviral drugs make up most of the research into COVID-19 treatments.

    Source: Boom text generator

    `, expanded: false, }, ] }; Rajesh-thapa/railway-reservation-system-webApp1-10 function validate() { var fname=document.getElementById("fname"); var lname=document.getElementById("lname"); var age=document.getElementById("age"); var mob=document.getElementById("mob"); var EmailId=document.getElementById("email"); var pw=document.getElementById("pw"); var cpw=document.getElementById("cpw"); var alphaExp = /^[a-zA-Z]+$/; var atpos = EmailId.value.indexOf("@"); var dotpos = EmailId.value.lastIndexOf("."); if(fname.value==null || fname.value=="") { fname.focus(); alert("Enter valid first name"); return false; } if(fname.value.match(alphaExp)){} else{ alert("First name can have only letters"); fname.focus(); return false; } if(lname.value==null || lname.value=="") { lname.focus(); alert("Enter valid last name"); return false; } if(lname.value.match(alphaExp)){} else{ alert("Last name can have only letters"); lname.focus(); return false; } if(age.value==null || age.value=="") { alert("Please Enter Age"); age.focus(); return false; } if (isNaN(age.value)) { alert(" Your Age must be Integer"); age.focus(); return false; } if(mob.value==null || mob.value==" ") { alert("Please Enter Mobile Number"); mob.focus(); return false; } if (isNaN(mob.value)) { alert(" Your Mobile Number must be Integers"); mob.focus(); return false; } if((mob.value.length!= 10)) { alert("Enter the valid Mobile Number(Like : 9669666999)"); mob.focus(); return false; } if (atpos<1 || dotpos=EmailId.value.length) { alert("Enter valid email-ID"); EmailId.focus(); return false; } if(pw.value.length< 8 || cpw.value.length< 8) { alert("Please enter a password of atleast 8 characters"); pw.focus(); return false; } else if (pw.value.length != cpw.value.length) { alert("Passwords do not match."); pw.focus(); return false; } else if (pw.value != cpw.value) { alert("Passwords do not match."); pw.focus(); return false; } return true; }ronyfr3/Project1-10 import { createSlice } from "@reduxjs/toolkit"; import getPlayers from "../api/PlayersApi"; const playerSlice = createSlice({ name: "players", initialState: { players: [], loading: null, }, extraReducers: { [getPlayers.pending]: (state) => { state.loading = "loading"; }, [getPlayers.fulfilled]: (state, action) => { state.players = action.payload; state.loading = "success"; }, [getPlayers.rejected]: (state) => { state.loading = "failed"; }, }, }); export default playerSlice.reducer;const parseArgs = require('minimist') const logUpdate = require('log-update') const { range } = require('lodash') const { readFileSync, writeFileSync } = require('fs') const { resolve } = require('path') const { loadLootTable, loadItemDetails, detailsToCsv } = require('./scripts') const ASSETS = { LOOT_TABLE_CSV: './assets/tbc-loot-table.csv', LOOT_TABLE_JSON: './assets/tbc-loot-table.json', DETAILS_JSON: './assets/tbc-loot-details.json', EXPORT_CSV: './export/tbc-loot-details.csv' } const saveResults = (path, content) => { const resolvedPath = resolve(path) writeFileSync(resolvedPath, content, { encoding: 'utf-8' }) console.log(`Results saved to ${resolvedPath}.`) } const renderProgressBar = (idx, total, barLength = 20) => { const ordinal = idx + 1 const progress = ordinal / total logUpdate( `[${range(barLength) .map(charIdx => (charIdx / barLength < progress ? '=' : ' ')) .join('')}] ${ordinal}/${total}` ) } const stringify = object => JSON.stringify(object, null, 2) async function lootToJson(input, output) { const inputPath = resolve(input || ASSETS.LOOT_TABLE_CSV) console.log(`Loading loot table from ${inputPath} and parsing CSV…`) try { const items = await loadLootTable(inputPath) console.log(`${items.length} items parsed.`) saveResults(output || ASSETS.LOOT_TABLE_JSON, stringify(items)) } catch (errors) { console.error('Failed to load or parse CSV!', errors) } } function loadJson(path, description = 'data') { console.log(`Loading ${description} from ${path}…`) const source = readFileSync(path) return JSON.parse(source) } async function fetchDetails(input, output) { const items = loadJson(resolve(input || ASSETS.LOOT_TABLE_JSON), 'loot table') console.log(`Fetching item details…`) for (let i = 0, l = items.length; i < l; ++i) { renderProgressBar(i, l) const { url } = items[i] items[i].item = await loadItemDetails(url) } saveResults(output || ASSETS.DETAILS_JSON, stringify(items)) } const EXPORT_FIELDS = { ZEPHAN: { ItemSlot: 'item.properties.slot', Slot: 'item.inventorySlot', Item: 'itemName', Location: 'instanceName', Boss: 'sourceName', Sta: 'item.equip.sta', Int: 'item.equip.int', Spi: 'item.equip.spi', Dmg: 'item.equip.spldmg', DvUD: undefined, ShD: 'item.equip.shasplpwr', FrD: 'item.equip.firsplpwr', Hit: 'item.equip.splhitrtng', Crit: 'item.equip.splcritstrkrtng', Haste: 'item.equip.splhastertng', Mp5: 'item.equip.manarng', Pen: 'item.equip.splpen', /* meta: 1, red: 2, yellow: 3, blue: 4 */ Gem: ({ item: { equip: { socket1, socket2, socket3, socket4 } } }) => [socket1, socket2, socket3, socket4] .map(num => ({ 2: 'R', 3: 'Y', 4: 'B' }[num])) .filter(Boolean) .join(''), Meta: ({ item: { equip: { socket1, socket2, socket3, socket4 } } }) => ([socket1, socket2, socket3, socket4].indexOf(1) === -1 ? '' : 1), Type: '', Amount: '', Resi: 'item.equip.resirtng', Set: '', Note: '', 'Socket Count': 'item.equip.nsockets' } } async function exportDetails(input, output, fields) { const items = loadJson(resolve(input || ASSETS.DETAILS_JSON), 'loot details') console.log(`Transforming to CSV…`) const csvString = await detailsToCsv(items, fields) saveResults(output || ASSETS.EXPORT_CSV, csvString) } async function app() { const { _: [script], input, output } = parseArgs(process.argv.slice(2), { string: ['input', 'output'] }) switch (script) { case 'loot-to-json': return lootToJson(input, output) case 'fetch-details': return fetchDetails(input, output) case 'export-details': return exportDetails(input, output, EXPORT_FIELDS.ZEPHAN) default: console.log('No script selected.') } } app().then( () => process.exit(0), error => console.error(error) || process.exit(1) ) "use strict"; const {assert} = require('chai'); const fs = require('fs'); const path = require('path'); const testdb = require('@dawadk/test-util/src/testdb'); const { computeDirty, createChangeTable, computeChanges } = require('../src/materialize'); const { applyInserts, applyDeletes, applyUpdates } = require('../src/table-diff'); const {insert, update, del} = require('../src/table-model-util'); const {go} = require('ts-csp'); const tableModel = { prim: { table: 'prim', primaryKey: ['id'], columns: [{ name: 'id' }, { name: 'name' }, { name: 'sec_id1' }, { name: 'sec_id2' }, { name: 'tert_id_part1' }, { name: 'tert_id_part2' }] }, secondary: { table: 'secondary', primaryKey: ['id'], columns: [{ name: 'id' }, { name: 'name' }] }, tertiary: { table: 'tertiary', primaryKey: ['id_part1', 'id_part2'], columns: [{ name: 'id_part1' }, { name: 'id_part2' }, { name: 'name' }] }, primary_mat: { table: 'primary_mat', primaryKey: ['id'], columns: [{ name: 'id' }, { name: 'prim_name' }, { name: 'sec_id1' }, { name: 'sec_id2' }, { name: 'sec_name1', }, { name: 'sec_name2', public: false }, { name: 'tert_id_part1' }, { name: 'tert_id_part2' }, { name: 'tert_name' }, { name: 'derived' }] } }; const testMaterialization = { table: 'primary_mat', view: 'primary_mat_view', dependents: [{ table: 'prim', columns: ['id'] }, { table: 'secondary', columns: ['sec_id1'] }, { table: 'secondary', columns: ['sec_id2'] }] }; describe('View materialization', () => { const setupSql = fs.readFileSync(path.join(__dirname, 'testMaterializeTables.sql'), {encoding: 'utf8'}); testdb.withTransactionEach('empty', clientFn => { beforeEach(() => go(function*() { yield clientFn().query(setupSql); for (let table of Object.keys(tableModel)) { yield createChangeTable(clientFn(), table); } })); describe('crud', () => { it('Can insert a row', () => go(function*() { const object = { id: '00000000-0000-0000-0000-a7d428a980cf', name: 'foo' }; yield insert(clientFn(), tableModel.prim, object); const result = yield clientFn().queryRows('select * from prim'); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].id, object.id); assert.strictEqual(result[0].name, object.name); })); it('Can update a row', () => go(function*() { const object = { id: '00000000-0000-0000-0000-a7d428a980cf', name: 'foo' }; const updated = { id: '00000000-0000-0000-0000-a7d428a980cf', name: 'bar' }; yield insert(clientFn(), tableModel.prim, object); yield update(clientFn(), tableModel.prim, updated); const result = yield clientFn().queryRows('select * from prim'); assert.strictEqual(result[0].id, object.id); assert.strictEqual(result[0].name, updated.name); })); it('Can delete a row', () => go(function*() { const o1 = { id: '00000000-0000-0000-0000-a7d428a980cf', name: 'foo' }; const o2 = { id: '00000000-0000-0000-0001-a7d428a980cf', name: 'bar' }; yield insert(clientFn(), tableModel.prim, o1); yield insert(clientFn(), tableModel.prim, o2); yield del(clientFn(), tableModel.prim, {id: o2.id}); const result = yield clientFn().queryRows('select * from prim'); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].id, o1.id); })); }); describe('computeDirty', () => { it('If materialized table contains a row, and no dependent rows are changed, the row is not marked dirty', () => go(function*() { const client = clientFn(); yield client.query(`INSERT INTO primary_mat(id, sec_id1) VALUES ('00002732-733c-433a-a5da-a7d428a980cf', 10)`); yield computeDirty(client, 1, tableModel, testMaterialization); const result = yield client.queryRows('select id from primary_mat_dirty'); assert.deepEqual(result, []); })); it('If materialized table contains a row, and a dependent row is changed, the row is marked dirty', () => go(function*() { const client = clientFn(); yield client.query(`INSERT INTO primary_mat(id, sec_id1) VALUES ('00002732-733c-433a-a5da-a7d428a980cf', 10)`); yield client.query(`INSERT INTO secondary_changes(txid, operation, public, id) values(1, 'delete', true, 10)`); yield computeDirty(client, 1, tableModel, testMaterialization); const result = yield client.queryRows('select id from primary_mat_dirty'); assert.deepEqual(result, [{id: '00002732-733c-433a-a5da-a7d428a980cf'}]); })); }); describe('applying changes', () => { const txid = 1; const insertedId = '00000000-733c-433a-a5da-a7d428a980cf'; const deletedId = '00000000-7777-433a-a5da-a7d428a980cf'; const updatedId = '10000000-0000-0000-a5da-a7d428a980cf'; beforeEach(() => go(function*() { const client = clientFn(); yield client.query(`INSERT INTO prim(id, sec_id1) VALUES ('00002732-733c-433a-a5da-a7d428a980cf', 9)`); yield client.query(`INSERT INTO prim(id, sec_id1, name) VALUES ('${updatedId}', 8, 'name')`); yield client.query(`INSERT INTO prim(id, sec_id1, name) VALUES ('${deletedId}', 8, 'toBeDeleted')`); yield client.query(`INSERT INTO prim_changes(txid, operation, public, id, sec_id1) VALUES (${txid}, 'insert', true, '${insertedId}', 10)`); yield client.query(`INSERT INTO prim_changes(txid, operation, public, id, sec_id1) VALUES (${txid}, 'delete', true, '${deletedId}', 11)`); yield client.query(`INSERT INTO prim_changes(txid, operation, public, id, sec_id1, name) VALUES (${txid}, 'update', true, '${updatedId}', 12, null)`); })); it('Correctly applies insert', () => go(function*() { yield applyInserts(clientFn(), txid, tableModel.prim); const result = yield clientFn().queryRows('select id, sec_id1 from prim where id = $1', [insertedId]); assert.strictEqual(result.length, 1); const insertedRow = result[0]; assert.strictEqual(insertedRow.id, insertedId); assert.strictEqual(insertedRow.sec_id1, 10); })); it('Correctly applies delete', () => go(function*() { yield applyDeletes(clientFn(), txid, tableModel.prim); const result = yield clientFn().queryRows('select id, sec_id1 from prim where id = $1',[deletedId]); assert.strictEqual(result.length, 0); })); it('Correctly applies update', () => go(function*() { yield applyUpdates(clientFn(), txid, tableModel.prim); const result = yield clientFn().queryRows('select id, sec_id1,name from prim where id = $1', [updatedId]); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].sec_id1, 12); assert.isNull(result[0].name, 12); })); }); describe('Computing changes', () => { const txid = 2; const unchangedId = '00000000-0000-0000-0000-a7d428a980cf'; const insertedId = '00000000-733c-433a-a5da-a7d428a980cf'; const deletedId = '00000000-0000-433a-a5da-a7d428a980cf'; const updatedId = '10000000-0000-0000-a5da-a7d428a980cf'; const tert_ref_cols = { tert_id_part1: 1, tert_id_part2: 2 }; beforeEach(() => go(function*() { const client = clientFn(); yield insert(client, tableModel.tertiary, {id_part1: 1, id_part2: 2, name: 'tert_name'}); yield insert(client, tableModel.secondary, {id: 10, name: 'second_name'}); yield insert(client, tableModel.prim, Object.assign({id: unchangedId}, tert_ref_cols)); yield insert(client, tableModel.prim, Object.assign({id: deletedId}, tert_ref_cols)); yield insert(client, tableModel.prim, Object.assign({id: updatedId}, tert_ref_cols, { sec_id2: 10 })); yield client.query('INSERT INTO primary_mat (select * from primary_mat_view)'); })); it('Will compute an insert', () => go(function*() { const client = clientFn(); yield client.query( `INSERT INTO prim_changes(txid, operation, public, id, tert_id_part1, tert_id_part2) VALUES(${txid}, 'insert', true, '${insertedId}', 1, 2)`); yield applyInserts(client, txid, tableModel.prim); yield computeDirty(client, txid, tableModel, testMaterialization); yield computeChanges(client, txid, tableModel, testMaterialization); const result = yield client.queryRows('select * from primary_mat_changes'); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].txid, txid); assert.strictEqual(result[0].operation, 'insert'); assert.strictEqual(result[0].id, insertedId); })); it('Will compute a delete', () => go(function*() { const client = clientFn(); yield client.query( `INSERT INTO prim_changes(txid, operation, public, id, tert_id_part1, tert_id_part2) VALUES(${txid}, 'delete', true, '${deletedId}', 1, 2)`); yield applyDeletes(client, txid, tableModel.prim); yield computeDirty(client, txid, tableModel, testMaterialization); yield computeChanges(client, txid, tableModel, testMaterialization); const result = yield client.queryRows('select * from primary_mat_changes'); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].txid, txid); assert.strictEqual(result[0].operation, 'delete'); assert.strictEqual(result[0].id, deletedId); })); it('Will compute an update', () => go(function*() { const client = clientFn(); yield client.query( `INSERT INTO prim_changes(txid, operation, public, id, tert_id_part1, tert_id_part2, name) VALUES(${txid}, 'update', true, '${updatedId}', 1, 2, 'foo')`); yield applyUpdates(client, txid, tableModel.prim); yield computeDirty(client, txid, tableModel, testMaterialization); yield computeChanges(client, txid, tableModel, testMaterialization); const result = yield client.queryRows('select * from primary_mat_changes'); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].txid, txid); assert.strictEqual(result[0].operation, 'update'); assert.strictEqual(result[0].id, updatedId); assert.strictEqual(result[0].prim_name, 'foo'); })); }); }); }); import React, { useState } from 'react' import Persons from './components/Persons' import Filter from './components/Filter' import PersonForm from './components/PersonForm' const App = () => { const [persons, setPersons] = useState([ { name: '', number: '15-531232314' }, { name: 'Machine', number: '10-1010001001' }, { name: '', number: '040-123456' }, { name: '', number: '39-44-5323523' }, { name: '', number: '12-43-234345' }, { name: '', number: '39-23-6423122' }, ]) const [newName, setNewName] = useState('') //newName is for controlling the form input element const [newNumber, setNewNumber] = useState('') const [newSearch, setNewSearch] = useState('') const addPerson = event => { event.preventDefault() const personObject = { name: newName, number: newNumber, id: newName, } const found = persons.some(person => person.name === newName) console.log(found) if (found) window.alert(`${newName} is already added to phonebook`) else setPersons(persons.concat(personObject)) setNewName('') setNewNumber('') } const handleNameChange = event => setNewName(event.target.value) const handleNumberChange = event => setNewNumber(event.target.value) const handleSearch = event => setNewSearch(event.target.value) function filterByName(person) { return person.name.toLowerCase().indexOf(newSearch) !== -1 } return (

    Phonebook

    add a new

    Numbers

    ) } export default App module.exports = { fetchAllMembers: true, token: process.env.TOKEN, owners: JSON.parse(process.env.OWNERS), nodes: JSON.parse(process.env.LAVALINK_NODES), dbConfig: JSON.parse(process.env.FIREBASE_CONFIG) } src/components/Chat-summary-card/chat-summary-card.js import React, { Component } from 'react'; import './chat-summary-card.scss'; export default class ChatSummaryCard extends Component { render() { let unread; if (this.props.unread > 0) { unread = {this.props.unread} } return (
    { unread }

    {this.props.name}

    {this.props.latestMessage}

    {this.props.latestTime}
    ); } }0 cancelUnless( internal || (me && me.privileges.indexOf('edit_items') != -1), "unauthorized", 401 ) var req = ctx.body, icItemConfig = require(process.cwd()+'/public/ic-item-config.js') cancelUnless(req.item, 'missing item.', 400) cancelUnless(req.from, 'missing from language(s).', 400) cancelUnless(req.to, 'missing target language(s).', 400) if(typeof req.from == 'string') req.from = [req.from] if(typeof req.to == 'string') req.to = [req.to] if(typeof req.properties == 'string') req.properties = [req.properties] $addCallback() var properties_to_translate = req.properties && req.properties.length ? req.properties : icItemConfig.properties .filter( property_obj => property_obj.translatable) .map( property_obj => property_obj.name) if(properties_to_translate.length == 0){ $finishCallback() ctx.error('no translatable properties found') } function isValidFrom(str){ return str && !str.match(/^\s*Google Translat/i) //legacy && !str.match(/^\[[^\]]*:\]/i) } function isValidTo(str){ return !isValidFrom(str) } ctx.dpd.items.get({id:req.item}) .then( item => { return Promise.all( properties_to_translate .filter( property => !!item[property] ) .map( property => { console.log('property: ', property.name) var from_language = req.from.filter( lang => isValidFrom(item[property][lang]))[0] console.log('from_language: ', from_language) if(!from_language) return false return Promise.all( req.to .filter(lang => isValidTo(item[property][lang])) .map( to_lang => icUtils.getTranslation(from_language, to_lang, item[property][from_language]) .then( translation => { console.log(translation) if(translation.translator && translation.text ){ item[property][to_lang] = "["+translation.translator+":] "+translation.text } }, reason => { console.log(reason) item[property][to_lang] = "[translation failed:]" } ) ) ) }) ) .then( () => ctx.dpd.items.put(item)) .then( updated_item => setResult(updated_item) ) .catch( reason => ctx.done(reason)) }) .catch( e => { console.log(e); cancel('item not found', 404) }) .finally($finishCallback)import React from 'react'; import { Image, Container } from 'react-bootstrap'; function AboutPage () { return (

    Developer

    Lorem ipsum dolor sit amet, duo modus tantas ea, numquam appetere vis cu. Reque soleat accusata mea ea, cum enim civibus repudiandae eu. Electram sapientem mel cu, quem eruditi accusata at his, diam nibh facilisi ut sea. Vix graece eripuit oportere at, eam ei utamur iudicabit expetendis, te magna ullamcorper sed. Nec cu graece mandamus vituperata, ius at euismod tacimates, mel ut modo iriure epicurei. Id dicam iuvaret quaerendum qui. Nec etiam delenit petentium ea. His in populo corpora, ius omnis erant iisque eu. Vidit verterem vim cu. Pro eu harum mandamus. Erat veritus verterem ut cum.

    ); } export default AboutPage; packages/api/routes/health.js import cachePolicy from "./cacheProvider/cachePolicy"; import contextConnector from "./contextProvider"; import cacheConnector from "./cacheProvider"; import RouteNames from "./routeNames"; import config from "../infrastructure/config"; const pingHandler = (req, res, next, server) => { res.send({ links: [ server.hypermediaUrl.createSelfLink(req), server.hypermediaUrl.createUpLink(RouteNames.root) ], data: { name: config.appName, version: config.appVersion } }); return next(); }; export default function registerHealthRoutes(router) { router.get( {name: RouteNames.health, path: '/health'}, cacheConnector(cachePolicy.publicVeryShortCachePolicy), contextConnector(pingHandler)); }"use strict"; // 类似noop函数 function INTERNAL() {} function isFunction(func) { return typeof func === "function"; } function isObject(obj) { return typeof obj === "object"; } function isArray(arr) { return Object.prototype.toString.call(arr) === "[object Array]"; } // Promsie的状态 var PENDING = 0; var FULFILLED = 1; var REJECTED = 2; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError("resolver must be a function"); } this.state = PENDING; this.value = void 0; // 队列 this.queue = []; if (resolver !== INTERNAL) { safelyResolveThen(this, resolver); } } // then方法内默认返回一个新的promise Promise.prototype.then = function(onFulfilled, onRejected) { // 如果是值穿透的情况 if ( (!isFunction(onFulfilled) && this.state === FULFILLED) || (!isFunction(onRejected) && this.state === REJECTED) ) { return this; } // 创建一个新的promise, // 或者使用,var promise = new Promise(INTERNAL); var promise = new this.constructor(INTERNAL); if (this.state !== PENDING) { // 如Promse.resolve('234234').then(() => {}),或者reject的情况 // 会创造一个新的Promise并且this.value指向234234 var resolver = this.state === FULFILLED ? onFulfilled : onRejected; // 直接执行回调了 unwrap(promise, resolver, this.value); } else { // 正常进来都是PENDING状态,所以放到队列中,resolve或者reject掉之后返回 this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); } return promise; }; Promise.prototype.catch = function(onRejected) { return this.then(null, onRejected); }; Promise.resolve = function resolve(value) { // 当 Promise.resolve 参数是一个 promise 时,直接返回该值。 if (value instanceof this) { return value; } return doResolve(new this(INTERNAL), value); } Promise.reject = function reject(reason) { var promise = new this(INTERNAL); return doReject(promise, reason); } // 安全的执行 then 函数,捕获异常,resolve或者reject只执行一次,没错执行doResolve,错误执行doReject function safelyResolveThen(self, then) { var called = false; try { then( function(value) { if (called) { return; } called = true; doResolve(self, value); }, function(error) { if (called) { return; } called = true; doReject(self, error); } ); } catch (err) { if (called) { return; } called = true; doReject(self, err); } } // 具体成功的执行函数,返回一个promise function doResolve(self, value) { try { var then = getThen(value); // 如果返回的还是一个promise的话,则把这个promise.then执行完 if (then) { safelyResolveThen(self, then); } else { // 正常设置FULFILLED状态,然后进入.then方法中,这里把成功和失败的方法统一包装成了一个对象 self.state = FULFILLED; self.value = value; self.queue.forEach(function(queueItem) { queueItem.callFulfilled(value); }); } return self; } catch (err) { return doReject(self, err); } } function doReject(self, error) { // 有错误或者Reject掉的情况 self.state = REJECTED; self.value = error; self.queue.forEach(function(queueItem) { queueItem.callRejected(error); }); return self; } // 辅助函数,获取then函数的 function getThen(obj) { var then = obj && obj.then; if (obj && (isObject(obj) || isFunction(obj)) && isFunction(then)) { return function applyThen() { then.apply(obj, arguments); }; } } //执行异步操作的地方, 第一个参数是子 promise,第二个参数是父 promise 的 then 的回调(onFulfilled/onRejected),第三个参数是父 promise 的值(正常值/错误)。 function unwrap(promise, func, value) { // 执行异步操作 setTimeout(function() { var returnValue; try { // promise的then中的回调结合返回值 returnValue = func(value); } catch (error) { return doReject(promise, error); } if (returnValue === promise) { doReject( promise, new TypeError("Cannot resolve promise with itself") ); } else { doResolve(promise, returnValue); } }); } // then中onFulfilled,onRejected包装成了一个类对象 function QueueItem(promise, onFulfilled, onRejected) { this.promise = promise; // 为了兼容值穿透的情况,返回value this.callFulfilled = function(value) { doResolve(this.promise, value); }; this.callRejected = function(error) { doReject(this.promise, error); }; if (isFunction(onFulfilled)) { this.callFulfilled = function(value) { unwrap(this.promise, onFulfilled, value); }; } if (isFunction(onRejected)) { this.callRejected = function(error) { unwrap(this.promise, onRejected, error); }; } } module.exports = Promise; itisAliRH/galaxy export { userStore } from "./userStore"; export { default as User } from "./User"; export { syncUserToGalaxy } from "./syncUserToGalaxy"; export { userFlagsStore } from "./userFlagsStore"; 'use strict' const GenericDBService = require('../../genricDBService') const UserService = new GenericDBService("User") const ProgramService = new GenericDBService("Program") const ModuleService = new GenericDBService("Module") const ActivityService = new GenericDBService("Activity") const TaskService = new GenericDBService("Task") const HELPER = require('../../utils/helper') const APP_CONSTANTS = require('../../config/appConstants') const async = require('async') const ERROR = APP_CONSTANTS.STATUS_MSG.ERROR /** [ { program: { id: 1, title: 'Respective program title' }, module: { id: 1, title: "Everyone can play!", shortDescription: "Active play is important for everyone in the family: adults and…", status: 'Incomplete', goalStatus: true, } } ] */ const getFavouriteModules = function (userData, callback) { var fetchData = [] async.series([ function (cb) { var criteria = { _id: userData._id } UserService.getRecord(criteria, {}, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb(ERROR.INCORRECT_ACCESSTOKEN) if (data[0].profile.favouriteModules.length === 0) return callback() data[0].profile.favouriteModules.forEach((userFavItem) => { var tempFavourite = {} tempFavourite.program = { id: userFavItem.programId } const userProgramModuleData = data[0].profile.programsData .find((program) => userFavItem.programId === program.programId).modules .find((mod) => userFavItem.id === mod.moduleId) /** * TODO: Add goalStatus */ tempFavourite.module = { id: userFavItem.id, status: userProgramModuleData.status } fetchData.push(tempFavourite) }) cb() }) }, // Set program.title for each entry in fetchData function (cb) { var programIdsArr = [] fetchData.forEach((favouriteItem) => programIdsArr.push(favouriteItem.program.id)) var criteria = { id: { $in: programIdsArr} } var projection = '' ProgramService.getRecord(criteria, projection, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb("PROGRAMS NOT FOUND") // For each program found, append it's title to respective fetchData's program.title data.forEach((program) => { const foundIndex = fetchData.findIndex((userFavItem) => userFavItem.program.id === program.id) if (foundIndex === -1) return // stop processing this iteration fetchData[foundIndex].program.title = program.title }) cb() }) }, // Set module.title, shortDescription for each entry in fetchData function (cb) { var moduleIdsArr = [] fetchData.forEach((favouriteItem) => moduleIdsArr.push(favouriteItem.module.id)) var criteria = { id: { $in: moduleIdsArr } } var projection = '' ModuleService.getRecord(criteria, projection, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb("MODULES NOT FOUND") // For each module found, append it's title to respective fetchData's module.title, shortDescription data.forEach((mod) => { const foundIndex = fetchData.findIndex((userFavItem) => userFavItem.module.id === mod.id) if (foundIndex === -1) return // stop processing this iteration fetchData[foundIndex].module.title = mod.title fetchData[foundIndex].module.shortDescription = mod.shortDescription }) cb() }) }, ], function (err) { if (err) callback(err) else callback(null, { favouriteModules: HELPER.deleteUnnecessaryUserData(fetchData) }) } ) } // Mongo doc: https://docs.mongodb.com/manual/reference/operator/update/push/ function addToFav(criteria, arrayName, requiredFav, cb) { var updateStatement = {} const str = 'profile.' + arrayName updateStatement.$push = {} updateStatement.$push[str] = requiredFav UserService.updateRecord(criteria, updateStatement, {}, function (err, data) { if (err) return cb(err) cb(null, "FAVOURITE ADDED") }) } // Mongo doc: https://docs.mongodb.com/manual/reference/operator/update/pull/ function removeFromFav(criteria, arrayName, requiredFav, cb) { var updateStatement = {} const str = 'profile.' + arrayName updateStatement.$pull = {} updateStatement.$pull[str] = requiredFav UserService.updateRecord(criteria, updateStatement, {}, function (err, data) { if (err) return cb(err) cb(null, "FAVOURITE DELETED") }) } const toggleFavouriteModule = function (userData, request, callback) { /** * Read programId and moduleId from request data * If that favourite exists, remove it * Else check if the favourite IDs are existing in user model and add that favourite * * TODO: Maybe send the new list.. :D */ var fetchData = [] async.series([ function (cb) { var criteria = { _id: userData._id } UserService.getRecord(criteria, {}, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb(ERROR.INCORRECT_ACCESSTOKEN) var requiredFav = { id: request.params.id, programId: request.query.programId } // Check if the required favourite IDs are existing in user's programs data const requiredProgram = data[0].profile.programsData .find((program) => requiredFav.programId === program.programId) if (undefined === requiredProgram) return cb("PROGRAM NOT FOUND") const requiredModule = requiredProgram.modules .find((mod) => requiredFav.id === mod.moduleId) if (undefined === requiredModule) return cb("MODULE NOT FOUND") const arrayName = 'favouriteModules' if (data[0].profile.favouriteModules.length === 0) return addToFav(criteria, arrayName, requiredFav, (err, data) => { if (err) return cb(err) fetchData = data cb() }) // ADD TO FAVOURITES const favouriteExists = data[0].profile.favouriteModules.filter(function(userFavItem) { return userFavItem.programId === request.query.programId && userFavItem.id === request.params.id }).length > 0 if (!favouriteExists) return addToFav(criteria, arrayName, requiredFav, (err, data) => { if (err) return cb(err) fetchData = data cb() }) // ADD TO FAVOURITES else return removeFromFav(criteria, arrayName, requiredFav, (err, data) => { if (err) return cb(err) fetchData = data cb() }) // REMOVE FROM FAVOURITES }) } ], function (err) { if (err) callback(err) else callback(null, { message: HELPER.deleteUnnecessaryUserData(fetchData) }) } ) } const getFavouriteActivities = function (userData, callback) { var fetchData = [] async.series([ function (cb) { var criteria = { _id: userData._id } UserService.getRecord(criteria, {}, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb(ERROR.INCORRECT_ACCESSTOKEN) if (data[0].profile.favouriteActivities.length === 0) return callback() data[0].profile.favouriteActivities.forEach((userFavItem) => { var tempFavourite = {} tempFavourite.program = { id: userFavItem.programId } tempFavourite.module = { id: userFavItem.moduleId } const userProgramModuleActivityData = data[0].profile.programsData .find((program) => userFavItem.programId === program.programId).modules .find((mod) => userFavItem.moduleId === mod.moduleId).activities .find((activity) => userFavItem.id === activity.activityId) /** * TODO: Add goalStatus */ tempFavourite.activity = { id: userFavItem.id, status: userProgramModuleActivityData.status } fetchData.push(tempFavourite) }) cb() }) }, // Set module.title for each entry in fetchData function (cb) { var moduleIdsArr = [] fetchData.forEach((favouriteItem) => moduleIdsArr.push(favouriteItem.module.id)) var criteria = { id: { $in: moduleIdsArr } } var projection = '' ModuleService.getRecord(criteria, projection, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb("MODULES NOT FOUND") // For each module found, append it's title to respective fetchData's module.title data.forEach((mod) => { const foundIndex = fetchData.findIndex((userFavItem) => userFavItem.module.id === mod.id) if (foundIndex === -1) return // stop processing this iteration fetchData[foundIndex].module.title = mod.title }) cb() }) }, // Set activity.title, shortDescription for each entry in fetchData function (cb) { var activityIdsArr = [] fetchData.forEach((favouriteItem) => activityIdsArr.push(favouriteItem.activity.id)) var criteria = { id: { $in: activityIdsArr } } var projection = '' ActivityService.getRecord(criteria, projection, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb("MODULES NOT FOUND") // For each activity found, append it's title to respective fetchData's activity.title, shortDescription data.forEach((activity) => { const foundIndex = fetchData.findIndex((userFavItem) => userFavItem.activity.id === activity.id) if (foundIndex === -1) return // stop processing this iteration fetchData[foundIndex].activity.title = activity.title fetchData[foundIndex].activity.shortDescription = activity.shortDescription }) cb() }) }, ], function (err) { if (err) callback(err) else callback(null, { favouriteActivities: HELPER.deleteUnnecessaryUserData(fetchData) }) } ) } const toggleFavouriteActivity = function (userData, request, callback) { var fetchData = [] async.series([ function (cb) { var criteria = { _id: userData._id } UserService.getRecord(criteria, {}, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb(ERROR.INCORRECT_ACCESSTOKEN) var requiredFav = { id: request.params.id, moduleId: request.query.moduleId, programId: request.query.programId } // Check if the required favourite IDs are existing in user's programs data const requiredProgram = data[0].profile.programsData .find((program) => requiredFav.programId === program.programId) if (undefined === requiredProgram) return cb("PROGRAM NOT FOUND") const requiredModule = requiredProgram.modules .find((mod) => requiredFav.moduleId === mod.moduleId) if (undefined === requiredModule) return cb("MODULE NOT FOUND") const requiredActivity = requiredModule.activities .find((activity) => requiredFav.id === activity.activityId) if (undefined === requiredActivity) return cb("ACTIVITY NOT FOUND") const arrayName = 'favouriteActivities' if (data[0].profile.favouriteActivities.length === 0) return addToFav(criteria, arrayName, requiredFav, (err, data) => { if (err) return cb(err) fetchData = data cb() }) // ADD TO FAVOURITES const favouriteExists = data[0].profile.favouriteActivities.filter(function(userFavItem) { return userFavItem.programId === request.query.programId && userFavItem.moduleId === request.query.moduleId && userFavItem.id === request.params.id }).length > 0 if (!favouriteExists) return addToFav(criteria, arrayName, requiredFav, (err, data) => { if (err) return cb(err) fetchData = data cb() }) // ADD TO FAVOURITES else return removeFromFav(criteria, arrayName, requiredFav, (err, data) => { if (err) return cb(err) fetchData = data cb() }) // REMOVE FROM FAVOURITES }) } ], function (err) { if (err) callback(err) else callback(null, { message: HELPER.deleteUnnecessaryUserData(fetchData) }) } ) } const getFavouriteTasks = function (userData, callback) { var fetchData = [] async.series([ function (cb) { var criteria = { _id: userData._id } UserService.getRecord(criteria, {}, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb(ERROR.INCORRECT_ACCESSTOKEN) if (data[0].profile.favouriteTasks.length === 0) return callback() data[0].profile.favouriteTasks.forEach((userFavItem) => { var tempFavourite = {} tempFavourite.program = { id: userFavItem.programId } tempFavourite.module = { id: userFavItem.moduleId } const userProgramModuleTaskData = data[0].profile.programsData .find((program) => userFavItem.programId === program.programId).modules .find((mod) => userFavItem.moduleId === mod.moduleId).tasks .find((task) => userFavItem.id === task.taskId) /** * TODO: Add goalStatus */ tempFavourite.task = { id: userFavItem.id, status: userProgramModuleTaskData.status } fetchData.push(tempFavourite) }) cb() }) }, // Set module.title for each entry in fetchData function (cb) { var moduleIdsArr = [] fetchData.forEach((favouriteItem) => moduleIdsArr.push(favouriteItem.module.id)) var criteria = { id: { $in: moduleIdsArr } } var projection = '' ModuleService.getRecord(criteria, projection, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb("MODULES NOT FOUND") // For each module found, append it's title to respective fetchData's module.title data.forEach((mod) => { const foundIndex = fetchData.findIndex((userFavItem) => userFavItem.module.id === mod.id) if (foundIndex === -1) return // stop processing this iteration fetchData[foundIndex].module.title = mod.title }) cb() }) }, // Set task.title, shortDescription for each entry in fetchData function (cb) { var taskIdsArr = [] fetchData.forEach((favouriteItem) => taskIdsArr.push(favouriteItem.task.id)) var criteria = { id: { $in: taskIdsArr } } var projection = '' TaskService.getRecord(criteria, projection, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb("MODULES NOT FOUND") // For each activity found, append it's title to respective fetchData's task.title, shortDescription data.forEach((task) => { const foundIndex = fetchData.findIndex((userFavItem) => userFavItem.task.id === task.id) if (foundIndex === -1) return // stop processing this iteration fetchData[foundIndex].task.title = task.title fetchData[foundIndex].task.shortDescription = task.shortDescription }) cb() }) }, ], function (err) { if (err) callback(err) else callback(null, { favouriteTasks: HELPER.deleteUnnecessaryUserData(fetchData) }) } ) } const toggleFavouriteTask = function (userData, request, callback) { var fetchData = [] async.series([ function (cb) { var criteria = { _id: userData._id } UserService.getRecord(criteria, {}, {}, function (err, data) { if (err) return cb(err) if (0 === data.length) return cb(ERROR.INCORRECT_ACCESSTOKEN) var requiredFav = { id: request.params.id, moduleId: request.query.moduleId, programId: request.query.programId } // Check if the required favourite IDs are existing in user's programs data const requiredProgram = data[0].profile.programsData .find((program) => requiredFav.programId === program.programId) if (undefined === requiredProgram) return cb("PROGRAM NOT FOUND") const requiredModule = requiredProgram.modules .find((mod) => requiredFav.moduleId === mod.moduleId) if (undefined === requiredModule) return cb("MODULE NOT FOUND") const requiredTask = requiredModule.tasks .find((task) => requiredFav.id === task.taskId) if (undefined === requiredTask) return cb("ACTIVITY NOT FOUND") const arrayName = 'favouriteTasks' if (data[0].profile.favouriteTasks.length === 0) return addToFav(criteria, arrayName, requiredFav, (err, data) => { if (err) return cb(err) fetchData = data cb() }) // ADD TO FAVOURITES const favouriteExists = data[0].profile.favouriteTasks.filter(function(userFavItem) { return userFavItem.programId === request.query.programId && userFavItem.moduleId === request.query.moduleId && userFavItem.id === request.params.id }).length > 0 if (!favouriteExists) return addToFav(criteria, arrayName, requiredFav, (err, data) => { if (err) return cb(err) fetchData = data cb() }) // ADD TO FAVOURITES else return removeFromFav(criteria, arrayName, requiredFav, (err, data) => { if (err) return cb(err) fetchData = data cb() }) // REMOVE FROM FAVOURITES }) } ], function (err) { if (err) callback(err) else callback(null, { message: HELPER.deleteUnnecessaryUserData(fetchData) }) } ) } module.exports = { getFavouriteActivities: getFavouriteActivities, toggleFavouriteActivity: toggleFavouriteActivity, getFavouriteModules: getFavouriteModules, toggleFavouriteModule: toggleFavouriteModule, getFavouriteTasks: getFavouriteTasks, toggleFavouriteTask: toggleFavouriteTask } export default function getNeighbors(node, links) { return links.reduce( (neighbors, link) => { if (link.target.id === node.id) { neighbors.push(link.source.id) } else if (link.source.id === node.id) { neighbors.push(link.target.id) } return neighbors }, [node.id] ) } import express from 'express'; import authRouter from './auth'; import api from './api'; const router = express.Router(); router.use('/auth', authRouter); router.use('/api', api); export default router; seveibar/devception import { styled } from "@material-ui/core/styles" import FileItem from "../FileItem" import Box from "@material-ui/core/Box" import FolderIcon from "@material-ui/icons/Folder" const Container = styled("div")({}) export const DirectoryItem = ({ pathToDirectory, files }) => { return ( {pathToDirectory} {files.map((file, i) => ( ))} ) } export default DirectoryItem import css from 'styled-jsx/css'; export const buttonStyle = css` .buttonStyle { position: relative; width: 100%; height: 32px; background: rgb(250, 250, 250); border-top: 1px solid rgb(214, 214, 214); border-right: none; border-bottom: none; border-left: none; border-image: initial; font-size: 12px; cursor: pointer; color: rgb(117, 153, 255); outline: none; } .buttonStyle:hover { background: rgb(245, 245, 245); } .dark { background: rgb(33, 33, 33); border-top: 1px solid #313131; } .dark:hover { background: rgb(21, 21, 21); } `; jbx81-1337/binlexdocs/html/structSHA256__CTX.js var structSHA256__CTX = [ [ "bitlen", "structSHA256__CTX.html#a7971befc0fa37b07350552d3a949634a", null ], [ "data", "structSHA256__CTX.html#ac4cf981ce4100c3af150be3c98b2d03e", null ], [ "datalen", "structSHA256__CTX.html#acff27dfecde1d6e42f7c8474a3175529", null ], [ "state", "structSHA256__CTX.html#a09c4eef8a0dc02bc9860e2a02c3f2638", null ] ];csethanhcong/d3jssrc/charts/C9.DonutChart.js0 import Chart from './C9.Chart'; import Axis from './utils/C9.Axis'; import Title from './utils/C9.Title'; import Legend from './utils/C9.Legend'; import Table from './utils/C9.Table'; import Tooltip from './utils/C9.Tooltip'; import Helper from '../helper/C9.Helper'; import DataAdapter from '../helper/C9.DataAdapter'; export default class DonutChart extends Chart { constructor(options) { super(options); var self = this; var R = Math.min(self.width - self.margin.left - self.margin.right, self.height - self.margin.top - self.margin.bottom) / 2; self.config = { outerRadius: R, innerRadius: R > 80 ? R - 80 : R - 40, // showText: true // show/hide text on middle or each donut }; // self.updateConfig(config); } /*============================== = Getter = ==============================*/ get pie() { return this._pie; } get arc() { return this._arc; } get currentData() { return this._currentData; } /*===== End of Getter ======*/ /*============================== = Setter = ==============================*/ set pie(arg) { if (arg) { this._pie = arg; } } set arc(arg) { if (arg) { this._arc = arg; } } set currentData(arg) { if (arg) { this._currentData = arg; } } /*===== End of Setter ======*/ /*====================================== = Main Functions = ======================================*/ /** * Update Donut Chart Config */ updateConfig(config, callback) { super.updateConfig(config); var self = this; self.options = Helper.mergeDeep(config, self.options); self.chartType = 'donut'; var dataOption = self.dataOption; dataOption.colorRange = self.colorRange; var da = new DataAdapter(dataOption, self.chartType, null); da.getDataTarget(self.chartType, function(data) { self.dataTarget = data; if (Helper.isFunction(callback)) { callback.call(self, self.dataTarget); } }); } /** * Update Donut Chart Config */ updateDataConfig(dataCfg, callback) { var self = this; self.options = Helper.mergeDeep(self.options, dataCfg); self.chartType = 'donut'; var dataOption = self.dataOption; dataOption.colorRange = self.colorRange; var da = new DataAdapter(dataOption, self.chartType, null); da.getDataTarget(self.chartType, function(data) { self.dataTarget = data; if (Helper.isFunction(callback)) { callback.call(self, self.dataTarget); } }); } /** * Update Donut Chart based on new data * @param {[type]} data [description] */ update(data) { var self = this; var width = self.width - self.margin.left - self.margin.right, height = self.height - self.margin.top - self.margin.bottom, color = self.colorRange; self.arc = d3.svg.arc() .outerRadius(self.options.outerRadius) .innerRadius(self.options.innerRadius); //we can sort data here self.pie = d3.layout.pie() .sort(null) .value(function(d) { return d.value; }); self.body.selectAll(".c9-chart-donut.c9-custom-arc-container").data([]).exit().remove(); //draw chart var arcs = self.body .append('g') .attr('class', 'c9-chart-donut c9-custom-arc-container') .attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')') .selectAll('.c9-chart-donut.c9-custom-arc') .data(self.pie(data)).enter() .append('g') .attr('class', 'c9-chart-donut c9-custom-arc'); // Append main path contains donut // TODO: add a unique class to allow Legend could find selected donut/pie arcs.append('path') .attr('class', 'c9-chart-donut c9-custom-path') .attr('data-ref', function(d) { return d.data['data-ref']; }) .attr('d', self.arc) .attr('fill', function(d, i) { return color(i); }) .attr('stroke', '#ffffff') .each(function(d) { self.currentData = d; }); // Current data used for calculate interpolation // between current arc vs disabled arc // Append middle text display name // if (self.showText) { // arcs.append('text') // .attr('class', 'c9-chart-donut c9-custom-text') // .attr('transform', function(d) { return 'translate(' + self.arc.centroid(d) + ')'; }) // .attr('dy', '.35em') // .attr('text-anchor', 'middle') // .text(function(d) { return d.data.name; }); // } self.updateInteraction(); } /** * Select all path as type PATH in Donut Chart via its CLASS */ selectAllPath() { var self = this; return self.body // .selectAll('g') .selectAll('path.c9-chart-donut.c9-custom-path'); } /** * Update Interaction: Hover * @return {} */ updateInteraction() { var self = this, selector= self.selectAllPath(), width = self.width - self.margin.left - self.margin.right, height = self.height - self.margin.top - self.margin.bottom, color = self.colorRange, chartInnerBefore = self.options.innerRadius, chartOuterBefore = self.options.outerRadius, chartInnerAfter = self.options.innerRadius, chartOuterAfter = self.options.outerRadius * 1.2; var hoverOptions = self.hover.options, hoverEnable = self.hover.enable, onMouseOverCallback = hoverOptions.onMouseOver.callback, onMouseOutCallback = hoverOptions.onMouseOut.callback, onClickCallback = self.click.callback; var tooltip = new Tooltip(self.options.tooltip); // Main Event Dispatch for paths in donut chart self._eventFactory = { 'click': function(d, i) { if (Helper.isFunction(onClickCallback)) { onClickCallback.call(this, d); } }, 'mouseover': function(d, i) { if (!hoverEnable) return; if (Helper.isFunction(onMouseOverCallback)) { onMouseOverCallback.call(this, d); } var selector = d3.select(this); selector.transition() .attr('d', d3.svg.arc() .innerRadius(chartInnerAfter) .outerRadius(chartOuterAfter) ); // For legend if (self.options.legend.show) self.legend.item.each(function() { if (d3.select(this).attr('data-ref') !== d.data['data-ref'] && d3.select(this).attr('data-enable') == 'true') { d3.select(this).attr('opacity', '0.3'); } }); // For Table if (self.options.table.show) { var tr = d3.selectAll('.c9-table-container>.c9-table-body tr'); tr.filter(function(i) { return i['data-ref'] != d.data['data-ref'] }).selectAll('td').style('opacity', '0.5'); var selectedItem = tr.filter(function(i) { return i['data-ref'] == d.data['data-ref'] }); //set its style and scroll to its pos selectedItem.selectAll('td').style('opacity', '1'); Helper.scroll(d3.select('.c9-table-container')[0][0], selectedItem[0][0].offsetTop, 200); } // For Chart self.selectAllPath().each(function(){ if (d3.select(this).attr('data-ref') !== d.data['data-ref']) { d3.select(this).attr('opacity', '0.3'); } }); // For Tooltip tooltip.draw(d, self, 'mouseover'); }, 'mouseout': function(d, i) { if (!hoverEnable) return; if (Helper.isFunction(onMouseOutCallback)) { onMouseOutCallback.call(this, d); } var selector = d3.select(this); selector.transition() .duration(500) .ease('bounce') .attr('d', d3.svg.arc() .innerRadius(chartInnerBefore) .outerRadius(chartOuterBefore) ); // For legend if (self.options.legend.show) self.legend.item.each(function() { if (d3.select(this).attr('data-ref') !== d.data['data-ref'] && d3.select(this).attr('data-enable') == 'true') { d3.select(this).attr('opacity', '1.0'); } }); // For Table if (self.options.table.show) d3.selectAll('.c9-table-container>.c9-table-body tr').selectAll('td').style('opacity', ''); // For Chart self.selectAllPath().each(function(){ if (d3.select(this).attr('data-ref') !== d.data['data-ref']) { d3.select(this).attr('opacity', '1.0'); } }); // For Tooltip tooltip.draw(d, self, 'mouseout'); } }; selector.on(self._eventFactory); } /*===== End of Main Functions ======*/ /*======================================== = User's Functions = ========================================*/ /** * Custom Event Listener * @param {[type]} eventType [description] * @param {Function} callback [description] * @return {[type]} [description] */ on(eventType, callback) { super.on(eventType, callback); var self = this; var selector = self.selectAllPath(); // Update Event Factory let eventFactory = { 'click.event': function(d) { if (Helper.isFunction(callback)) { callback.call(this, d); } }, 'mouseover.event': function(d) { if (Helper.isFunction(callback)) { callback.call(this, d); } }, 'mouseout.event': function(d) { if (Helper.isFunction(callback)) { callback.call(this, d); } } } let eventName = eventType + '.event'; selector.on(eventName, eventFactory[eventName]); } /** * Main draw function of Donut Chart */ draw() { super.draw(); var self = this; self.updateConfig(self.config, function(data) { var title = new Title(self.options.title, self); var legend = new Legend(self.options.legend, self, self.dataTarget); var table = new Table(self.options.table, self, self.dataTarget); self.title = title; self.legend = legend; self.table = table; // Draw title self.title.draw(); // Update interaction of this own chart self.update(self.dataTarget); self.updateInteraction(); self.legend = legend; self.table = table; // Draw legend self.legend.draw(); self.legend.updateInteractionForDonutPieChart(self, self.selectAllPath(), self.pie, self.currentData, self.arc); // Draw table self.table.draw(); self.table.updateInteractionForDonutPieChart(self); }); } /** * Set option via stand-alone function * @param {[type]} key [description] * @param {[type]} value [description] */ setOption(key, value) { super.setOption(key, value); var self = this; Helper.set(key, value, self.options); self.updateConfig(self.options); } /** * Update chart based on new data with optional dataConfig * @param {[type]} data [description] * @param {[type]} dataConfig [description] */ updateData(newData, newDataConfig) { var self = this; var newCfg = {}; if (!Helper.isEmpty(newDataConfig)) { newCfg.data = { plain: newData, keys: newDataConfig, }; } else { newCfg.data = { plain: newData, }; } self.updateDataConfig(newCfg, function(data) { // Update Chart self.update(data); // Update Legend self.legend.update(data); self.legend.updateInteractionForDonutPieChart(self, self.selectAllPath(), self.pie, self.currentData, self.arc); // Update Table self.table.update(data); self.table.updateInteractionForDonutPieChart(self); }); } /*===== End of User's Functions ======*/ } earthtone/tiny-curry /** * Curry a function * * @func * @param {Function} fn * @param {Number} arity - number of arguments * @return {Function} * */ export function curry (fn, arity = fn.length) { return function _curry (...args) { if (args.length < arity) { return _curry.bind(null, ...args) } return fn(...args) } } import {List, Map, fromJS} from 'immutable' import {expect} from 'chai' import {setEntries, next, vote} from '../src/core' describe('application logic', () => { describe('setEntries', () => { it('adds the entries to the state', () => { const state = Map(); const entries = List.of('Trainspotting', '28 Days Later'); const nextState = setEntries(state, entries) expect(nextState).to.equal(Map({ entries: List.of('Trainspotting', '28 Days Later') })) }) //end add entries it('converts to immutable', () => { const state = Map() const entries = ['Trainspotting', '28 Days Later'] const nextState = setEntries(state, entries) expect(nextState).to.equal(Map({ entries: List.of('Trainspotting', '28 Days Later') })) }) // end converts }) //end set entries describe('next', () => { it('takes the next two entries for a vote', () => { const state = Map({ entries: List.of('Trainspotting', '28 Days Later', 'Sunshine') }) const nextState = next(state) expect(nextState).to.equal(Map({ vote: Map({ pair: List.of('Trainspotting', '28 Days Later') }), entries: List.of('Sunshine') })) }) it('puts the winner of a current vote back into entries', () => { const state = Map({ vote: Map({ pair: List.of('Trainspotting', '28 Days Later'), tally: Map({ 'Trainspotting': 4, '28 Days Later': 2 }) }), entries: List.of('Sunshine', 'Millions', '127 Hours') }) const nextState = next(state) expect(nextState).to.equal(Map({ vote: Map({ pair: List.of('Sunshine', 'Millions'), }), entries: List.of('127 Hours', 'Trainspotting') })) }) it('puts the tied pair of a current vote back into entries', () => { const state = Map({ vote: Map({ pair: List.of('Trainspotting', '28 Days Later'), tally: Map({ 'Trainspotting': 4, '28 Days Later': 4 }) }), entries: List.of('Sunshine', 'Millions', '127 Hours') }) const nextState = next(state) expect(nextState).to.equal(Map({ vote: Map({ pair: List.of('Sunshine', 'Millions'), }), entries: List.of('127 Hours', 'Trainspotting', '28 Days Later') })) }) it('marks winner when just one entry left', () => { const state = Map({ vote: Map({ pair: List.of('Trainspotting', '28 Days Later'), tally: Map({ 'Trainspotting': 4, '28 Days Later': 2 }) }), entries: List() }) const nextState = next(state) expect(nextState).to.equal(Map({ winner: 'Trainspotting' })) }) }) //end describe next describe('vote', () => { it('creates a tally for the voted entry', () => { const state = Map({ vote: Map({pair: List.of('Trainspotting', '28 Days Later')}), entries: List() }) const nextState = vote(state, 'Trainspotting') expect(nextState).to.equal(Map({ vote: Map({ pair: List.of('Trainspotting', '28 Days Later'), tally: Map({'Trainspotting': 1}) }), entries: List() })) }) it('increments a tally for an existing entry', () => { const state = Map({ vote: Map({ pair: List.of('Trainspotting', '28 Days Later'), tally: Map({ 'Trainspotting': 3, '28 Days Later': 2 }) }), entries: List() }) const nextState = vote(state, 'Trainspotting') expect(nextState).to.equal(Map({ vote: Map({ pair: List.of('Trainspotting', '28 Days Later'), tally: Map({ 'Trainspotting': 4, '28 Days Later': 2 }) }), entries: List() })) }) }) //end describe vote }) //end application logic import React, { Component } from 'react' import PropTypes from 'prop-types' import CSSModules from 'react-css-modules' import style from './forget.less' import { List, InputItem, Toast, NavBar, Icon } from 'antd-mobile'; import { createForm } from 'rc-form'; @CSSModules(style, { handleNotFoundStyleName: 'ignore' }) class forgetPsdComponent extends Component { constructor(props) { super(props) this.state = { phoneNumber: '', //手机号码 hasPhoneError: false, messageCode: '', //验证码 hasCodeError: false, loginPsd: '', //第一遍密码 hasPsdError: false, confirmPsd: '', //第二遍密码 hasConfirmError: false, } } //手机号相关 onErrorClickPhone = () => { if (this.state.hasPhoneError) { Toast.info('请输入11位手机号'); } } onChangePhone = (value) => { if (value.replace(/\s/g, '').length < 11) { this.setState({ hasPhoneError: true, }); } else { this.setState({ hasPhoneError: false, }); } this.setState({ phoneNumber: value }); } // 验证码相关 onErrorClickCode = () => { if (this.state.hasCodeError) { Toast.info('请正确填写验证码!'); } } onChangeCode = (value) => { if (value.replace(/\s/g, '').length < 4) { this.setState({ hasCodeError: true, }); } else { this.setState({ hasCodeError: false, }); } this.setState({ messageCode: value }); } // 首次密码相关 onErrorClickPsd = () => { if (this.state.hasPsdError) { Toast.info('密码必须由6~18个字母和数字组成,请重新填写!'); } } onChangePsd = (value) => { let regExp = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$/; value = value.replace(/\s/g, ''); if (value.length < 6 || value.length > 18) { this.setState({ hasPsdError: true, }); } else if (!regExp.test(value)) { this.setState({ hasPsdError: true, }); } else { this.setState({ hasPsdError: false, }); } this.setState({ loginPsd: value }); } //确认密码相关 onErrorClickConfirm = () => { if (this.state.hasConfirmError) { Toast.info('确认密码请和密码一致'); } } onChangeConfirm = (value) => { if (value !== this.state.loginPsd) { this.setState({ hasConfirmError: true, }); } else { this.setState({ hasConfirmError: false, }); } this.setState({ confirmPsd: value }); } //获取验证码 getCode = () => { if (this.state.hasPhoneError || this.state.phoneNumber.length == 0){ Toast.info('请正确填写注册手机号码'); return false } this.props.getCode({ phone: this.state.phoneNumber.replace(/\s/g, '') }) } //注册 reset = () => { if (this.state.hasPhoneError || this.state.phoneNumber.length == 0){ Toast.info('请正确填写注册手机号码'); return false } if(this.state.hasCodeError || this.state.messageCode.length == 0){ Toast.info('请正确填写验证码!'); return false } if(this.state.hasPsdError || this.state.loginPsd.length == 0){ Toast.info('请正确填写登录密码!'); return false } if(this.state.hasConfirmError || this.state.confirmPsd.length == 0){ Toast.info('请正确确认登录密码!'); return false } this.props.resetPsd({ Phone: this.state.phoneNumber.replace(/\s/g, ''), SmsCode: this.state.messageCode, Password: this.state.loginPsd, ConfirmPassword: this.state.confirmPsd },()=>{ this.props.goToBack() }) } render() { const { getFieldProps } = this.props.form; return (
    } onLeftClick={() => this.props.goToBack()} >忘记密码
    手机号码 验证码 获取验证码
    密码 确认密码
    确认重置
    ) } } forgetPsdComponent.propTypes = { phoneNumber: PropTypes.string, messageCode: PropTypes.string, loginPsd: PropTypes.string, confirmPsd: PropTypes.string } const forgetPsdComponentWrapper = createForm()(forgetPsdComponent); export default forgetPsdComponentWrapperexport const ACCESS_TOKEN = 'ACCESS_TOKEN'; export const REFRESH_TOKEN = 'REFRESH_TOKEN'; zoho/zohocrm-typescript-sdk-2.0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.XMLConverter = exports.MasterModel = void 0; const converter_1 = require("./converter"); class XMLConverter extends converter_1.Converter { getResponse(response, pack) { throw new Error("Method not implemented."); } formRequest(requestInstance, pack, instanceNumber, classMemberDetail) { throw new Error("Method not implemented."); } getWrappedResponse(response, pack) { throw new Error("Method not implemented."); } appendToRequest(requestBase) { throw new Error("Method not implemented."); } } exports.MasterModel = XMLConverter; exports.XMLConverter = XMLConverter; //# sourceMappingURL=xml_converter.js.map0 // load environment properties from a .env file for local development require('dotenv').load({ silent: true }); const app = require('./app.js'); const port = process.env.PORT || 3000; app.listen(port); console.log('listening at:', port); // eslint-disable-line juanfelipe82193/opensap /*! * SAP UI development toolkit for HTML5 (SAPUI5) (c) Copyright 2009-2015 SAP SE. All rights reserved */ // Provides the Design Time Metadata for the sap.gantt.GanttChart control sap.ui.define([], function () { "use strict"; return { aggregations: { relationships: { ignore: true } } }; }, /* bExport= */ false); var Bookshelf = null; module.exports = function (config) { "use strict"; if (Bookshelf) { return Bookshelf; } var knex = require('knex')({ client: 'mysql', connection: config.connection }); Bookshelf = require('bookshelf')(knex); /* * This solves the circular module dependency problem created by Bookshelf models * in a previous commit #38d98bb4c33e91b636a3538bd546ebe7f5077328 **/ Bookshelf.plugin('registry'); return Bookshelf; }; inmadria/cascade-server (function() { var app = angular.module('cascade'); app.directive('eventTags', function() { return { restrict: 'E', templateUrl: '/app/common/event-tags/event-tags.html', scope: { mappedEvents: '=', labels: '&' }, controller: function($scope) { $scope.labels = { process:'default', flow:'default', registry: 'default', user_session:'default', file: 'default', thread: 'default' }; } } }); })();import { ReduceStore } from 'flux/utils'; import AppDispatcher from '../../AppDispatcher'; import ActionTypes from '../actions/ActionTypes'; class SpeedtestStore extends ReduceStore { constructor() { super(AppDispatcher); } getInitialState() { return { results: [], currentDatacenter: {}, isRunning: false }; } reduce(state, action) { const newState = JSON.parse(JSON.stringify(state)); switch (action.type) { case ActionTypes.STARTED: newState.isRunning = true; return newState; case ActionTypes.STOPPED: newState.isRunning = false; return newState; case ActionTypes.CHANGED_TEST: newState.currentDatacenter = action.value; return newState; case ActionTypes.CHANGED_RESULTS: newState.results = action.value; return newState; default: return state; } } } export default new SpeedtestStore(); Gsodipo/Assignment2 function calculateTax() { // variable declaration const shippingCost = 3.00; let tax = 0; let subTotal = 0; let total = 0; // Get info from form using VALUE attribute let quantity = document.getElementById("quantity").value; let price = document.getElementById("choice").value; // Initial Calculations subTotal = quantity * price; tax = subTotal * shippingCost; total = subTotal + shippingCost; // Round to two decimal places total = total.toFixed(2); // Move data back to Form document.getElementById("subtotal").innerHTML = "Subtotal = " + subTotal; document.getElementById("tax").innerHTML = "Shipping Cost = " + shippingCost + " (@€3.00)"; document.getElementById("total").innerHTML = "Total = " + total; }/** * * @authors () * @date 2015-10-19 18:32:08 * @version $Id$ */ 'use strict'; var React = require('react-native'); var { StyleSheet, Image, } = React; var styles = StyleSheet.create({ container: { marginBottom:115, }, //slider row:{ flexDirection:'row', }, wrapper: { height:125, }, flex1:{ flex:1, }, center:{ alignItems:'center', justifyContent: 'center', }, slide: { height:125, resizeMode: Image.resizeMode.stretch, }, adv: { height:145, resizeMode: Image.resizeMode.stretch, }, hotLine:{ height:1, backgroundColor:'#333333', }, hottitle:{ fontSize: 16, textAlign: 'center', }, container_bqservice:{ padding:10, }, inputRow:{ flexDirection:'row', alignItems:'center', justifyContent: 'center', marginBottom:10, }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, itemRow:{ flexDirection:'row', marginBottom:2, }, }); module.exports = styles; must-be-perfect/MIM0 import Element from './Element'; const mathX = (cx, radius) => angle => cx + (Math.cos(angle) * radius); const mathY = (cy, radius) => angle => cy + (Math.sin(angle) * radius); export default class Path extends Element { el = document.createElementNS('http://www.w3.org/2000/svg', 'path'); setProps(props) { Object.assign(this.props, props); // this.render(); } bezierLine = (fromX, fromY, toX, toY) => [fromX, fromY, fromX, fromY, toX, toY, toX, toY]; roundBezierAngleStepCurve = (radius, sides, cx, cy, fromAngle, toAngle) => { const bezierRound = (4 / 3) * Math.tan(Math.PI / (2 * sides)); const bezierRoundAngle = Math.tanh((bezierRound * radius) / radius); const bezierPointRadius = Math.sqrt(Math.pow(radius, 2) + Math.pow(radius * bezierRound, 2)); const getX = mathX(cx, radius); const getY = mathY(cy, radius); const fromVariableGetX = mathX(cx, bezierPointRadius); const fromVariableGetY = mathY(cy, bezierPointRadius); const fromX = getX(fromAngle); const fromY = getY(fromAngle); const toX = getX(toAngle); const toY = getY(toAngle); const fromVariableX = fromVariableGetX(fromAngle + bezierRoundAngle); const fromVariableY = fromVariableGetY(fromAngle + bezierRoundAngle); const toVariableX = fromVariableGetX(toAngle - bezierRoundAngle); const toVariableY = fromVariableGetY(toAngle - bezierRoundAngle); return [fromX, fromY, fromVariableX, fromVariableY, toVariableX, toVariableY, toX, toY]; } bezierStepCircleSetup = (defaultRadius, defaultCx, defaultCy, defaultSides, startAngle) => ( step, radius = defaultRadius, sides = defaultSides, cx = defaultCx, cy = defaultCy, optionalFromAngle, optionalFoAngle, ) => { const stepAngle = (2 * Math.PI) / sides; const fromAngle = optionalFromAngle || startAngle + (stepAngle * step); const toAngle = optionalFoAngle || fromAngle + stepAngle; return this.roundBezierAngleStepCurve(radius, sides, cx, cy, fromAngle, toAngle); }; } // http://jsfiddle.net/AbdiasSoftware/8MYyg/ LWD8/vue-vue-ElementUI2/src/store/index.js import Vue from 'vue'; import Vuex from 'vuex'; import aside from './modules/aside'; // 侧边栏模块 Vue.use(Vuex); export default new Vuex.Store({ strict: true, modules: { aside } }); import React from 'react' import { Button } from 'semantic-ui-react' import { Link } from '../../../routes' export default (params) => ( ) src/errors/MessageParsingBlinkError.js 'use strict'; const BlinkError = require('./BlinkError'); class MessageParsingBlinkError extends BlinkError { constructor(errorMessage, payload) { super(errorMessage); this.badPayload = `${payload}`.replace(/\n/g, '\n'); } } module.exports = MessageParsingBlinkError; 0 rock.namespace('rock.game.graphics.engine.renderer.webgl'); /** * Renderer for {@link rock.game.graphics.model.PhongTextureModel} with {@link rock.game.graphics.scene.DirectionalLighting} * * @param {rock.graphics.engine.webgl.WebGLContext} glContext * the WebGL context * * @constructor * @extends rock.game.graphics.engine.renderer.webgl.ModelRenderer * * @author */ rock.game.graphics.engine.renderer.webgl.DirectionalLightingPhongTextureMaterialModelRenderer = function (glContext) { var lightingType= rock.game.constants.DIRECTIONAL_LIGHTING_TYPE; var modelType = rock.game.constants.PHONG_TEXTURE_MODEL_TYPE; var gl = glContext.getHTMLContext(); var drawingMode = gl.TRIANGLES; var vertexShaderSrc = rock.game.graphics.engine.renderer.webgl.GLSL.TEXTURE_NORMAL_VERTEX_SHADER; var fragmentShaderSrc = rock.game.graphics.engine.renderer.webgl.DirectionalLightingPhongTextureMaterialModelRenderer.fragmentShaderSrc; var maxLights = rock.game.graphics.engine.renderer.webgl.DirectionalLightingPhongTextureMaterialModelRenderer.MAX_LIGHTS; var lightingSetter = new rock.game.graphics.engine.renderer.webgl.programsetter.setter.lighting.DirectionalLightingSetter(glContext, maxLights); var modelSetter = new rock.game.graphics.engine.renderer.webgl.programsetter.setter.model.PhongTextureModelSetter(glContext); var superParams = [lightingType, modelType, glContext, drawingMode, vertexShaderSrc, fragmentShaderSrc, lightingSetter, modelSetter]; rock.super_(this, superParams); }; rock.extends_(rock.game.graphics.engine.renderer.webgl.DirectionalLightingPhongTextureMaterialModelRenderer, rock.game.graphics.engine.renderer.webgl.ModelRenderer); rock.game.graphics.engine.renderer.webgl.DirectionalLightingPhongTextureMaterialModelRenderer.MAX_LIGHTS = 10; rock.game.graphics.engine.renderer.webgl.DirectionalLightingPhongTextureMaterialModelRenderer.fragmentShaderSrc = '' + rock.game.graphics.engine.renderer.webgl.GLSL_PRECISION.ROCK_PRECISION + ' #define MAX_LIGHTS ' + rock.game.graphics.engine.renderer.webgl.DirectionalLightingPhongTextureMaterialModelRenderer.MAX_LIGHTS + ' \n' + rock.game.graphics.engine.renderer.webgl.GLSL.STRUCT_MATERIAL + rock.game.graphics.engine.renderer.webgl.GLSL.STRUCT_LIGHT + rock.game.graphics.engine.renderer.webgl.GLSL.FUNCTION_CALCULATE_DIRECTIONAL_LIGHT_COLOR + ' uniform Light u_directionalLights[MAX_LIGHTS]; \n' + ' uniform int u_directionalLightsCount; \n' + ' uniform Material u_material; \n' + ' uniform sampler2D u_textureAmbient; \n' + ' uniform sampler2D u_textureDiffuse; \n' + ' uniform sampler2D u_textureSpecular; \n' + ' varying vec4 v_modelViewVertex; \n' + ' varying vec3 v_normal; \n' + ' varying vec2 v_texCoord; \n' + ' void main() { \n' + ' vec3 normal = normalize(v_normal); \n' + ' vec3 viewDirection = normalize(-v_modelViewVertex.xyz); \n' + ' vec3 lightColor = vec3(0); \n' + ' Material textureMaterial; \n' + ' textureMaterial.ambient = u_material.ambient * texture2D(u_textureAmbient, v_texCoord).rgb; \n' + ' textureMaterial.diffuse = u_material.diffuse * texture2D(u_textureDiffuse, v_texCoord).rgb; \n' + ' textureMaterial.specular = u_material.specular * texture2D(u_textureSpecular, v_texCoord).rgb; \n' + ' textureMaterial.shininess = u_material.shininess; \n' + ' for (int i = 0; i < MAX_LIGHTS; i++) { \n' + ' if (i < u_directionalLightsCount) { \n' + ' lightColor += calculateDirectionalLightColor(u_directionalLights[i], textureMaterial, normal, viewDirection); \n' + ' } \n' + ' } \n' + ' gl_FragColor = vec4(lightColor, u_material.alpha); \n' + ' } \n'; const Engine = Matter.Engine; const Render = Matter.Render; const World = Matter.World; const Bodies = Matter.Bodies; const Constraint = Matter.Constraint; const Body = Matter.Body; const Composites = Matter.Composites; const Composite = Matter.Composite; var zombieleft,zombieright,bgImg; var ground,wall1,wall2,bridge,joinPoint1,joinPoint2,link,stones; function preload(){ zombieleft = loadAnimation('./assets/zombies/zombie1.png.png','./assets/zombies/zombie2.png.png','./assets/zombies/zombie3.png.png','./assets/zombies/zombie4.png.png','./assets/zombies/zombie5.png.png','./assets/zombies/zombie6.png.png','./assets/zombies/zombie7.png.png','./assets/zombies/zombie8.png.png','./assets/zombies/zombie9.png.png','./assets/zombies/zombie10.png.png','./assets/zombies/zombie11.png.png','./assets/zombies/zombie12.png.png'); bgImg = loadImage("./assets/background.png"); } function setup() { rectMode(CENTER); ellipseMode(CENTER); createCanvas(windowWidth, windowHeight); engine = Engine.create(); world = engine.world; frameRate(80); zombie = createSprite(width/2,height-110); zombie.addAnimation("left",zombieleft); zombie.scale = 0.3; zombie.velocityX = 10; breakButton = createButton(""); breakButton.position(width-200,height/2 - 50); breakButton.class("breakbutton"); breakButton.mousePressed(handleButtonPress); ground = new Base(width/2,height,width,20); wall1 = new Base(0,height/2,20,height); wall2 = new Base(width,height/2,20,height); bridge = new Bridge(21,{x: 10, y: height-450}); //Matter.Composite.add(bridge.body,joinPoint1); joinPoint1 = new Base(25,height-450,200,200); joinPoint2 = new Base(width-25,height-450,200,200); link = new Link(bridge,joinPoint2); stones = []; for (var i = 0; i < 8; i++){ var x = random(width/2 - 180, width/2 + 180); var y = random(0, 50); var stone = new Stone(x,y,80,80); stones.push(stone); } } function draw() { background(bgImg); Engine.update(engine); bridge.show(); for (var k = 0; k < stones.length; k++){ stones[k].show(); } if (zombie.position.x < 230){ zombie.velocityX = 10; zombie.mirrorX(1); } if (zombie.position.x > width-230){ zombie.velocityX = -10; zombie.mirrorX(-1); } drawSprites(); } function handleButtonPress(){ link.dettach(); setTimeout(() => { bridge.break(); },1500); }dbmi-pitt/CQL-Testing-Frameworkpddi-rule-tests/citalopram-qt/node_modules/cql-execution/lib/fhir/imagingobjectselection.js // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, ImagingObjectSelection, InstanceComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, SeriesComponent, StudyComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class InstanceComponent @exports InstanceComponent as InstanceComponent */ InstanceComponent = (function(superClass) { extend(InstanceComponent, superClass); function InstanceComponent(json) { this.json = json; InstanceComponent.__super__.constructor.call(this, this.json); } /** SOP class uid of the selected instance. @returns {oid} */ InstanceComponent.prototype.sopClass = function() { if (this.json['sopClass']) { return new oid(this.json['sopClass']); } }; /** SOP Instance uid of the selected instance. @returns {oid} */ InstanceComponent.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** The DICOM Application Entity Title where the DICOM SOP instance can be retrieved. @returns {Array} an array of {@link String} objects */ InstanceComponent.prototype.retrieveAETitle = function() { return this.json['retrieveAETitle']; }; /** WADO-RS URL to retrieve the DICOM SOP Instance. @returns {Array} an array of {@link String} objects */ InstanceComponent.prototype.retrieveUrl = function() { return this.json['retrieveUrl']; }; return InstanceComponent; })(BackboneElement); /** Embedded class @class SeriesComponent @exports SeriesComponent as SeriesComponent */ SeriesComponent = (function(superClass) { extend(SeriesComponent, superClass); function SeriesComponent(json) { this.json = json; SeriesComponent.__super__.constructor.call(this, this.json); } /** Series instance uid of the SOP instances in the selection. @returns {oid} */ SeriesComponent.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** The DICOM Application Entity Title where the series can be retrieved. Note that this AE Title is provided to retrieve all SOP instances of the series not only those in the selection. @returns {Array} an array of {@link String} objects */ SeriesComponent.prototype.retrieveAETitle = function() { return this.json['retrieveAETitle']; }; /** WADO-RS URL to retrieve the series Note that this URL retrieves all SOP instances of the series not only those in the selection. @returns {Array} an array of {@link String} objects */ SeriesComponent.prototype.retrieveUrl = function() { return this.json['retrieveUrl']; }; /** Identity and locating information of the selected DICOM SOP instances. @returns {Array} an array of {@link InstanceComponent} objects */ SeriesComponent.prototype.instance = function() { var i, item, len, ref, results; if (this.json['instance']) { ref = this.json['instance']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new InstanceComponent(item)); } return results; } }; return SeriesComponent; })(BackboneElement); /** Embedded class @class StudyComponent @exports StudyComponent as StudyComponent */ StudyComponent = (function(superClass) { extend(StudyComponent, superClass); function StudyComponent(json) { this.json = json; StudyComponent.__super__.constructor.call(this, this.json); } /** Study instance uid of the SOP instances in the selection. @returns {oid} */ StudyComponent.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** The DICOM Application Entity Title where the study can be retrieved. Note that this AE Title is provided to retrieve all SOP instances of the study, not only those in the selection. @returns {Array} an array of {@link String} objects */ StudyComponent.prototype.retrieveAETitle = function() { return this.json['retrieveAETitle']; }; /** WADO-RS URL to retrieve the study. Note that this URL retrieves all SOP instances of the study, not only those in the selection. @returns {Array} an array of {@link String} objects */ StudyComponent.prototype.retrieveUrl = function() { return this.json['retrieveUrl']; }; /** Series indetity and locating information of the DICOM SOP instances in the selection. @returns {Array} an array of {@link SeriesComponent} objects */ StudyComponent.prototype.series = function() { var i, item, len, ref, results; if (this.json['series']) { ref = this.json['series']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SeriesComponent(item)); } return results; } }; return StudyComponent; })(BackboneElement); /** A set of DICOM SOP Instances of a patient, selected for some application purpose, e.g., quality assurance, teaching, conference, consulting, etc. Objects selected can be from different studies, but must be of the same patient. @class ImagingObjectSelection @exports ImagingObjectSelection as ImagingObjectSelection */ ImagingObjectSelection = (function(superClass) { extend(ImagingObjectSelection, superClass); function ImagingObjectSelection(json) { this.json = json; ImagingObjectSelection.__super__.constructor.call(this, this.json); } /** Instance UID of the DICOM KOS SOP Instances represenetd in this resource. @returns {oid} */ ImagingObjectSelection.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** A patient resource reference which is the patient subject of all DICOM SOP Instances in this key object selection. @returns {Reference} */ ImagingObjectSelection.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** The reason for, or significance of, the selection of objects referenced in the resource. @returns {CodeableConcept} */ ImagingObjectSelection.prototype.title = function() { if (this.json['title']) { return new CodeableConcept(this.json['title']); } }; /** Text description of the DICOM SOP instances selected in the key object selection. This should be aligned with the content of the title element, and can provide further explanation of the SOP instances in the selection. @returns {Array} an array of {@link String} objects */ ImagingObjectSelection.prototype.description = function() { return this.json['description']; }; /** Author of key object selection. It can be a human authtor or a device which made the decision of the SOP instances selected. For example, a radiologist selected a set of imaging SOP instances to attached in a diagnostic report, and a CAD application may author a selection to describe SOP instances it used to generate a detection conclusion. @returns {Reference} */ ImagingObjectSelection.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; /** Date and time when the key object selection was authored. Note that this is the date and time the DICOM SOP instances in the selection were selected (selection decision making). It is different from the creation date and time of the selection resource. @returns {Array} an array of {@link Date} objects */ ImagingObjectSelection.prototype.authoringTime = function() { if (this.json['authoringTime']) { return DT.DateTime.parse(this.json['authoringTime']); } }; /** Study identity and locating information of the DICOM SOP instances in the selection. @returns {Array} an array of {@link StudyComponent} objects */ ImagingObjectSelection.prototype.study = function() { var i, item, len, ref, results; if (this.json['study']) { ref = this.json['study']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new StudyComponent(item)); } return results; } }; return ImagingObjectSelection; })(DomainResource); module.exports.ImagingObjectSelection = ImagingObjectSelection; }).call(this); //# sourceMappingURL=imagingobjectselection.js.map commercionetwork/almericosrc/store/starting/mutations.js export default { /** * * @param {StartingState} state */ startLoading(state) { state.error = null; state.isLoading = true; }, /** * * @param {StartingState} state */ stopLoading(state) { state.isLoading = false; }, /** * * @param {StartingState} state * @param {Object} error */ setError(state, error) { state.error = { ...error }; }, /** * * @param {StartingState} state * @param {Object} data */ setNodeInfo(state, data) { state.nodeInfo = { ...data, }; }, /** * * @param {StartingState} state * @param {Object} data */ setParams(state, data) { state.params = { ...data, }; }, /** * * @param {StartingState} state * @param {Object} data */ setPool(state, data) { state.pool = { ...data, }; }, /** * * @param {StartingState} state * @param {Array.} data */ setTokens(state, data) { state.tokens = data.map((obj) => ({ ...obj })); }, }; 1-10 /** * Module dependencies */ import indicative from 'indicative' /** * Application dependencies */ import db from './database' const { User } = db.models const required = param => { throw new Error(`Missing parameter ${param}`) } /** * Define custom rules */ const alphaSpace = (data, field, message, args, get) => new Promise((resolve, reject) => { const fieldValue = get(data, field) if (!fieldValue) return resolve('validation skipped') const regex = /^[a-zA-Z ]*$/ return regex.test(fieldValue) ? resolve('alpha_space validation passed') : reject(message) }) const uniqueEmail = (data, field, message, args, get) => new Promise((resolve, reject) => { const fieldValue = get(data, field) if (!fieldValue) return resolve('validation skipped'); (async function () { try { const user = await User.find({ where: { email: fieldValue } }) return user ? reject(message) : resolve('validation passed') } catch (error) { reject('Oops, can not check for unique email right now.') } })() }) indicative.extend('alphaSpace', alphaSpace, '{{field}} field can only contain alphabets and spaces.') indicative.extend('uniqueEmail', uniqueEmail, 'Email address is already registered.') export default () => async(ctx, next) => { ctx.validateRequest = async(body = required('body'), rules = required('rules'), messages) => { const defaultMessages = { email: 'It looks like the email address is not valid.', min: (field, validation, args) => `The ${field} field is too short. Must be at least ${args} characters long.`, max: (field, validation, args) => `The ${field} field is too long. Maximum number of characters allowed is ${args}.`, required: 'The {{field}} field is required.', ...messages } try { await indicative.validateAll(body, rules, defaultMessages) } catch (errors) { ctx.fail({ message: 'Validation failed', firstError: errors[0].message, errors }, 422) } } await next() } import { ServerInfo } from './collections'; class Params { static version = 'version'; static lastUpdateTime = 'lastUpdateTime' static CURR_VERSION = '0.0.1'; static get(paramKey) { return ServerInfo.findOne({name: paramKey}); } static set(paramKey, value) { return ServerInfo.upsert({name: paramKey}, {name: paramKey, value: value}); } } export { Params };nchriqui/24hWeatherDoc/html/namespace_m_xC3_xA9t_xC3_xA9o.js var namespace_m_xC3_xA9t_xC3_xA9o = [ [ "Calendar", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_calendar.html", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_calendar" ], [ "Mail", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_mail.html", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_mail" ], [ "Table", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_table.html", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_table" ], [ "User", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_user.html", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_user" ], [ "Weather", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_weather.html", "namespace_m_xC3_xA9t_xC3_xA9o_1_1_weather" ], [ "Connection", "class_m_xC3_xA9t_xC3_xA9o_1_1_connection.html", "class_m_xC3_xA9t_xC3_xA9o_1_1_connection" ], [ "Favoris", "class_m_xC3_xA9t_xC3_xA9o_1_1_favoris.html", "class_m_xC3_xA9t_xC3_xA9o_1_1_favoris" ], [ "FavorisTable", "class_m_xC3_xA9t_xC3_xA9o_1_1_favoris_table.html", "class_m_xC3_xA9t_xC3_xA9o_1_1_favoris_table" ], [ "Validator", "class_m_xC3_xA9t_xC3_xA9o_1_1_validator.html", "class_m_xC3_xA9t_xC3_xA9o_1_1_validator" ] ];"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Pagination = exports.PaginationVariant = void 0; var _propTypes = _interopRequireDefault(require("prop-types")); var React = _interopRequireWildcard(require("react")); var _Dropdown = require("../Dropdown"); var _ToggleTemplate = require("./ToggleTemplate"); var _pagination = _interopRequireDefault(require("@patternfly/react-styles/css/components/Pagination/pagination")); var _reactStyles = require("@patternfly/react-styles"); var _Navigation = require("./Navigation"); var _PaginationOptionsMenu = require("./PaginationOptionsMenu"); var _withOuia = require("../withOuia"); var _reactTokens = require("@patternfly/react-tokens"); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 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; } var PaginationVariant; exports.PaginationVariant = PaginationVariant; (function (PaginationVariant) { PaginationVariant["top"] = "top"; PaginationVariant["bottom"] = "bottom"; PaginationVariant["left"] = "left"; PaginationVariant["right"] = "right"; })(PaginationVariant || (exports.PaginationVariant = PaginationVariant = {})); var defaultPerPageOptions = [{ title: '10', value: 10 }, { title: '20', value: 20 }, { title: '50', value: 50 }, { title: '100', value: 100 }]; var handleInputWidth = function handleInputWidth(lastPage, node) { if (!node) { return; } var len = String(lastPage).length; if (len >= 3) { node.style.setProperty(_reactTokens.c_pagination__nav_page_select_c_form_control_width_chars.name, "".concat(len)); } else { node.style.setProperty(_reactTokens.c_pagination__nav_page_select_c_form_control_width_chars.name, '2'); } }; var paginationId = 0; var Pagination = /*#__PURE__*/ function (_React$Component) { _inherits(Pagination, _React$Component); function Pagination() { var _getPrototypeOf2; var _this; _classCallCheck(this, Pagination); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Pagination)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "paginationRef", React.createRef()); return _this; } _createClass(Pagination, [{ key: "getLastPage", value: function getLastPage() { var _this$props = this.props, itemCount = _this$props.itemCount, perPage = _this$props.perPage; return Math.ceil(itemCount / perPage) || 0; } }, { key: "componentDidMount", value: function componentDidMount() { var node = this.paginationRef.current; handleInputWidth(this.getLastPage(), node); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var node = this.paginationRef.current; if (prevProps.perPage !== this.props.perPage || prevProps.itemCount !== this.props.itemCount) { handleInputWidth(this.getLastPage(), node); } } }, { key: "render", value: function render() { var _this$props2 = this.props, children = _this$props2.children, className = _this$props2.className, variant = _this$props2.variant, isDisabled = _this$props2.isDisabled, isCompact = _this$props2.isCompact, perPage = _this$props2.perPage, titles = _this$props2.titles, firstPage = _this$props2.firstPage, propPage = _this$props2.page, offset = _this$props2.offset, defaultToFullPage = _this$props2.defaultToFullPage, itemCount = _this$props2.itemCount, itemsStart = _this$props2.itemsStart, itemsEnd = _this$props2.itemsEnd, perPageOptions = _this$props2.perPageOptions, dropDirection = _this$props2.dropDirection, widgetId = _this$props2.widgetId, toggleTemplate = _this$props2.toggleTemplate, onSetPage = _this$props2.onSetPage, onPerPageSelect = _this$props2.onPerPageSelect, onFirstClick = _this$props2.onFirstClick, onPreviousClick = _this$props2.onPreviousClick, onNextClick = _this$props2.onNextClick, onPageInput = _this$props2.onPageInput, onLastClick = _this$props2.onLastClick, ouiaContext = _this$props2.ouiaContext, ouiaId = _this$props2.ouiaId, props = _objectWithoutProperties(_this$props2, ["children", "className", "variant", "isDisabled", "isCompact", "perPage", "titles", "firstPage", "page", "offset", "defaultToFullPage", "itemCount", "itemsStart", "itemsEnd", "perPageOptions", "dropDirection", "widgetId", "toggleTemplate", "onSetPage", "onPerPageSelect", "onFirstClick", "onPreviousClick", "onNextClick", "onPageInput", "onLastClick", "ouiaContext", "ouiaId"]); var page = propPage; if (!page && offset) { page = Math.ceil(offset / perPage); } var lastPage = this.getLastPage(); if (page < firstPage && itemCount > 0) { page = firstPage; } else if (page > lastPage) { page = lastPage; } var firstIndex = itemCount <= 0 ? 0 : (page - 1) * perPage + 1; var lastIndex; if (itemCount <= 0) { lastIndex = 0; } else { lastIndex = page === lastPage ? itemCount : page * perPage; } return React.createElement("div", _extends({ ref: this.paginationRef, className: (0, _reactStyles.css)(_pagination["default"].pagination, variant === PaginationVariant.bottom && _pagination["default"].modifiers.footer, isCompact && _pagination["default"].modifiers.compact, className), id: "".concat(widgetId, "-").concat(paginationId++) }, ouiaContext.isOuia && { 'data-ouia-component-type': 'Pagination', 'data-ouia-component-id': ouiaId || ouiaContext.ouiaId }, props), variant === PaginationVariant.top && React.createElement("div", { className: (0, _reactStyles.css)(_pagination["default"].paginationTotalItems) }, React.createElement(_ToggleTemplate.ToggleTemplate, { firstIndex: firstIndex, lastIndex: lastIndex, itemCount: itemCount, itemsTitle: titles.items })), React.createElement(_PaginationOptionsMenu.PaginationOptionsMenu, { itemsPerPageTitle: titles.itemsPerPage, perPageSuffix: titles.perPageSuffix, itemsTitle: isCompact ? '' : titles.items, optionsToggle: titles.optionsToggle, perPageOptions: perPageOptions, firstIndex: itemsStart !== null ? itemsStart : firstIndex, lastIndex: itemsEnd !== null ? itemsEnd : lastIndex, defaultToFullPage: defaultToFullPage, itemCount: itemCount, page: page, perPage: perPage, lastPage: lastPage, onPerPageSelect: onPerPageSelect, dropDirection: dropDirection, widgetId: widgetId, toggleTemplate: toggleTemplate, isDisabled: isDisabled }), React.createElement(_Navigation.Navigation, { pagesTitle: titles.page, toLastPage: titles.toLastPage, toPreviousPage: titles.toPreviousPage, toNextPage: titles.toNextPage, toFirstPage: titles.toFirstPage, currPage: titles.currPage, paginationTitle: titles.paginationTitle, page: itemCount <= 0 ? 0 : page, perPage: perPage, firstPage: itemsStart !== null ? itemsStart : 1, lastPage: lastPage, onSetPage: onSetPage, onFirstClick: onFirstClick, onPreviousClick: onPreviousClick, onNextClick: onNextClick, onLastClick: onLastClick, onPageInput: onPageInput, isDisabled: isDisabled, isCompact: isCompact }), children); } }]); return Pagination; }(React.Component); _defineProperty(Pagination, "propTypes", { children: _propTypes["default"].node, className: _propTypes["default"].string, itemCount: _propTypes["default"].number.isRequired, variant: _propTypes["default"].oneOf(['top', 'bottom', 'left', 'right']), isDisabled: _propTypes["default"].bool, isCompact: _propTypes["default"].bool, perPage: _propTypes["default"].number, perPageOptions: _propTypes["default"].arrayOf(_propTypes["default"].shape({ title: _propTypes["default"].string, value: _propTypes["default"].number })), defaultToFullPage: _propTypes["default"].bool, firstPage: _propTypes["default"].number, page: _propTypes["default"].number, offset: _propTypes["default"].number, itemsStart: _propTypes["default"].number, itemsEnd: _propTypes["default"].number, widgetId: _propTypes["default"].string, dropDirection: _propTypes["default"].oneOf(['up', 'down']), titles: _propTypes["default"].shape({ page: _propTypes["default"].string, items: _propTypes["default"].string, itemsPerPage: _propTypes["default"].string, perPageSuffix: _propTypes["default"].string, toFirstPage: _propTypes["default"].string, toPreviousPage: _propTypes["default"].string, toLastPage: _propTypes["default"].string, toNextPage: _propTypes["default"].string, optionsToggle: _propTypes["default"].string, currPage: _propTypes["default"].string, paginationTitle: _propTypes["default"].string }), toggleTemplate: _propTypes["default"].oneOfType([_propTypes["default"].func, _propTypes["default"].string]), onSetPage: _propTypes["default"].func, onFirstClick: _propTypes["default"].func, onPreviousClick: _propTypes["default"].func, onNextClick: _propTypes["default"].func, onLastClick: _propTypes["default"].func, onPageInput: _propTypes["default"].func, onPerPageSelect: _propTypes["default"].func }); _defineProperty(Pagination, "defaultProps", { children: null, className: '', variant: PaginationVariant.top, isDisabled: false, isCompact: false, perPage: defaultPerPageOptions[0].value, titles: { items: '', page: '', itemsPerPage: 'Items per page', perPageSuffix: 'per page', toFirstPage: 'Go to first page', toPreviousPage: 'Go to previous page', toLastPage: 'Go to last page', toNextPage: 'Go to next page', optionsToggle: 'Items per page', currPage: 'Current page', paginationTitle: 'Pagination' }, firstPage: 1, page: 0, offset: 0, defaultToFullPage: false, itemsStart: null, itemsEnd: null, perPageOptions: defaultPerPageOptions, dropDirection: _Dropdown.DropdownDirection.down, widgetId: 'pagination-options-menu', toggleTemplate: _ToggleTemplate.ToggleTemplate, onSetPage: function onSetPage() { return undefined; }, onPerPageSelect: function onPerPageSelect() { return undefined; }, onFirstClick: function onFirstClick() { return undefined; }, onPreviousClick: function onPreviousClick() { return undefined; }, onNextClick: function onNextClick() { return undefined; }, onPageInput: function onPageInput() { return undefined; }, onLastClick: function onLastClick() { return undefined; }, ouiaContext: null, ouiaId: null }); var PaginationWithOuiaContext = (0, _withOuia.withOuiaContext)(Pagination); exports.Pagination = PaginationWithOuiaContext; //# sourceMappingURL=Pagination.js.map0 function handler(In) { this.executeOutputLink(In.type(), In); }src/main/webapp/resources/js/resultSearch.js /*function makeEditable() { $.ajax({ url: "rest/offers", method: "GET" }).then(function (response) { for(var i = 0; i < response.length ; i++) { var row = $(""); var name = $("" + response[i].name + ""); var description = $("" + response[i].description + ""); var price = $("" + response[i].price + ""); row.append([name, description, price]).append(""); tableBody.append(row); } }); }*/ /* $(function () { $.ajax({ url: "https://jsonplaceholder.typicode.com/posts", success: function (result) { $.each(result, function (index, item) { var userId = item.userId; var typeId = item.id; var titleId = item.title; var bodyId = item.body; var $info = $("

    ").html("user id: " + userId + "
    " + "id: " + typeId + "
    " + "title: " + titleId + "
    " + "body: " + bodyId); var html = '

    JavaScript/OOP/prototypeChain/inheritance01.js const ferrari = { carModel: 'F40', carSpeedLimit: 324, }; const volvo = { carModel: 'B40', carSpeedLimit: 200, }; console.log(ferrari.__proto__ === Object.prototype); console.log(volvo.__proto__ === Object.prototype); console.log(Object.prototype.__proto__); src/components/exampleTwo/pagination/Styled_Pagination.js import styled from 'styled-components'; import { Primary, Secondary, Black, Grey } from '../../../layout/layout.scss'; const StyledPagination = styled.section` .pagination { display: flex; justify-content: center; margin: 15px 0; ul { display: flex; .previous, .next { a { font-weight: 500; color: ${Black} !important; } } li { margin: 0 8px; padding: 0 8px; } .active { border-bottom: 1px solid ${Black}; a { color: ${Secondary}; } } .disabled { a { color: ${Grey} !important; } } a { color: ${Primary}; outline: none; } } } @media (max-width: 576px) { .pagination { font-size: .9em; ul { li { margin: 0 4px; } } } } @media (max-width: 425px) { .pagination { font-size: .8em; ul { li { margin: 0 2px; } } } } @media (max-width: 375px) { .pagination { font-size: .7em; ul { li { margin: 0; } } } } ` export default StyledPagination;src/utils/index.js1-10 import './hotkey' export * from './token' export * from './common' export * from './filter' export * from './generic-query' export * from './model' export * from './validate' api/middleware/errorHandler.js1-10 module.exports = function errorHandler(err, req, res, next) { switch (true) { case typeof err === 'string': console.log(err) // custom application error const is404 = err.toLowerCase().endsWith('not found'); const statusCode = is404 ? 404 : 400; return res.status(statusCode).send(err); case err.name === 'ValidationError': // mongoose validation error return res.status(400).send({ message: err.message }); case err.name === 'UnauthorizedError': // jwt authentication error return res.status(401).send({ message: 'Unauthorized' }); default: return res.status(500).send({ message: err.message }); } }steem.api.getDiscussionsByCreated({"tag": "steemnova-rewards", "limit": 1}, function(err, result) { if (err === null) { $('#feed').css('display', ''); $('#feed_margin').css('display', ''); var i, len = result.length; for (i = 0; i < len; i++) { var discussion = result[i]; $('#feed_'+i).css('display', ''); $('#title_'+i).text(discussion['title']); $('#url_'+i).attr('href', 'https://busy.org' + discussion['url']); $('#votes_'+i).text(discussion['net_votes']); $('#pending_payout_value_'+i).text(discussion['pending_payout_value']); document.getElementById('image_'+i).src = JSON.parse(discussion['json_metadata']).image[0]; } } else { console.log(err); } });test/integration/test.events-midroll.js100-1000 /* TODO: * timeupdate, adtimeupdate, contenttimeupdate * loadstart, adloadstart, contentloadstart * play, adplay, contentplay * loadeddata, adloadeddata, contentloadeddata * loadedmetadata, adloadedmetadata, contentloadedmetadata */ import videojs from 'video.js'; import '../../examples/basic-ad-plugin/example-plugin.js'; import document from 'global/document'; import QUnit from 'qunit'; QUnit.module('Events and Midrolls', { beforeEach() { this.video = document.createElement('video'); this.fixture = document.querySelector('#qunit-fixture'); this.fixture.appendChild(this.video); this.player = videojs(this.video); this.player.exampleAds({ adServerUrl: '/test/integration/lib/inventory.json', playPreroll: false, midrollPoint: 1 }); this.player.src({ src: 'http://vjs.zencdn.net/v/oceans.webm', type: 'video/webm' }); // Mute the player to allow playback without user interaction this.player.muted(true); }, afterEach() { this.player.dispose(); } }); QUnit.test('Midrolls', function(assert) { const done = assert.async(); let beforeMidroll = true; const seenInAdMode = []; const seenInContentResuming = []; const seenOutsideAdModeBefore = []; const seenOutsideAdModeAfter = []; this.player.on('adend', () => { beforeMidroll = false; }); let events = [ 'suspend', 'abort', 'error', 'emptied', 'stalled', 'canplay', 'canplaythrough', 'waiting', 'seeking', 'durationchange', 'progress', 'pause', 'ratechange', 'volumechange', 'firstplay', 'suspend', 'playing', 'ended' ]; events = events.concat(events.map(function(e) { return 'ad' + e; })); events = events.concat(events.map(function(e) { return 'content' + e; })); this.player.on(events, (e) => { const str = e.type; if (this.player.ads.isInAdMode()) { if (this.player.ads.isContentResuming()) { seenInContentResuming.push(str); } else { seenInAdMode.push(str); } } else if (beforeMidroll) { seenOutsideAdModeBefore.push(str); } else { seenOutsideAdModeAfter.push(str); } }); this.player.on(['error', 'aderror'], () => { assert.ok(false, 'no errors'); done(); }); this.player.on('timeupdate', () => { videojs.log(this.player.currentTime(), this.player.currentSrc()); if (this.player.currentTime() > 1.1) { seenOutsideAdModeBefore.forEach((event) => { assert.ok(!/^ad/.test(event), event + ' has no ad prefix before midroll'); assert.ok(!/^content/.test(event), event + ' has no content prefix before midroll'); }); seenInAdMode.forEach((event) => { assert.ok(/^ad/.test(event), event + ' has ad prefix during midroll'); }); seenInContentResuming.forEach((event) => { assert.ok(/^content/.test(event), event + ' has content prefix during midroll'); }); seenOutsideAdModeAfter.forEach((event) => { assert.ok(!/^ad/.test(event), event + ' has no ad prefix after midroll'); assert.ok(!/^content/.test(event), event + ' has no content prefix after midroll'); }); done(); } }); // Seek to right before the midroll this.player.one('playing', () => { this.player.currentTime(0.9); }); this.player.ready(this.player.play); }); app/components/Introduction.js import React from 'react'; class Introduction extends React.Component { render() { return (

    Welcome!

    My name is .

    I am a full stack software developer with a special interest for web applications.

    Currently, I live in Chicago and I am open to meet in person, or feel free to contact me through my website.

    If you're intreseted in what I'm currently working on, you can check it out on github or codepen.

    Enjoy your stay!

    ); } } export default Introduction; node_modules/tinify/lib/tinify/compat.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fs = require("fs"); /** @internal */ function promisify(fn) { return function () { const args = Array.from(arguments); return new Promise((resolve, reject) => { args.push((err, value) => { if (err) return reject(err); resolve(value); }); fn.apply(undefined, args); }); }; } /** @internal */ exports.readFile = promisify(fs.readFile); /** @internal */ exports.writeFile = promisify(fs.writeFile); /** @internal */ const nodeify = require("promise-nodeify"); exports.nodeify = nodeify; /* eslint-disable no-unused-expressions */ import React from 'react' import savor from 'react-savor' import { App } from '../../../src' import { Data, Core, Errors } from 'react-chunky' import appConfig from '../../assets/chunky' import { JSDOM } from 'jsdom' import { Redirect } from 'react-router/cjs/react-router' import { Container } from 'react-chunky/lib/core' savor .add('should not to render the web app without properties', (context, done) => { const props = { info: { analytics: {} } } context.expect(() => { context.shallow( ) }).to.throw(Errors.UNABLE_TO_LOAD_CHUNKS().message) done() }) .add('should create a web app and have a valid lifecyle', (context, done) => { context.spy(App.prototype, 'componentDidMount') context.spy(App.prototype, 'render') const container = context.mount( ) // And, we're looking good App.prototype.componentDidMount.restore() App.prototype.render.restore() done() }) .add('should handle an error in retrieving a user account', (context, done) => { const stub = context.stub(global.storage, 'getItem').callsFake(((key, callback) => callback(null, null))) const container = context.mount( ) // And, we're looking good stub.restore() done() }) .add('should retrieve a cache user account', (context, done) => { const stub = context.stub(global.storage, 'getItem').callsFake(((key, callback) => callback(null, { username: "chunky" }))) const container = context.mount( ) // And, we're looking good stub.restore() done() }) .add('should handle events', (context, done) => { global.firebase = { auth: () => ({ currentUser: { uid: "test", emailVerified: true }, signOut: () => ({}) }) } const container = context.shallow() const app = container.instance() app.userLoggedIn({ username: "test" }) app.userLogout() // And, we're looking good done() }) .add('should handle transitions', (context, done) => { const container = context.mount( ) // And, we're looking good done() }) .run('[Web] App Rendering') if (!phantom.casperLoaded) { console.log('This script must be invoked using the casperjs executable'); phantom.exit(1); } var fs = require('fs'); var utils = require('utils'); var f = utils.format; var casper = require('casper').create({ faultTolerant: false }); // Options from cli casper.options.verbose = casper.cli.get('direct') || false; casper.options.logLevel = casper.cli.get('log-level') || "error"; // Overriding Casper.open to prefix all test urls casper.setFilter('open.location', function(location) { if (!/^http/.test(location)) { return f('file://%s/%s', phantom.casperPath, location); } return location; }); var tests = []; if (casper.cli.args.length) { tests = casper.cli.args.filter(function(path) { return fs.isFile(path) || fs.isDirectory(path); }); } else { casper.echo('No test path passed, exiting.', 'RED_BAR', 80); casper.exit(1); } casper.test.on('tests.complete', function() { this.renderResults(true, undefined, casper.cli.get('xunit') || undefined); }); casper.test.runSuites.apply(casper.test, tests); import React, { useState } from "react" import { navigate } from "gatsby" import Layout from "../layout" import SEO from "../seo" import useFBAuth from "../hooks/useFBAuth" import Container from "../components/boxes/container" import Flex from "../components/boxes/flex" import Box from "../components/boxes/box" const Register = () => { const auth = useFBAuth() const [details, setDetails] = useState({ regFirst: "", regLast: "", regEmail: "", regPassword: "", }) const handleSubmit = e => { e.preventDefault() auth .createUserWithEmailAndPassword(details.regEmail, details.regPassword) .then(cred => { cred.user.updateProfile({ displayName: details.regFirst, }) navigate("/app") }) } const handleChange = e => { setDetails({ ...details, [e.target.name]: e.target.value }) } return (
    ) } export default Register 0 const { User } = require('../model/users'); const express = require('express'); const router = express.Router(); const jwt = require("jsonwebtoken"); const dotenv = require("dotenv").config(); const redis = require("redis"); const redisClient = require('../redis/client') router.get('/', async (req, res) => { //TODO: Delete this endopoint as it is only for development let listOfUsers = await User.find() res.send(listOfUsers) }) router.post('/register', async (req, res) => { // Check if this user already exisits let user = await User.findOne({ email: req.body.email }); if (user) { return res.status(400).send('That user already exisits!'); } else { // Insert the new user if they do not exist yet user = new User({ name: req.body.name, email: req.body.email, password: }); await user.save((err, user) => { // Create a token with the user_ID let user_Id = user._id.toString() let token = jwt.sign( {user_Id} , process.env.TOKEN_SECRET, { expiresIn: '10h' }) // And store the user in Redis under key redisClient.set(user_Id, token, redis.print ); //Send User Token (TODO: Save in localstorage vs sessions) res.send({ user, token }); }); } }); router.post("/login", async (req, res, next) => { // When user logs in, there is no token pair in the browser // cookies. We need to issue both of them. Because you also // log user in in this step, let user = await User.findOne({ email: req.body.email }); if (!user) { res.status(400).send('User does not exist') } else { let token = jwt.sign(user._id, process.env.TOKEN_SECRET, { expiresIn: '10h' }) redisClient.set(user._id, token, redisClient.print); } res.send({ user, token }); }); module.exports = router;wirtaw/vue-awesome import Icon from '../components/Icon.vue' Icon.register({ rocket: { width: 512, height: 512, paths: [ { d: 'M505.1 19.1c7 32.2 7 57.4 6.9 82.6 0 102.7-55.4 164.8-128 211.1v104.4 0c0 16.4-11.9 35.6-26.5 42.9l-98.7 49.4c-2.8 1.4-7.6 2.5-10.7 2.5-13.2 0-24-10.8-24-24v0-103.8l-22.5 22.5c-5.2 5.2-15.3 9.4-22.6 9.4-7.3 0-17.5-4.2-22.6-9.4l-50.9-50.9c-5.2-5.2-9.4-15.3-9.4-22.6s4.2-17.5 9.4-22.6l22.5-22.5h-103.8 0c-13.2 0-24-10.8-24-24 0-3.1 1.1-7.9 2.5-10.7l49.4-98.8c7.3-14.6 26.5-26.5 42.9-26.5h104.2c46.2-72.8 108.1-128 211.3-128 25.1 0 50.3 0 82.5 6.9 5.5 1.2 11 6.7 12.2 12.2zM384 168c22.1 0 40-17.9 40-40s-17.9-40-40-40-40 17.9-40 40 17.9 40 40 40z' } ] } }) windylaugit/windyland.com /** * */ define(function(require,exports,module){ /* ui插件 */ require('ui/wlTable'); var me = require('js/me'); me.C({ columns:[ {display:'ID',width:40,name:'id'}, {display:'栏目名称',width:200,name:'name'}, ], init:function(){ me.init_eles(); me.init_grid(); }, init_eles:function(){ me.eles = { $list:$('#column_list') } }, init_grid:function(){ me.grid = me.eles.$list.wlTable({ columns:me.columns, checkbox:true, multiLevel:true, multiLevelColumn:'name' }); /* 添加数据 */ me.grid.load([ {id:1006,name:"下载中心3-1",pid:1005}, {id:1003,name:"下载中心1",pid:1002}, {id:1001,name:"编程技术"}, {id:1004,name:"下载中心2",pid:1002}, {id:1002,name:"下载中心"}, {id:1005,name:"下载中心3",pid:1002}, ]); } }); return me.init(); });SWRapp/src/views/WeatherPageAlt.js import React from "react"; import AltWeather from "../components/AltWeather/index"; export default class WeatherPageAlt extends React.Component { render() { return ; } } lananh265/social-network "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.zoomInOutline = void 0; var zoomInOutline = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M13 11h-2v-2c0-.275-.225-.5-.5-.5s-.5.225-.5.5v2h-2c-.275 0-.5.225-.5.5s.225.5.5.5h2v2c0 .275.225.5.5.5s.5-.225.5-.5v-2h2c.275 0 .5-.225.5-.5s-.225-.5-.5-.5zM19.381 15.956l-2.244-2.283c.227-.687.363-1.412.363-2.173 0-3.859-3.141-7-7-7s-7 3.141-7 7 3.141 7 7 7c.762 0 1.488-.137 2.173-.364l2.397 2.386c.601.506 1.348.783 2.104.783 1.727 0 3.131-1.404 3.131-3.131 0-.84-.328-1.628-.924-2.218zm-3.901-1.11l2.492 2.531c.205.203.332.486.332.797 0 .625-.507 1.131-1.131 1.131-.312 0-.594-.127-.816-.313l-2.512-2.511c.646-.436 1.201-.991 1.635-1.635zm-9.98-3.346c0-2.757 2.243-5 5-5s5 2.243 5 5-2.243 5-5 5-5-2.243-5-5z" }, "children": [] }] }; exports.zoomInOutline = zoomInOutline;"use strict"; /** * The singleton GeoShape provides public transformAndDownload() method for conversion of GeoJSON to zipped shapefile(s). * Because the shapefile can contain only the records of same type of geometry the transform() method generates standalone shapefile set (shp, shx, dbf, cpg, prj, csv) * for each distinct geometry type. * Usage: GeoShape.transformAndDownload(parsedGeoJSONObject, "zippedShapeFile.zip"); * * */ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var GeoShape = { /** * GeoJSON to shapefile conversion * * @param {any} jsonObject - input GeoJSON object * @param {any} resultZipFile - desired filename of output zip file */ transformAndDownload: function transformAndDownload(jsonObject, resultZipFile) { this.files = []; this.files["Point"] = new PointFileGen(); this.files["LineString"] = new LineStringFileGen(); this.files["Polygon"] = new PolygonFileGen(); this.files["MultiPoint"] = new MultiPointFileGen(); this.files["MultiLineString"] = new MultiLineStringFileGen(); this.files["MultiPolygon"] = new MultiPolygonFileGen(); jsonObject.features.forEach(function (item, index) { if (item.geometry) this.files[item.geometry.type].process(item); else if (item.geometries) { //GeometryCollection item.geometries.forEach(function (item, index) { var gitem = {}; gitem.geometry = item; this.files[item.type].process(gitem); }, this); } }, this); var zip = new JSZip(); for (var fname in this.files) { var f = this.files[fname]; if (f.records.length > 0) { f.writeShp(); zip.file(f.getShpName(), f.shp); f.writeShx(); zip.file(f.getShxName(), f.shx); f.writeDbf(); zip.file(f.getDbfName(), f.dbf); zip.file(f.getCpgName(), "UTF-8"); if (f.useCSV) { f.writeCsv(); zip.file(f.getCsvName(), f.csv); } if (jsonObject.crs && jsonObject.crs.properties && jsonObject.crs.properties.name) zip.file(f.getPrjName(), jsonObject.crs.properties.name); } } if (!resultZipFile) resultZipFile = "result.zip"; zip.generateAsync({ type: "blob" }).then(function (blob) { // 1) generate the zip file GeoShape._downloadBlob(blob, resultZipFile); // 2) trigger the download }, function (err) { jQuery("#blob").text(err); }); }, /** * Blob data download * @param {any} blob * @param {any} resultZipFile */ _downloadBlob: function _downloadBlob(blob, resultZipFile) { if (window.navigator && window.navigator.msSaveBlob) window.navigator.msSaveBlob(blob, resultZipFile); else { var a = document.createElement("a"); a.style = "display: none"; document.body.appendChild(a); //Create a DOMString representing the blob //and point the link element towards it var url = window.URL.createObjectURL(blob); a.href = url; a.download = resultZipFile; a.target = "_self"; //programatically click the link to trigger the download a.click(); //release the reference to the file by revoking the Object URL window.URL.revokeObjectURL(url); } }, /** * Shape record writers - bounding box * @param {any} rec - ShapeRecord object * @param {any} shpView - file view * @param {any} offset - file offset */ _recWriteBox: function _recWriteBox(rec, shpView, offset) { var ofs = 8 + offset; shpView.setFloat64(4 + ofs, rec.X1, true); shpView.setFloat64(12 + ofs, rec.Y1, true); shpView.setFloat64(20 + ofs, rec.X2, true); shpView.setFloat64(28 + ofs, rec.Y2, true); }, /** * Shape record writers - record length calculators * * @param {any} rec - ShapeRecord object */ _recGetPointContentLength: function _recGetPointContentLength(rec) { return 20; }, _recGetMultiPointContentLength: function _recGetMultiPointContentLength(rec) { return 40 + 8 * rec.points.length; }, _recGetPolygonContentLength: function _recGetPolygonContentLength(rec) { return 44 + 4 * rec.partCount + 8 * rec.points.length; }, /** * Shape record writers - geometry writers * * @param {any} rec - ShapeRecord object * @param {any} shpView - file view * @param {any} offset - file offset * @param {any} id - record id */ _recWritePointGeometry: function _recWritePointGeometry(rec, shpView, offset, id) { if (rec.points.length == 0) return; // record header shpView.setInt32(0 + offset, id, false); //big record id shpView.setInt32(4 + offset, GeoShape._recGetPointContentLength(rec) / 2, false); //big record len //record content var ofs = 8 + offset; shpView.setInt32(0 + ofs, rec.fileGen.shape, true); shpView.setFloat64(4 + ofs, rec.points[0], true); shpView.setFloat64(12 + ofs, rec.points[1], true); }, _recWritePolygonGeometry: function _recWritePolygonGeometry(rec, shpView, offset, id) { var pc = rec.points.length; if (pc == 0) return; // record header shpView.setInt32(0 + offset, id, false); //big record id shpView.setInt32(4 + offset, GeoShape._recGetPolygonContentLength(rec) / 2, false); //big record len //record content var ofs = 8 + offset; shpView.setInt32(0 + ofs, rec.fileGen.shape, true); GeoShape._recWriteBox(rec, shpView, offset); shpView.setInt32(36 + ofs, rec.partCount, true); shpView.setInt32(40 + ofs, pc / 2, true); ofs = 8 + 44 + offset; for (var i = 0; i < rec.partCount; i++) { shpView.setInt32(ofs + 4 * i, rec.partIndices[i], true); } ofs = 8 + 44 + offset + 4 * rec.partCount; for (var i = 0; i < pc; i++) { shpView.setFloat64(ofs + 8 * i, rec.points[i], true); } }, _recWriteMultiPointGeometry: function _recWriteMultiPointGeometry(rec, shpView, offset, id) { var pc = rec.points.length; if (pc == 0) return; // record header shpView.setInt32(0 + offset, id, false); //big record id shpView.setInt32(4 + offset, GeoShape._recGetMultiPointContentLength(rec) / 2, false); //big record len //record content var ofs = 8 + offset; shpView.setInt32(0 + ofs, rec.fileGen.shape, true); GeoShape._recWriteBox(rec, shpView, offset); shpView.setInt32(36 + ofs, pc / 2, true); ofs = 8 + 40 + offset; for (var i = 0; i < pc; i++) { shpView.setFloat64(ofs + 8 * i, rec.points[i], true); } } }; /** * Shapefile record class * * Gathers all informations about single shape record - source geometry, file generator object, bounding box, properties * * */ var ShapeRecord = function () { function ShapeRecord(fileGen, item) { _classCallCheck(this, ShapeRecord); this.fileGen = fileGen; this.points = []; this.partIndices = []; this.partCount = 0; this.X1 = 16.288516; this.X2 = 9.797679; this.Y1 = 46.442824; this.Y2 = 48.708890; fileGen.useCSV = false; fileGen.records.push(this); this.properties = []; this.propertiesOrig = []; if (item.properties) { for (var pname in item.properties) { fileGen.propertyNames[pname] = pname; var orig = item.properties[pname]; var val = ShapeRecord.toUTF8Array(orig); var len = val ? val.length : 0; if (len > 250) { fileGen.useCSV = true; len = 250; val = val.slice(0, 250); } this.properties[pname] = val; this.propertiesOrig[pname] = orig; if (!fileGen.propertyLengths[pname] || fileGen.propertyLengths[pname] < len) fileGen.propertyLengths[pname] = len; } } } /** * Update the record geometry bounds with respect to given point * * @param {any} X * @param {any} Y */ _createClass(ShapeRecord, [{ key: "checkBounds", value: function checkBounds(X, Y) { if (this.X1 > X) this.X1 = X; if (this.X2 < X) this.X2 = X; if (this.Y1 < Y) this.Y1 = Y; if (this.Y2 > Y) this.Y2 = Y; } /** * Object to string converter * * @param {any} str */ }, { key: "getDbfRecordArray", /** * Record to DBF record converter * * @param {any} id - record id * @param {any} idLen - record id field length */ value: function getDbfRecordArray(id, idLen) { var rec = new Array(1 /*delMarker*/ + idLen) /*.fill(32)*/; for (var i = 0; i < rec.length; i++) { rec[i] = 32; } var val = ShapeRecord.toArray(id); // write fid for (var d = idLen, s = val.length - 1; s >= 0; d-- , s--) { rec[d] = val[s]; } for (var item in this.fileGen.propertyNames) { var flen = this.fileGen.propertyLengths[item]; var f = new Array(flen) /*.fill(32)*/; for (var i = 0; i < f.length; i++) { f[i] = 32; } val = this.properties[item]; if (val) { for (var i = 0; i < val.length; i++) { f[i] = val[i]; } } rec = rec.concat(f); }; return rec; } /** * Record to CSV record converter * * @param {any} id - record id */ }, { key: "getCsvRecordString", value: function getCsvRecordString(id) { var rec = id.toString(); for (var item in this.fileGen.propertyNames) { var val = ShapeRecord.toStr(this.propertiesOrig[item]); if (val) { rec += ";\"" + val.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; } else rec += ";"; }; return rec; } }], [{ key: "toStr", value: function toStr(str) { if (!str) return null; switch (typeof str === "undefined" ? "undefined" : _typeof(str)) { case "number": str = str.toString(); break; case "boolean": str = str ? "1" : "0"; break; case "object": str = str.toString(); break; } return str; } /** * String to array converter * * @param {any} str */ }, { key: "toArray", value: function toArray(str) { if (!str) return null; str = ShapeRecord.toStr(str); var res = []; for (var i = 0; i < str.length; i++) { res[i] = str.charCodeAt(i); } return res; } /** * String to UTF8 ancoded array converter * * @param {any} str */ }, { key: "toUTF8Array", value: function toUTF8Array(str) { if (!str) return null; str = ShapeRecord.toStr(str); var utf8 = []; for (var i = 0; i < str.length; i++) { var charcode = str.charCodeAt(i); if (charcode < 0x80) utf8.push(charcode); else if (charcode < 0x800) { utf8.push(0xc0 | charcode >> 6, 0x80 | charcode & 0x3f); } else if (charcode < 0xd800 || charcode >= 0xe000) { utf8.push(0xe0 | charcode >> 12, 0x80 | charcode >> 6 & 0x3f, 0x80 | charcode & 0x3f); } else { i++; charcode = 0x10000 + ((charcode & 0x3ff) << 10 | str.charCodeAt(i) & 0x3ff); utf8.push(0xf0 | charcode >> 18, 0x80 | charcode >> 12 & 0x3f, 0x80 | charcode >> 6 & 0x3f, 0x80 | charcode & 0x3f); } } return utf8; } }]); return ShapeRecord; }(); /** * Shapefile generator base class * * This class and his subclasses gather all ShapeRecord objects for single geometry type and control the shape file generation * * */ var ESRIFileGen = function () { /** * Constructor * @param {any} geometry - geometry name * @param {any} shape - target ESRI shape type */ function ESRIFileGen(geometry, shape) { _classCallCheck(this, ESRIFileGen); this.geometry = geometry; this.shape = shape; this.records = []; this.X1 = 9999; this.X2 = -9999; this.Y1 = -9999; this.Y2 = 9999; this.propertyNames = []; this.propertyLengths = []; this.useCSV = false; } /** * Update the file geometry bounds with respect to given point * * @param {any} X * @param {any} Y */ _createClass(ESRIFileGen, [{ key: "checkBounds", value: function checkBounds(X, Y) { if (this.X1 > X) this.X1 = X; if (this.X2 < X) this.X2 = X; if (this.Y1 < Y) this.Y1 = Y; if (this.Y2 > Y) this.Y2 = Y; } /** * Geometry processing method. Each geometry has its specific process() method implemented by subclasses of this class * * @param {any} item */ }, { key: "process", value: function process(item) { } /** * Target files - names */ }, { key: "getShpName", value: function getShpName() { return this.geometry + ".shp"; } }, { key: "getShxName", value: function getShxName() { return this.geometry + ".shx"; } }, { key: "getDbfName", value: function getDbfName() { return this.geometry + ".dbf"; } }, { key: "getCpgName", value: function getCpgName() { return this.geometry + ".cpg"; } }, { key: "getCsvName", value: function getCsvName() { return this.geometry + ".csv"; } }, { key: "getPrjName", value: function getPrjName() { return this.geometry + ".prj"; } /** * Target files - size calculations */ }, { key: "getShxSize", value: function getShxSize() { var s = 100 + 8 * this.records.length; return s; } }, { key: "getShpSize", value: function getShpSize() { var s = 100; this.records.forEach(function (item, index) { s += 8 + this._getContentLength(item); }, this); return s; } /** * Target files - writers */ }, { key: "writeShp", value: function writeShp() { if (this.records.length == 0) return; var size = this.getShpSize(); this.shp = new ArrayBuffer(size); this.shpView = new DataView(this.shp); var offset = 100; var id = 1; this.records.forEach(function (item, index) { this.checkBounds(item.X1, item.Y1); this.checkBounds(item.X2, item.Y2); this._writeGeometry(item, this.shpView, offset, id); offset += 8 + this._getContentLength(item); id++; }, this); this._writeShpxHeader(this.shpView, size); } }, { key: "writeShx", value: function writeShx() { if (this.records.length == 0) return; var size = this.getShxSize(); this.shx = new ArrayBuffer(size); this.shxView = new DataView(this.shx); var offset = 100; var ioffset = 100; var id = 1; this.records.forEach(function (item, index) { this.shxView.setInt32(0 + offset, ioffset / 2, false); //big record id var size = this._getContentLength(item); this.shxView.setInt32(4 + offset, size / 2, false); //big record id ioffset += 8 + size; offset += 8; id++; }, this); this._writeShpxHeader(this.shxView, size); } }, { key: "_writeShpxHeader", value: function _writeShpxHeader(dataView, size) { dataView.setInt32(0, 9994, false); //big dataView.setInt32(24, size / 2, false); //filesize - big dataView.setInt32(28, 1000, true); //little dataView.setInt32(32, this.shape, true); //little dataView.setFloat64(36, this.X1, true); dataView.setFloat64(44, this.Y2, true); dataView.setFloat64(52, this.X2, true); dataView.setFloat64(60, this.Y1, true); } }, { key: "writeDbf", value: function writeDbf() { var headerSize = 32; var fieldCount = 1; var idLen = 0x0b; var flen = idLen; var recordBytes = flen; var h = [3, 120, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var f = [0x46, 0x49, 0x44, 0, 0, 0, 0, 0, 0, 0, 0, 0x4e, 0, 0, 0, 0, flen, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; h = h.concat(f); for (var item in this.propertyNames) { flen = this.propertyLengths[item]; f = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x43, 0, 0, 0, 0, flen, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (var i = 0; i < item.length; i++) { f[i] = item.charCodeAt(i); } fieldCount++; recordBytes += flen; h = h.concat(f); }; headerSize += 32 * fieldCount + 1 /*fieldTerm*/; h[headerSize - 1] = 13; /*fieldTerm*/ var size = headerSize + (1 /*delMarker*/ + recordBytes) * this.records.length; this.dbf = new ArrayBuffer(size); var array = new Uint8Array(this.dbf); array.set(h, 0); var dataView = new DataView(this.dbf); dataView.setUint32(4, this.records.length, true); dataView.setUint16(8, headerSize, true); dataView.setUint16(10, recordBytes + 1, true); var offset = headerSize; var id = 1; this.records.forEach(function (record, index) { var rec = record.getDbfRecordArray(id, idLen); array.set(rec, offset); offset += 1 /*delMarker*/ + recordBytes; id++; }, this); } }, { key: "writeCsv", value: function writeCsv() { var res = "FID"; for (var item in this.propertyNames) { res += ";" + item; }; var id = 1; this.records.forEach(function (record, index) { var rec = record.getCsvRecordString(id); res += "\n" + rec; id++; }, this); this.csv = [0xef, 0xbb, 0xbf].concat(ShapeRecord.toUTF8Array(res)); } }]); return ESRIFileGen; }(); /** * Shapefile generators implementing all GeoJSON geometries, each implementing geometry specific process() method */ var PointFileGen = function (_ESRIFileGen) { _inherits(PointFileGen, _ESRIFileGen); function PointFileGen() { _classCallCheck(this, PointFileGen); var _this = _possibleConstructorReturn(this, (PointFileGen.__proto__ || Object.getPrototypeOf(PointFileGen)).call(this, "Point", 1)); _this._writeGeometry = GeoShape._recWritePointGeometry; _this._getContentLength = GeoShape._recGetPointContentLength; return _this; } _createClass(PointFileGen, [{ key: "process", value: function process(item) { var g = item.geometry.coordinates; this.checkBounds(item[0], item[1]); var rec = new ShapeRecord(this, item); rec.checkBounds(item[0], item[1]); rec.points.push(g[0], g[1]); } }]); return PointFileGen; }(ESRIFileGen); var LineStringFileGen = function (_ESRIFileGen2) { _inherits(LineStringFileGen, _ESRIFileGen2); function LineStringFileGen() { _classCallCheck(this, LineStringFileGen); var _this2 = _possibleConstructorReturn(this, (LineStringFileGen.__proto__ || Object.getPrototypeOf(LineStringFileGen)).call(this, "LineString", 3)); _this2._writeGeometry = GeoShape._recWritePolygonGeometry; _this2._getContentLength = GeoShape._recGetPolygonContentLength; return _this2; } _createClass(LineStringFileGen, [{ key: "process", value: function process(item) { var g = item.geometry.coordinates; var rec = new ShapeRecord(this, item); rec.partIndices[rec.partCount++] = rec.points.length / 2; g.forEach(function (item, index) { rec.checkBounds(item[0], item[1]); rec.points.push(item[0], item[1]); }, this); } }]); return LineStringFileGen; }(ESRIFileGen); var PolygonFileGen = function (_ESRIFileGen3) { _inherits(PolygonFileGen, _ESRIFileGen3); function PolygonFileGen() { _classCallCheck(this, PolygonFileGen); var _this3 = _possibleConstructorReturn(this, (PolygonFileGen.__proto__ || Object.getPrototypeOf(PolygonFileGen)).call(this, "Polygon", 5)); _this3._writeGeometry = GeoShape._recWritePolygonGeometry; _this3._getContentLength = GeoShape._recGetPolygonContentLength; return _this3; } _createClass(PolygonFileGen, [{ key: "process", value: function process(item) { var g = item.geometry.coordinates; var rec = new ShapeRecord(this, item); g.forEach(function (pg, index) { rec.partIndices[rec.partCount++] = rec.points.length / 2; pg.forEach(function (item, index) { rec.checkBounds(item[0], item[1]); rec.points.push(item[0], item[1]); }, this); }, this); } }]); return PolygonFileGen; }(ESRIFileGen); var MultiPointFileGen = function (_ESRIFileGen4) { _inherits(MultiPointFileGen, _ESRIFileGen4); function MultiPointFileGen() { _classCallCheck(this, MultiPointFileGen); var _this4 = _possibleConstructorReturn(this, (MultiPointFileGen.__proto__ || Object.getPrototypeOf(MultiPointFileGen)).call(this, "MultiPoint", 8)); _this4._writeGeometry = GeoShape._recWriteMultiPointGeometry; _this4._getContentLength = GeoShape._recGetMultiPointContentLength; return _this4; } _createClass(MultiPointFileGen, [{ key: "process", value: function process(item) { var g = item.geometry.coordinates; var rec = new ShapeRecord(this, item); g.forEach(function (item, index) { rec.checkBounds(item[0], item[1]); rec.points.push(item[0], item[1]); }, this); } }]); return MultiPointFileGen; }(ESRIFileGen); var MultiLineStringFileGen = function (_ESRIFileGen5) { _inherits(MultiLineStringFileGen, _ESRIFileGen5); function MultiLineStringFileGen() { _classCallCheck(this, MultiLineStringFileGen); var _this5 = _possibleConstructorReturn(this, (MultiLineStringFileGen.__proto__ || Object.getPrototypeOf(MultiLineStringFileGen)).call(this, "MultiLineString", 3)); _this5._writeGeometry = GeoShape._recWritePolygonGeometry; _this5._getContentLength = GeoShape._recGetPolygonContentLength; return _this5; } _createClass(MultiLineStringFileGen, [{ key: "process", value: function process(item) { var g = item.geometry.coordinates; var rec = new ShapeRecord(this, item); g.forEach(function (ls, index) { rec.partIndices[rec.partCount++] = rec.points.length / 2; ls.forEach(function (item, index) { rec.checkBounds(item[0], item[1]); rec.points.push(item[0], item[1]); }, this); }, this); } }]); return MultiLineStringFileGen; }(ESRIFileGen); var MultiPolygonFileGen = function (_ESRIFileGen6) { _inherits(MultiPolygonFileGen, _ESRIFileGen6); function MultiPolygonFileGen() { _classCallCheck(this, MultiPolygonFileGen); var _this6 = _possibleConstructorReturn(this, (MultiPolygonFileGen.__proto__ || Object.getPrototypeOf(MultiPolygonFileGen)).call(this, "MultiPolygon", 5)); _this6._writeGeometry = GeoShape._recWritePolygonGeometry; _this6._getContentLength = GeoShape._recGetPolygonContentLength; return _this6; } _createClass(MultiPolygonFileGen, [{ key: "process", value: function process(item) { var g = item.geometry.coordinates; var rec = new ShapeRecord(this, item); g.forEach(function (mpg, index) { mpg.forEach(function (pg, index) { rec.partIndices[rec.partCount++] = rec.points.length / 2; pg.forEach(function (item, index) { rec.checkBounds(item[0], item[1]); rec.points.push(item[0], item[1]); }, this); }, this); }, this); } }]); return MultiPolygonFileGen; }(ESRIFileGen); // Load dependencies const xsltProcessor = require('xslt-processor'); const fs = require("fs"); const rp = require('request-promise').defaults({ jar: true }); const path = require("path"); const Config = require("./app/Config.js"); /** * Reads XML files needed to run AUnit Tests and transform to JUnit * @return xml file with call to run abap unit test, xsl to transform from AUnit Result to JUnit Result */function readXml() { const xsltData = fs.readFileSync(path.resolve(__dirname, "./xml/aunit2junit.xsl")); const xmlRunAbapUnitBuffer = fs.readFileSync(path.resolve(__dirname, "./xml/runAbapUnit.xml")); const xslt = xsltProcessor.xmlParse(xsltData.toString()); // xsltString: string of xslt file contents const xmlRunAbapUnit = xmlRunAbapUnitBuffer.toString('utf8').replace("{{package}}", config.configuration.test.package ); return { xmlRunAbapUnit, xslt }; } /** Run abap unit tests * @param csrf token needed for the call * @returns Promise with the result */ function runAbapUnitTest(xmlRunAbapUnit, xCSRFToken) { const optionsRunUnitTest = getRunUnitTestOptions(xmlRunAbapUnit, xCSRFToken); return rp(optionsRunUnitTest); } function getRunUnitTestOptions(xmlRunAbapUnit, xCSRFToken) { return { method: 'POST', url: config.configuration.network.protocol + '://' + config.configuration.network.host + '/sap/bc/adt/abapunit/testruns', auth: { user: config.configuration.auth.username, password: config.configuration.auth.password }, headers: { 'x-csrf-token': xCSRFToken, 'Content-Type': "application/vnd.sap.adt.abapunit.testruns.config.v2+xml", 'Accept' : 'application/vnd.sap.adt.abapunit.testruns.result.v1+xml' }, body: xmlRunAbapUnit, insecure: config.configuration.network.insecure, rejectUnauthorized: !config.configuration.network.insecure }; } /** Get CSRF Token by calling GET with x-csrf-token: fetch * @returns Promise with the result of the call */ function getCSRFToken() { const optionsGetCSRFToken = getCSRFTokenOptions(); return rp(optionsGetCSRFToken); } function getCSRFTokenOptions() { return { method: "GET", url: config.configuration.network.protocol + '://' + config.configuration.network.host + '/sap/bc/adt/abapunit/testruns', simple: false, resolveWithFullResponse: true, auth: { user: config.configuration.auth.username, password: }, headers: { 'X-CSRF-Token': 'fetch' }, insecure: config.configuration.network.insecure, rejectUnauthorized: !config.configuration.network.insecure }; } /** Runs the abap unit test and converts them to JUnit format * 1) Get CSRF Token * 2) Call Netweaver Server and get abap unit results * 3) Transform result and save to output.xml **/ function main() { config = new Config(); const { xmlRunAbapUnit, xslt } = readXml(); csrfTokenPromise = getCSRFToken(); var runAbapUnitTestPromise = csrfTokenPromise.then(function (response) { var csrfToken = response.headers['x-csrf-token']; return runAbapUnitTest(xmlRunAbapUnit,csrfToken); } ).catch(function (err) { console.error("ERROR: " + JSON.stringify(err)); } ); runAbapUnitTestPromise.then(function (parsedBody) { const xml = xsltProcessor.xmlParse(parsedBody); // xsltString: string of xslt file contents if( config.configuration.result.saveAunit ) { fs.writeFileSync(config.configuration.result.abapResultFile,parsedBody); } const outXmlString = xsltProcessor.xsltProcess(xml, xslt); // outXmlString: output xml string. fs.writeFileSync(config.configuration.result.file, outXmlString) }).catch(function (err) { console.error(err); }); } main();const SlashCommand = require("../../lib/SlashCommand"); const { MessageEmbed } = require("discord.js"); const command = new SlashCommand() .setName("loopqueue") .setDescription("Loop the queue") .setRun(async (client, interaction, options) => { let player = client.manager.players.get(interaction.guild.id); if (!player) { return interaction.reply({ embeds: [client.ErrorEmbed("There is no music playing")], }); } if (!interaction.member.voice.channel) { const joinEmbed = new MessageEmbed() .setColor(client.config.embedColor) .setDescription( "❌ | **You need to join voice channel first before you can use this command.**" ); return interaction.reply({ embeds: [joinEmbed], ephemeral: true }); } if ( interaction.guild.me.voice.channel && !interaction.guild.me.voice.channel.equals( interaction.member.voice.channel ) ) { const sameEmbed = new MessageEmbed() .setColor(client.config.embedColor) .setDescription( "❌ | **You must be in the same voice channel as me.**" ); return interaction.reply({ embeds: [sameEmbed], ephemeral: true }); } if (player.setQueueRepeat(!player.queueRepeat)); const queueRepeat = player.queueRepeat ? "enabled" : "disabled"; let loopembed = new MessageEmbed() .setColor(client.config.embedColor) .setDescription(`:thumbsup: | **Loop queue is now \`${queueRepeat}\`**`); interaction.reply({ embeds: [loopembed] }); }); module.exports = command; // Listeners chrome.runtime.onMessage.addListener(function (msg, sender, response) { document.title = msg; });export default (() => { const middlewares = [] return middleware => { if(middleware) { middlewares.push(middleware) } return middlewares } })()'use strict'; var UrgentFunctionsProxy = (function UrgentFunctionsProxyClosure() { function UrgentFunctionsProxy() { var scriptsToImport = [asyncProxy.AsyncProxyMaster.getEntryUrl() + '/scripts/callee.js']; var ctorArgs = []; this._workerHelper = new asyncProxy.AsyncProxyMaster(scriptsToImport, 'Callee', ctorArgs, { functionsBufferSize: 3 }); } UrgentFunctionsProxy.prototype.urgentFunction = function urgentFunction(callNumber) { var args = [callNumber]; this._workerHelper.callFunction('urgentFunction', args, { isSendImmediately: true }); }; UrgentFunctionsProxy.prototype.nonUrgentFunction = function nonUrgentFunction(callNumber) { var args = [callNumber]; this._workerHelper.callFunction('nonUrgentFunction', args); }; return UrgentFunctionsProxy; })();TZB-Loong/gzy-pc import React, { Component } from 'react'; import { routerRedux } from 'dva/router'; import { Card, Modal, Table, Button, Input, Select, Checkbox, DatePicker, Form, Row, Col, message, Radio, Icon, Spin, Tooltip, } from 'antd'; import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'; import {connect} from 'dva' import {getUrlParamBySearch,uuid} from '../../utils/utils' import {isfalse} from '../../Tools/util_tools' import PageHeaderLayout from '../../layouts/PageHeaderLayout'; import Styles from './style.less' import PropertySetting from './propertySetting'; import ControlView from './controlView'; import BasicSetting from '../Custom/basicSetting'; const Option = Select.Option; const { MonthPicker, RangePicker, WeekPicker } = DatePicker; const FormItem = Form.Item; const { TextArea } = Input; const RadioGroup = Radio.Group; const CheckboxGroup = Checkbox.Group; //自定义ICON const MenusIcon = Icon.createFromIconfontCN({ scriptUrl: '//at.alicdn.com/t/font_897614_s1hjnuh81g.js', // 在 iconfont.cn 自定义 }); const reorder = (list, startIndex, endIndex) => { const result = Array.from(list); const [removed] = result.splice(startIndex, 1); result.splice(endIndex, 0, removed); return result; }; //移动节点重置数据 const move = (source, destination, droppableSource, droppableDestination) => { const sourceMenu = [ { ctrlType: 'text', chnName: '单行文本', props: {"required":false,"placeholder":"请填写文本内容","options":null,"format":null,"maxLength":100,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'textarea', chnName: '多行文本', props: {"required":false,"placeholder":"请填写文本内容","options":null,"format":null,"maxLength":500,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'number', chnName: '数字', props: {"required":false,"placeholder":"请填写数字","options":null,"format":null,"maxLength":10,"defaultValue":"","rule":"","unit":'个',"readonly":false,'point':2} }, { ctrlType: 'money', chnName: '金额', props: {"required":false,"placeholder":"请填写金额","options":null,"format":null,"maxLength":10,"defaultValue":"","rule":"","unit":'元',"readonly":false,'point':2} }, { ctrlType: 'radio', chnName: '单选框', props: {"required":false,"placeholder":"请选择","options":[ {value:'选项1',checked:false}, {value:'选项2',checked:false}, {value:'选项3',checked:false}], "format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'checkbox', chnName: '多选框', props: {"required":false,"placeholder":"请选择","options":[ {value:'选项1',checked:false}, {value:'选项2',checked:false}, {value:'选项3',checked:false}], "format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'dropdown', chnName: '下拉列表', props: {"required":false,"placeholder":"请选择","options":[ {value:'选项1',checked:false}, {value:'选项2',checked:false}, {value:'选项3',checked:false}], "format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'date', chnName: '日期', props: {"required":false,"placeholder":"请选择日期","options":null,"format":'YYYY-MM-DD',"maxLength":0,"defaultValue":"none","rule":"","unit":null,"readonly":false} }, { ctrlType: 'datearea', chnName: '日期区间', props: {"required":false,"placeholder":"请选择日期区间","options":null,"format":'YYYY-MM-DD',"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'phone', chnName: '电话号码', props: {"required":false,"placeholder":"请填写电话号码","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'attach', chnName: '附件', props: {"required":false,"placeholder":"请上传附件","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'subfrom', chnName: '子表单', props: {"required":false,"placeholder":"子表单","options":[ {ctrlType: 'text', chnName: '单行文本', ctrlName: '单行文本', extentionProps: { required: false, placeholder: '请填写文本内容', options: null, format: null, maxLength: 100, defaultValue: '', rule: '', unit: null, readonly: false, }}, ],"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'www', chnName: '网址', props: {"required":false,"placeholder":"请填写网址","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'email', chnName: '邮箱', props: {"required":false,"placeholder":"请填写邮箱","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'user', chnName: '人员选择', props: {"required":false,"placeholder":"请人员选择","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'area', chnName: '地区', props: {"required":false,"placeholder":"请填写地区","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'applyPerson', chnName: '申请人', props: {"required":false,"placeholder":"请填写申请人","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":true} }, { ctrlType: 'applyTime', chnName: '申请日期', props: {"required":false,"placeholder":"申请日期","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":true} }, { ctrlType: 'chooseProject', chnName: '选择项目', props: {"required":false,"placeholder":"请选择项目","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, //{ index:19,ctrlType: 'chooseMaterialTender', chnName: '选择材料招标', props: {"required":false,"placeholder":"请选择材料招标","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, //{ index:20,ctrlType: 'chooseLabourTender', chnName: '选择劳务招标', props: {"required":false,"placeholder":"请选择劳务招标","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { index:21,ctrlType: 'chooseMaterialSupplier', chnName: '选择材料供应商', props: {"required":false,"placeholder":"请选择材料供应商","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { index:21,ctrlType: 'chooseLabourSupplier', chnName: '选择劳务供应商', props: {"required":false,"placeholder":"请选择劳务供应商","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { index:22,ctrlType: 'material', chnName: '选择材料分类', props: {"required":false,"placeholder":"请选择材料分类","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, ] const sourceClone = Array.from(sourceMenu); const destClone = Array.from(destination); const [removed] = sourceClone.splice(droppableSource.index, 1); destClone.splice(droppableDestination.index, 0, removed); const result = {}; result[droppableSource.droppableId] = source; result[droppableDestination.droppableId] = destClone; return result; }; //操作区域样式 const getItemStyle = (isDragging, draggableStyle) => ({ userSelect: 'none', background: isDragging ? '#e2f3ff' : 'transparent', ...draggableStyle }); const getItemLeftStyle = (isDragging, draggableStyle) => ({ userSelect: 'none', padding: '10px 15px', margin: `0 0 5px 0`, boxShadow:isDragging? '1px 1px 2px #666':'', background: isDragging ? '#EDFFE3' : '#fff', ...draggableStyle }); const getListStyle = isDraggingOver => ({ // border:'1px solid rgb(231, 231, 231)', // padding: grid, width: '100%', overflowY:'scroll', height:"calc(100% - 60px)", }); @Form.create() @connect(({ custom,submForm, loading }) => ({ custom,submForm, loading: loading.effects['custom/getControlList'], })) export default class DesignForms extends Component { state = { items:[], selected: [], basic: {}, require: false, type: 'ADD', checkboxIndex: null, checkboxValue: {}, }; id2List = { droppable: 'items', droppable2: 'selected', }; componentDidMount() { let nodes = document.getElementsByClassName('setHeight'); for (let i =0;nodes.length>i;i++){ nodes[i].style.height = (window.innerHeight-305)+'px' }; const {dispatch,submForm} = this.props; if(getUrlParamBySearch(window.location.href, 'bizCode')){ this.setState({ bizCode:getUrlParamBySearch(window.location.href, 'bizCode'), },()=>{this.queryForm()}) } /*if (!isfalse(submForm.listData)) { submForm.listData.map(item=>{ item.props = JSON.parse(item.extentionProps) }); this.setState({ selected: submForm.listData, }); }*/ dispatch({ type: 'custom/getControlList', }).then(()=>{ let items = this.props.custom.controlList; /*items.map((item,i)=>{ // ,.{ ctrlType: 'date', chnName: '日期', props: { placeholder: 'date' } } item.ctrlType=item.type; item.chnName=item.name; item.props= JSON.parse(item.props); Object.assign(item.props, {index:i}); }); this.setState({ items, // menu:items, },()=>{console.log(this.state)}) console.log(this.props)*/ }); if(getUrlParamBySearch(window.location.href, 'bizType')){ let params={ bizDesc:getUrlParamBySearch(window.location.href, 'bizDesc')||'', bizType:getUrlParamBySearch(window.location.href, 'bizType')||'', bizName:getUrlParamBySearch(window.location.href, 'bizName')||'', }; this.setState({ basic:params, type:getUrlParamBySearch(window.location.href, 'type'), bizCode:getUrlParamBySearch(window.location.href, 'bizCode'), },()=>{this.queryForm()}) } }; queryForm = () => { //查询数据,生成表单 const { dispatch } = this.props; dispatch({ type: 'submForm/bizObjectMetadataCustomList', payload: {bizCode:this.state.bizCode}, }).then(() => { const { submForm } = this.props; if (!isfalse(submForm.listData)) { submForm.listData.map(item=>{ let dataProps = JSON.parse(item.extentionProps); if(item.ctrlType == "subfrom" && dataProps.options){ dataProps.options.map(item=>{ item.extentionProps = JSON.parse(item.extentionProps) }) } item.props = dataProps }); this.setState({ selected: submForm.listData, }); } }); }; //提交表单设计数据 saveFormNode=(menu)=>{ const {dispatch,custom:{controlList},form} = this.props; form.validateFields((err, values) => { console.log(values) if (!err) { let data = this.state.selected; if(data.length===0){ message.info('至少包含一个业务控件!'); return } console.log(data) let params = {},MetadataList=[]; data.map((item,index)=>{ let oldctrlName = ''; for(let i =0;menu.length>i;i++){ if(item.ctrlType==menu[i].ctrlType){ oldctrlName = menu[i].chnName; } } if(item.ctrlType=='attach'){ // 生成随机附件code item.props=Object.assign({}, item.props, { attachCode: uuid() }) } MetadataList.push({ ctrlName:item.ctrlName, id:item.id, chnName:item.chnName, ctrlType:item.ctrlType, required:item.props.required, placeholder:item.props.placeholder, extentionProps:item.props, }) }); if(getUrlParamBySearch(window.location.href, 'id')){ values.bizCode=getUrlParamBySearch(window.location.href,'bizCode'); values.id=getUrlParamBySearch(window.location.href,'id'); MetadataList.map(item=>{ item.bizId = this.state.selected[0].bizId; }) } console.log(MetadataList) params.bizObject=values; params.bizObjectMetadataList=MetadataList; dispatch({ type: 'custom/saveForm', payload:params, }).then(()=>{ const {custom:{saveStatus,fromObj}} = this.props; const {type} = this.state; console.log(this.props) if(saveStatus){ let id = ''; if(getUrlParamBySearch(window.location.href, 'id')) { id = getUrlParamBySearch(window.location.href, 'id'); message.success('表单编辑成功!'); }else { id = fromObj.id; message.success('表单保存成功,请继续完成流程设计!'); } dispatch( routerRedux.push(`/processCenter/designFormNext?bizCode=`+fromObj.bizCode+ '&bizName='+params.bizObject.bizName+ '&type='+type+ '&id='+id+ '&bizDesc='+values.bizDesc+ '&bizType='+values.bizType) ); } }); } }); }; changeState(selected) { this.setState({ selected, }); } getList = id => this.state[this.id2List[id]]; onDragEnd = result => { const { source, destination } = result; if (!destination) { return; } if (source.droppableId === destination.droppableId) { const items = reorder( this.getList(source.droppableId), source.index, destination.index ); let state = { items }; if (source.droppableId === 'droppable2') { state = { selected: items }; this.setState({ checkboxIndex: result.destination.index, checkboxValue: items[result.destination.index] }); } this.setState(state); // 拖拽时修改选中值 } else { const result = move( this.getList(source.droppableId), this.getList(destination.droppableId), source, destination ); let selecteds = result.droppable2 console.log(selecteds) let submitData =[] selecteds.map((item,index)=>{ submitData.push({ id:item.id||null, chnName:item.chnName, ctrlName:item.ctrlName, ctrlType:item.ctrlType, props:item.props, index:index, }); }) console.log(submitData) this.setState({ items: result.droppable, selected: submitData, }); }/* if(source.droppableId=="droppable"){ let curSelectCtrl = this.state.selected; curSelectCtrl.push(sourceMenu[source.index]); this.setState({ selected: curSelectCtrl, }); }*/ }; //删除选择项 onRemove=(index)=>{ let selected = this.state.selected; selected.splice(index,1); this.setState({selected}) }; addCurControl=(item)=>{ let selected = this.state.selected; console.log(item) selected.map((item,index)=>{ item.index = index; }) selected.push(item); this.setState({selected},()=>{ console.log(this.state.selected) }) }; render() { let { checkboxValue } = this.state; const { getFieldDecorator } = this.props.form; const menu = [ { ctrlType: 'text', chnName: '单行文本', props: {"required":false,"placeholder":"请填写文本内容","options":null,"format":null,"maxLength":100,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'textarea', chnName: '多行文本', props: {"required":false,"placeholder":"请填写文本内容","options":null,"format":null,"maxLength":500,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'number', chnName: '数字', props: {"required":false,"placeholder":"请填写数字","options":null,"format":null,"maxLength":10,"defaultValue":"","rule":"","unit":'个',"readonly":false,'point':2} }, { ctrlType: 'money', chnName: '金额', props: {"required":false,"placeholder":"请填写金额","options":null,"format":null,"maxLength":10,"defaultValue":"","rule":"","unit":'元',"readonly":false,'point':2} }, { ctrlType: 'radio', chnName: '单选框', props: {"required":false,"placeholder":"请选择","options":[ {value:'选项1',checked:false}, {value:'选项2',checked:false}, {value:'选项3',checked:false}], "format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'checkbox', chnName: '多选框', props: {"required":false,"placeholder":"请选择","options":[ {value:'选项1',checked:false}, {value:'选项2',checked:false}, {value:'选项3',checked:false}], "format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'dropdown', chnName: '下拉列表', props: {"required":false,"placeholder":"请选择","options":[ {value:'选项1',checked:false}, {value:'选项2',checked:false}, {value:'选项3',checked:false}], "format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'date', chnName: '日期', props: {"required":false,"placeholder":"请选择日期","options":null,"format":'YYYY-MM-DD',"maxLength":0,"defaultValue":"none","rule":"","unit":null,"readonly":false} }, { ctrlType: 'datearea', chnName: '日期区间', props: {"required":false,"placeholder":"请选择日期区间","options":null,"format":'YYYY-MM-DD',"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'phone', chnName: '电话号码', props: {"required":false,"placeholder":"请填写电话号码","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'attach', chnName: '附件', props: {"required":false,"placeholder":"请上传附件","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'subfrom', chnName: '子表单', props: {"required":false,"placeholder":"子表单","options":[ {ctrlType: 'text', chnName: '单行文本', ctrlName: '单行文本', extentionProps: { required: false, placeholder: '请填写文本内容', options: null, format: null, maxLength: 100, defaultValue: '', rule: '', unit: null, readonly: false, }}, ],"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'www', chnName: '网址', props: {"required":false,"placeholder":"请填写网址","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'email', chnName: '邮箱', props: {"required":false,"placeholder":"请填写邮箱","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'user', chnName: '人员选择', props: {"required":false,"placeholder":"请人员选择","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'area', chnName: '地区', props: {"required":false,"placeholder":"请填写地区","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { ctrlType: 'applyPerson', chnName: '申请人', props: {"required":false,"placeholder":"请填写申请人","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":true} }, { ctrlType: 'applyTime', chnName: '申请日期', props: {"required":false,"placeholder":"申请日期","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":true} }, { ctrlType: 'chooseProject', chnName: '选择项目', props: {"required":false,"placeholder":"请选择项目","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, //{ index:19,ctrlType: 'chooseMaterialTender', chnName: '选择材料招标', props: {"required":false,"placeholder":"请选择材料招标","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, //{ index:20,ctrlType: 'chooseLabourTender', chnName: '选择劳务招标', props: {"required":false,"placeholder":"请选择劳务招标","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { index:21,ctrlType: 'chooseMaterialSupplier', chnName: '选择材料供应商', props: {"required":false,"placeholder":"请选择材料供应商","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { index:21,ctrlType: 'chooseLabourSupplier', chnName: '选择劳务供应商', props: {"required":false,"placeholder":"请选择劳务供应商","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, { index:22,ctrlType: 'material', chnName: '选择材料分类', props: {"required":false,"placeholder":"请选择材料分类","options":null,"format":null,"maxLength":0,"defaultValue":"","rule":"","unit":null,"readonly":false} }, ]; const {form} = this.props; const SortableList = ({ items }) => { return (
    {items.map((value, index) => ( ))} ); }; const SortableItem = ({ value, sortIndex }) => (
    {(provided, snapshot) => (
    { this.setState({ checkboxIndex: sortIndex, checkboxValue: value }); }} > this.onRemove(sortIndex)} theme="outlined" />
    )}
    ); return (
    } >

    可选控件

    点击或拖拽到预览区

    {(provided, snapshot) => (
    {menu.map((item, index) => ( {(provided, snapshot) => (
    {item.chnName} this.addCurControl(item)} className={Styles.addCurNode} type={`icon-add`}/>
    )}
    ))} {provided.placeholder}
    )}

    表单编辑区

    {(provided, snapshot) => (
    {this.state.selected.length===0?

    将控件拖拽到这里进行编辑

    :}
    )}
    ); } } import * as QUnit from "qunitjs" import {fsmContracts, NO_OUTPUT} from "../src" import {events, fsmFactory, routes} from "./contracts-fsm" // Cheapest deep equal possible // Bit beware of caveats of JSON.stringify and the JSON format! const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b); // Remove the NO_OUTPUT from the sequence of actions for comparison // (NO_OUTPUT is an implementation detail that is not part of the specifications) // It can occur when the machine traverses transient states and takes a transition without actions function removeNoOutputs(arr) { return arr.filter(x => x !== NO_OUTPUT) } function computeCleanedActualOutputs(fsm, inputSeq) { return inputSeq.map(fsm).filter(Boolean).map(removeNoOutputs); } QUnit.module("Testing home route fsm", {}); const [ROUTE_CHANGED, TAGS_FETCHED_OK, TAGS_FETCHED_NOK, ARTICLES_FETCHED_OK, ARTICLES_FETCHED_NOK] = events; const {home} = routes; const HOME_ROUTE_LOADING_SEQ = [ {[ROUTE_CHANGED]: {hash: home}} ]; const HOME_ROUTE_LOADING_SEQ_COMMANDS = [ [ { "command": "FETCH_AUTHENTICATION", "params": undefined } ] ]; const fsmMapping = [ [`Loading `, HOME_ROUTE_LOADING_SEQ, HOME_ROUTE_LOADING_SEQ_COMMANDS], ]; const fsmSettings = {debug: {console, checkContracts: fsmContracts}}; // const fsmSettings = { debug: { console } }; fsmMapping.forEach(([scenario, inputSeq, outputsSeq]) => { QUnit.test(`Home route: ${scenario}`, function exec_test(assert) { const fsm = fsmFactory(fsmSettings); const actualOutputsSeq = computeCleanedActualOutputs(fsm, inputSeq); let indexWhenFailed = -1; const isTestPassed = inputSeq.every((input, index) => { const outputs = actualOutputsSeq[index]; const expected = outputsSeq[index]; const isTestPassed = deepEqual(outputs, expected); if (!isTestPassed) { indexWhenFailed = index } return isTestPassed }); const errorMessage = `Actual outputs sequence differ from expected outputs sequence at index ${indexWhenFailed}`; const okMessage = `Alles gut!`; const message = isTestPassed ? okMessage : errorMessage; assert.deepEqual(actualOutputsSeq, outputsSeq, message); }); }); stegos/stegos-wallet10-100 // @flow import React, { Fragment, PureComponent } from 'react'; import { FormattedMessage, FormattedPlural, injectIntl } from 'react-intl'; import { formatDigit } from '../../../utils/format'; import Chart from '../../Accounts/Account/Chart/Chart'; import TransactionsList from '../../Accounts/Account/TransactionsList/TransactionsList'; import styles from './Portfolio.css'; import Stg from '../../../../resources/img/Stg.svg'; import { POWER_DIVISIBILITY } from '../../../constants/config'; import type { AccountsStateType } from '../../../reducers/types'; import { generateChartData } from '../../../utils/chart'; type Props = { accounts: AccountsStateType, intl: any }; class Portfolio extends PureComponent { static getDayName(date) { return date.toLocaleDateString('en-us', { weekday: 'short' }); } state = { period: 'week' }; get balance() { const { accounts } = this.props; return Object.entries(accounts).reduce((a, c) => a + c[1].balance, 0); } get availableBalance() { const { accounts } = this.props; return Object.entries(accounts).reduce( (a, c) => a + c[1].availableBalance, 0 ); } get lockedBalance() { const { accounts } = this.props; return Object.entries(accounts).reduce( (a, c) => a + c[1].balance - c[1].availableBalance, 0 ); } get publicBalance() { const { accounts } = this.props; return Object.entries(accounts).reduce((a, c) => a + c[1].publicBalance, 0); } get size() { const { accounts } = this.props; return Object.keys(accounts).length; } get filteredTransactions() { const { accounts } = this.props; const { period } = this.state; const transactions = Object.entries(accounts) .map(a => a[1].transactions) .reduce((arr, tr) => [...arr, ...tr], []) .sort((a, b) => b.timestamp - a.timestamp); const now = new Date(); const weekAgo = new Date().setDate(now.getDate() - 7); const monthAgo = new Date().setMonth(now.getMonth() - 1); const yearAgo = new Date().setFullYear(now.getFullYear() - 1); switch (period) { case 'week': return transactions.filter(t => t.timestamp > weekAgo); case 'month': return transactions.filter(t => t.timestamp > monthAgo); case 'year': return transactions.filter(t => t.timestamp > yearAgo); default: return transactions; } } get chartDataSource() { const { period } = this.state; return generateChartData(this.filteredTransactions, this.balance, period); } changePeriod(period: 'week' | 'month' | 'year' = 'week') { this.setState({ period }); } render() { const { period } = this.state; const { intl } = this.props; const { availableBalance, balance, lockedBalance, publicBalance, size } = this; const transactions = this.filteredTransactions; return (
    STG
    :   {formatDigit( (availableBalance / POWER_DIVISIBILITY).toFixed(4) )} STG
    :   {formatDigit((balance / POWER_DIVISIBILITY).toFixed(4))} STG
    :   {formatDigit( (lockedBalance / POWER_DIVISIBILITY).toFixed(4) )} STG
    :   {formatDigit( (publicBalance / POWER_DIVISIBILITY).toFixed(4) )} STG
    {!!transactions.length && (
    )}
    {!!transactions.length && ( )}
    ); } } export default injectIntl(Portfolio); 0 import chalk from 'chalk' export class LoggerService { contructor() { } log(...args) { const dateString = this.getFormattedDate(new Date()) console.log(`[${dateString}]`, ...args) } scopeLog(scope, ...args) { let color = 'blue' if(typeof scope !== 'string') { color = scope.color scope = scope.scope } this.log(`[${chalk[color].bold(scope)}]`, ...args) } getFormattedDate(date) { return ("0" + date.getDate()).slice(-2) + "-" + ("0"+(date.getMonth()+1)).slice(-2) + "-" + date.getFullYear() + " " + ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2); } get styler() { return chalk } } /* @flow */ import React from 'react' import { FormattedMessage } from 'react-intl' import FormGroup from 'react-bootstrap/lib/FormGroup' import FormControl from 'react-bootstrap/lib/FormControl' import ControlLabel from 'react-bootstrap/lib/ControlLabel' import { alphabets } from 'lib/alphabets' type Props = { value: string, onChange: string => void, size?: number, square?: boolean, controlId?: string } export default ({ value, onChange, size, square, controlId }: Props) => ( onChange(e.target.value)} > {alphabets({ size, square }).map(({ name, letters, description }) => ( ))} ) 1-10 const {StateService} = require('../services'); class StateController { static async find(req, res, next) { try { const states = await StateService.find(req.params.id); res.send(states.departments); } catch (err) { next(err); } } } module.exports = StateController; function carregar(){ let msg = window.document.getElementById('msg'); let imagem = window.document.getElementById('imagem'); let data = new Date(); let hora = data.getHours(); //hora = 23; msg.innerHTML = `Agora são ${hora} horas` if (hora >= 0 && hora <= 12){ //BOM DIA imagem.scr = 'fotomanha.jpg' document.body.style.background = '#fffa61'; } else if (hora > 12 && hora <= 18){ //BOA TARDE imagem.src = 'fototarde.jpg' document.body.style.background = '#c2984f'; } else { //BOA NOITE imagem.src = 'fotonoite.jpg' document.body.style.background = '#1a1933'; } } import EquipmentItem from './EquipmentItem' export default EquipmentItem AndyLZJ/anoyshopsrc/store/order.js const cart = { namespaced: true, state: { cart_add: false, isShip: { bool: false, id: null } }, mutations: { setCartAdd(state, data) { state.cart_add = data; }, setShip(state, data) { state.isShip = data; } }, getters: { getCartAdd: function (state) { return state.cart_add; }, getShip: function (state) { return state.isShip; } }, actions: {} }; export default cart; angular.module('genie.home-ctrl', []) .controller('HomeCtrl', function($scope, $state) { $scope.hello = 'hello'; $scope.go = function(route) { $state.go(route); } }); var jsonDao = require('./dao/jsonDao.js'); const Promise = require('bluebird'); // Using arrow functions. Check ES6 specs for more informations module.exports = (name) => { return new Promise(function (resolve, reject) { jsonDao.deleteContacts(name).then(() => { resolve();}).catch((e) => { console.error('Contacts module: remove=>', e); return reject(e); }); }); }pages/course.js // @flow import React from 'react'; import gql from 'graphql-tag'; import { Helmet } from 'react-helmet'; import { connect } from 'react-redux'; import { graphql } from 'react-apollo'; import { COURSE_QUERY } from 'lib/constants'; import { withRouter } from 'next/router'; import { size } from 'lodash'; import { i18n, withTranslation } from 'lib/i18n'; import withApollo from 'lib/withApollo'; import { courseBySlugFromState } from 'components/Course/selectors'; import Container from 'components/Container'; import Course from 'components/Course'; import type { GraphQLData } from 'lib/types'; type Props = { currentLanguage: ?string, data: GraphQLData, slug: string, t: Function, }; const CoursePage = (props: Props) => { const { currentLanguage, data, slug, t, } = props; return ( {`${t('title')} – ${slug}`} ); }; CoursePage.getInitialProps = async ({ query, req }) => { // TODO: figure out how to get data from apolloClient cache instead of redux // console.log('apolloClient: ', apolloClient); const { slug } = query; const currentLanguage = req ? req.language : i18n.language; return { currentLanguage, namespacesRequired: ['common', 'course'], slug }; }; const SEARCH_COURSE = gql` query CourseBySlugQuery($slug: String!) { courseBySlug(slug: $slug) { ${COURSE_QUERY} } } `; const ComponentWithMutation = graphql(SEARCH_COURSE, { options: ({ router: { query } }) => ({ variables: { slug: query.slug, }, }), props: ({ data }) => ({ data, }), skip: ({ course }) => size(course) > 0, })(CoursePage); const mapStateToProps = (state, ownProps) => ({ course: courseBySlugFromState(state, ownProps), }); export default connect(mapStateToProps)( withApollo(withRouter(withTranslation('common')(ComponentWithMutation))), ); var math = {}; math.getRandomNumber = function(min, max) { min = typeof min == 'number' && min % 1 === 0 ? min : 0; max = typeof max == 'number' && max % 1 === 0 ? max : 0; return Math.floor(Math.random() * (max - min + 1) + min); }; module.exports = math; at-voice-code-samples/yoda-voice-intro const express = require('express'); const xmlbuilder = require('xmlbuilder'); const bodyParser = require('body-parser'); //const mediaFolder = __dirname + '/media'; const app = express(); app.use(bodyParser.urlencoded({extended: true})); // we want to serve media files from our app //app.use(express.static(mediaFolder)); const appPort = 3050; // If you chose to host the file on your own machine OR vm // Make sure to pass the host name when startin the application // example DOMAIN=https://www.mydomain.com/file.mp3 // or DOMAIN=https://www.mydomain.com:3050/file.mp3 // DOMAIN=http://172.16.31.10:3050/file.mp3 // and pass that as the fileUrl //const serverFQDN = process.env.DOMAIN; const fileUrl = "https://s3.eu-west-2.amazonaws.com/at-voice-sample/play.mp3"; let callAction = ""; // Say and Play actions /** * Say * * attributes: * * voice : The voice to use man or woman. Default * * playBeep : Whether to play a beep at the end of the text-to-speech parsing. Default false * * Welcome to Africa's Talking text-to-speech service * * Play * * attributes: * * url: A valid url pointing to your media file. Accepted format is MP3 * * { res.send('It lives!'); }); app.post('/voice/sayplay', (req, res) =>{ callAction = sayPlayAction; res.send(callAction); }); app.listen(process.env.PORT || appPort, () => { console.info('We are up!'); });0 (function() { angular.module("myApp", ['ngResource']) .controller("MoviesController", function($scope, Movies) { // $scope.movies = [ // { // title: "2001: A Space Odyssey" // }, { // title: "Star wars" // } // ]; // Movies.getAllMovies() // .then(movies => $scope.movies = movies) // $scope.movies = Movies.query() $scope.movies = [ Movies.get({movieId: 369557}) ] // console.log( $scope.movies.length) // setTimeout(() => console.log( $scope.movies.length), 1000); // $scope.movies.$promise.then(() => console.log( $scope.movies.length)); }) // .service('Movies', function($http){ // this.getAllMovies = function(){ // return $http.get('/api/movies') // .then(rsp => rsp.data) // } // }); .factory('Movies', function($resource){ return $resource('/api/movies/:movieId'); }) })(); import request from 'superagent' import update from 'immutability-helper' import { APIBASE } from 'utils' import laroute from 'utils/laroute.js' // ------------------------------------ // Constants // ------------------------------------ export const LIKE_ELEMENT_POST_REQUEST = 'LIKE_ELEMENT_POST_REQUEST' export const LIKE_ELEMENT_POST_SUCCESS = 'LIKE_ELEMENT_POST_SUCCESS' export const CREATE_ELEMENT_POST_REQUEST = 'CREATE_ELEMENT_POST_REQUEST' export const CREATE_ELEMENT_POST_SUCCESS = 'CREATE_ELEMENT_POST_SUCCESS' export const GET_ELEMENT_POSTS_LOADING = 'GET_ELEMENT_POSTS_LOADING' export const GET_ELEMENT_POSTS_SUCCESS = 'GET_ELEMENT_POSTS_SUCCESS' // ------------------------------------ // Actions // ------------------------------------ // like existing element export function likeElementPost (postId = 0) { return function (dispatch, getState) { dispatch(likeElementPostRequest(postId)) const token = getState().auth.token return request.post(laroute.route('api.v1.student.community.likes.store')) .set('Accept', 'application/json') .set('Authorization', 'Bearer ' + token) .send({post_id: postId}) .set('Content-Type', 'application/json') .then(response => { dispatch(likeElementPostSuccess(response.body)) }) .catch(error => { // console.log(error) }) } } export function likeElementPostRequest (postId = 0) { return { type: LIKE_ELEMENT_POST_REQUEST, payload: postId } } export function likeElementPostSuccess (like = {}) { return { type: LIKE_ELEMENT_POST_SUCCESS, payload: like } } // create new element export function createElementPost (elementId = 0, subject = '', content = '', parentId = null) { return function (dispatch, getState) { dispatch(createElementPostRequest(elementId)) const token = getState().auth.token return request.post(laroute.route('api.v1.student.community.posts.store')) .set('Accept', 'application/json') .set('Authorization', 'Bearer ' + token) .send({ type: 'element', id: elementId, subject, content, parent_id: parentId }) .set('Content-Type', 'application/json') .then(response => { dispatch(createElementPostSuccess(response.body)) }) .catch(error => { }) } } export function createElementPostRequest (elementId = 0) { return { type: CREATE_ELEMENT_POST_REQUEST, payload: elementId } } export function createElementPostSuccess (post = {}) { return { type: CREATE_ELEMENT_POST_SUCCESS, payload: post } } // get elements export function getElementPostsSuccess (id = 0, page = 1, response = {}) { return { type: GET_ELEMENT_POSTS_SUCCESS, payload: { response, id, page } } } export function getElementPostsLoading (id = 0, page = 1) { return { type: GET_ELEMENT_POSTS_LOADING, payload: { id, page } } } export function getElementPosts (id = 0, page = 1) { return function (dispatch, getState) { const exist = getState().element_community.pagination[id] if (exist && exist.currentPage >= page) return dispatch(getElementPostsLoading(id, page)) const token = getState().auth.token return request // .get(laroute.route('api.v1.student.community.posts.index')) // .set('Authorization', 'Bearer ' + token) .get(APIBASE + '/api/community/posts') .set('x-access-token', token) .query({ postable: 'element', id, page, 'except[]': Object.keys(getState().element_community.posts)}) .set('Accept', 'application/json') .set('Content-Type', 'application/json') .then(response => { dispatch(getElementPostsSuccess(id, page, response.body)) }) .catch(error => { if (error) { } }) } } export const actions = { getElementPosts } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [CREATE_ELEMENT_POST_SUCCESS]: (state, action) => { const postable = state.pagination[action.payload.postable_id] let currentPage = 1 Object.keys(state.pagination).map(e => { Object.keys(state.pagination[e].pages).map(l => { if (state.pagination[e].pages[l].ids.findIndex(id => id === (!action.payload.parent_id ? action.payload.id : action.payload.parent_id)) > -1) { currentPage = parseInt(l, 10) } }) }) // const newtotal = parseInt(page.total + 1, 10) return Object.assign({}, state, { inserting: update(state.inserting, {$splice: [[state.inserting.findIndex(i => i === action.payload.parent_id || action.payload.id), 1]] }), posts: {...state.posts, [!action.payload.parent_id ? action.payload.id : action.payload.parent_id]: !action.payload.parent_id ? action.payload : update(state.posts[action.payload.parent_id], {replies: {$push: [action.payload]}})}, pagination: update(state.pagination, {$merge: { [action.payload.postable_id]: { total: postable.total + (action.payload.parent_id ? 0 : 1), totalPages: postable.totalPages, currentPage: postable.currentPage, pages: { ...state.pagination[action.payload.postable_id].pages, [currentPage]: { ids: !action.payload.parent_id ? update(postable.pages[currentPage].ids, {$unshift: [action.payload.id]}) : postable.pages[currentPage].ids } } } } }) }) }, [GET_ELEMENT_POSTS_SUCCESS]: (state, action) => { let _posts = {} for (let post of action.payload.response.data) { _posts = { ..._posts, [post.id]: post } } const pagination = update(state.pagination, { [action.payload.id]: { $set: { totalPages: action.payload.response.last_page, total: action.payload.response.total, currentPage: action.payload.response.current_page, pages: { ...state.pagination[action.payload.id].pages, [action.payload.page]: { ids: action.payload.response.data.map(post => post.id), isFetching: false } } } } }) return Object.assign({}, state, { posts: {...state.posts, ..._posts}, pagination }) }, [CREATE_ELEMENT_POST_REQUEST]: (state, action) => { return Object.assign(state, {inserting: update(state.inserting, {$push: [action.payload]})}) }, [LIKE_ELEMENT_POST_REQUEST]: (state, action) => { return Object.assign(state, {liking: update(state.liking, {$push: [action.payload]})}) }, [LIKE_ELEMENT_POST_SUCCESS]: (state, action) => { return Object.assign(state, {posts: update(state.posts, { [action.payload.post_id]: { likes: { $push: [action.payload] } } } ), liking: update(state.liking, {$splice: [[state.liking.findIndex(i => i === action.payload.post_id), 1]] }) }) }, [GET_ELEMENT_POSTS_LOADING]: (state, action) => { let _pages = [] const exist = state.pagination[action.payload.id] if (exist) { _pages = update(_pages, {$set: exist.pages}) } return Object.assign({}, state, { pagination: update(state.pagination, { [action.payload.id]: { $set: { totalPages: exist ? exist.totalPages : 0, total: exist ? exist.total : 0, currentPage: action.payload.page, pages: { ..._pages, [action.payload.page]: { ids: [], isFetching: true } } } } } ) }) } } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { inserting: [], liking: [], posts: {}, pagination: {} } export default function ElementPostsReducer (state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state } import { addLocaleData } from 'react-intl'; import { setUsedLocale } from '../app/appActions'; import { getLocale } from '../reducers'; import enTranslations from '../locales/en.json'; export function getDefaultTranslation() { return enTranslations; } export const availableLocales = [ 'en', 'cs', 'es', 'zh', 'fr', 'de', 'ru', 'ko', 'nl', 'sl', 'sv', 'pl', 'ar', 'tr', 'ro', 'ja', 'fil', 'th', 'lo', 'id', 'ms', 'da', 'it', 'no', 'pt', 'vi', 'el', 'bg', 'uk', 'he', 'hi', 'ca', 'et', 'as', 'ta', 'bn', 'ne', 'yo', 'hr', 'hu', ]; export const rtlLocales = ['he', 'ar', 'far', 'yi', 'ku', 'ur', 'dv', 'ha', 'ps']; export const getBrowserLocale = () => { let detectedLocale; if (typeof navigator !== 'undefined') { detectedLocale = navigator.userLanguage || navigator.language || (navigator.languages && navigator.languages[0] ? navigator.languages[0] : undefined); } if (detectedLocale) { return detectedLocale.slice(0, 2); } return undefined; }; export const getLocaleDirection = locale => (rtlLocales.includes(locale) ? 'rtl' : 'ltr'); export const getAvailableLocale = appLocale => { let locale = appLocale || 'auto'; if (appLocale === 'auto') { locale = getBrowserLocale() || 'en'; } if (availableLocales.includes(locale)) { return locale; } return 'en'; }; export const loadTranslations = async store => { const state = store.getState(); const availableLocale = getAvailableLocale(getLocale(state)); const localeDataPromise = await import(`react-intl/locale-data/${availableLocale}`); const translationsPromise = await import(`../locales/${availableLocale}.json`); const [localeData, translations] = await Promise.all([localeDataPromise, translationsPromise]); addLocaleData(localeData); global.translations = translations; store.dispatch(setUsedLocale(availableLocale)); }; ekoeryanto/pintersrc/background.js 'use strict' import { join } from 'path' import { app, protocol, BrowserWindow, Menu, Tray } from 'electron' import { createProtocol, installVueDevtools } from 'vue-cli-plugin-electron-builder/lib' import { autoUpdater } from 'electron-updater' import { server, start } from './server' const isDevelopment = process.env.NODE_ENV !== 'production' // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let win let tray let quiting // Scheme must be registered before the app is ready protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }]) if (!isDevelopment) { Menu.setApplicationMenu(null) } const icon = join(__static, 'icon.png') function createWindow () { // Create the browser window. win = new BrowserWindow({ icon, width: 800, height: 600, autoHideMenuBar: true, hasShadow: true, show: isDevelopment, alwaysOnTop: !isDevelopment, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true } }) win.removeMenu() tray = new Tray(icon) const trayMenu = Menu.buildFromTemplate([ { label: 'Settings', id: 'settings', click () { win.show() } }, { label: 'Start Server', id: 'start', click () { start() }, enabled: true }, { label: 'Stop Server', id: 'stop', click () { server.close() }, enabled: false }, { label: 'Exit', id: 'exit', role: 'quit' } ]) tray.setContextMenu(trayMenu) tray.on('double-click', () => win.show()) tray.on('click', () => trayMenu.popup()) server.on('error', error => { win.webContents.send('server.error', error) }) server.on('listening', () => { win.webContents.send('server.started', server.address()) trayMenu.getMenuItemById('stop').enabled = true trayMenu.getMenuItemById('start').enabled = false }) server.on('close', () => { if (win) { win.webContents.send('server.stoped') trayMenu.getMenuItemById('stop').enabled = false trayMenu.getMenuItemById('start').enabled = true } }) if (process.env.WEBPACK_DEV_SERVER_URL) { // Load the url of the dev server if in development mode win.loadURL(process.env.WEBPACK_DEV_SERVER_URL) if (!process.env.IS_TEST) win.webContents.openDevTools() } else { createProtocol('app') // Load the index.html when not in development win.loadURL('app://./index.html') autoUpdater.checkForUpdatesAndNotify() } win.on('closed', () => { win = null tray = null }) win.on('minimize', event => { event.preventDefault() win.hide() }) win.on('close', event => { if (!quiting) { event.preventDefault() win.hide() event.returnValue = false } }) } const appLock = app.requestSingleInstanceLock() if (!appLock) { app.quit() } else { app.on('second-instance', () => { // tried to run a second instance, we should focus our window. if (win) { if (win.isMinimized()) { win.restore() } win.focus() } }) app.on('before-quit', () => { quiting = true server.close() }) // Quit when all windows are closed. app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { server.close() app.quit() } }) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow() } }) // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', async () => { if (isDevelopment && !process.env.IS_TEST) { // Install Vue Devtools try { await installVueDevtools() } catch (e) { console.error('Vue Devtools failed to install:', e.toString()) } } createWindow() }) } // Exit cleanly on request from parent process in development mode. if (isDevelopment) { if (process.platform === 'win32') { process.on('message', data => { if (data === 'graceful-exit') { app.quit() } }) } else { process.on('SIGTERM', () => { app.quit() }) } } model/db.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const urlsSchema = new Schema({ longUrl: String, shortUrl: Number }); const Url = mongoose.model('urls', urlsSchema); exports.createNew = function(urlToAdd, done) { // check if collection is empty isCollEmpty(function(err, response) { if (err) return done(err); if (response) { // if empty, save new url document with shortUrl of 1 const url = new Url({ longUrl: urlToAdd, shortUrl: 1 }); url.save(function(err, data) { if (err) { return done(err, null); } else { return done(null, data.shortUrl); } }); } else if (!response) { // if not empty, see if longUrl already exists in collection isUrlInDB(urlToAdd, function(err, response){ if (err) return done(err); if (response) { // if it exists, return it without saving anything new return done(null, response); } else { // if not, find largest shortUrl, save new with +1 shorturl findLargestUrl(function(err, response) { const short = response + 1; const url = new Url({ longUrl: urlToAdd, shortUrl: short }); url.save(function(err, data) { if (err) { return done(err, null); } else { return done(null, data.shortUrl); } }); }); } }); } }); // Check if collection is empty function isCollEmpty(done) { Url.count(function (err, count) { if (!err && count === 0) { // is empty, return true return done(null, true); } else if (err) { // error, return error and null return done(err, null); } else { return done(null, false); } }); } // Check if url is already in collection function isUrlInDB(url, done) { Url.findOne({ longUrl: url}, function(err, data) { if (err) return done(err); if (data) { // url was already in database // get it, and return shorturl return done(null, data.shortUrl); } else { // url was not in database, return null return done(null, null); } }); } // Find shorturl of latest entry in collection function findLargestUrl(callback) { Url.find().sort({ shortUrl:-1 }).limit(1) .exec(function(err, data) { if (err) return callback(err, null); return callback(null, data[0].shortUrl); }); }; } // end createNew(); exports.findAll = function(req, res) { Url.find().lean().exec(function(err, data) { if(err) { res.render('error'); } if(data) { if(Array.isArray(data)) { let jsonObj = {}; data.forEach( el => jsonObj[el.shortUrl] = el.longUrl); res.json(jsonObj); } else { res.json(data); } } else { res.render('error'); } }) }; exports.getLongUrl = function(shortUrl, callback) { Url.findOne({ shortUrl: shortUrl}, function(err, data) { if(data) { return callback(null, data.longUrl); } else { return callback(err, null); } }); } WilliamChang80/agenku-1 import React from "react" import AgencyHomePage from "../../../components/pages/agencyPages/agencyHomePage" const AgencyPage = () => { return } export default AgencyPageconst fetch = require("node-fetch"); const fetchData = async (url) => { let val = await fetch(url) .then((res) => res.json()) .catch((err) => err); return val; }; module.exports = fetchData; const observableModule = require("data/observable"); const frameModule = require("tns-core-modules/ui/frame"); const user = require("../app-root/Users"); function LoginViewModel() { const viewModel = observableModule.fromObject({ email: "", password: "", logout: function () { user.logOut(); frameModule.topmost().navigate("login/login-page"); /* *********************************************************** * Call your custom signin logic using the email and password data. *************************************************************/ } }); return viewModel; } module.exports = LoginViewModel; // Angular script to add required skills in ad product form var app = angular.module("addProductForm", ['ngSanitize']); app.controller("ProdCtrl", function ($scope, $http) { //------------------------------------------------------------------------------------------------------// $scope.productData = [{id: 'choice1'}]; $scope.addNewProductDiv = function () { //document.getElementById("remove").style.display = "block"; var newItemNo = $scope.productData.length + 1; $scope.productData.push({'id': 'choice' + newItemNo}); //$scope.removeDiv = false; }; $scope.removeChoice = function () { var lastItem = $scope.productData.length - 1; $scope.productData.splice(lastItem); }; //------------------------------------------------------------------------------------------------------// //-----------------------------------------div for add the product specifications-------------------------------------------------------------// $scope.Data = [{id: 'choice1'}]; $scope.addNewProductSpecificationDiv = function () { //document.getElementById("remove").style.display = "block"; var newItemNo = $scope.Data.length + 1; $scope.Data.push({'id': 'choice' + newItemNo}); //$scope.removeDiv = false; }; $scope.removeProductChoice = function () { var lastItem = $scope.Data.length - 1; $scope.Data.splice(lastItem); }; //-----------------------------------------div for add the product specifications-------------------------------------------------------------// $scope.products = []; // add skill to temp $scope.addSkill = function () { $scope.errortext = ""; if (!$scope.addSkillbtn) { return; } if ($scope.products.indexOf($scope.addSkillbtn) == -1) { $scope.products.push($scope.addSkillbtn); $scope.skilJSON = JSON.stringify($scope.products); } else { $scope.errortext = "This operation is already listed."; } }; //-------------------------------------------------------------------------------------------------------------------------------- // remove skill from temp $scope.removeSkill = function (x) { $scope.errortext = ""; $scope.products.splice(x, 1); $scope.skilJSON = JSON.stringify($scope.products); }; //---------show all category $scope.showPlants = function () { //alert('hi'); $http({ method: 'get', url: BASE_URL + 'admin/dashboard/showPlants' }).then(function successCallback(response) { // Assign response category object console.log(response.data); $scope.plants = response.data; // $scope.mes=response; }); }; //------------------------------------------------------------------------------------------------------------- $scope.showPlants(); // check product type and display plant $scope.prodType = function () { if ($scope.typeSelected == "1") $scope.plantDiv = true; else $scope.plantDiv = false; }; // check raw material type // function to disable all fields $scope.InputDisable = function () { document.getElementById("rm_thick").value = ''; document.getElementById("rm_dia").value = ''; document.getElementById("rm_id").value = ''; document.getElementById("rm_od").value = ''; document.getElementById("rm_pitch").value = ''; document.getElementById("rm_weight").value = ''; document.getElementById("rm_length").value = ''; document.getElementById("rm_quantity").value = ''; document.getElementById("Drawing_no").value = ''; document.getElementById("rm_thick").disabled = true; document.getElementById("rm_dia").disabled = true; document.getElementById("rm_id").disabled = true; document.getElementById("rm_od").disabled = true; document.getElementById("rm_pitch").disabled = true; //document.getElementById("rm_weight_" + index).disabled = true; document.getElementById("rm_length").disabled = true; document.getElementById("rm_quantity").disabled = true; document.getElementById("Drawing_no").disabled = true; }; $scope.RmType = function () { $scope.getMaterialDetailsByCategory(); var type = document.getElementById("rm_type").value; //alert(index); $scope.rmSpecimen = true; // check type selected switch (type) { case '1': $scope.InputDisable(); document.getElementById("rm_thick").disabled = false; document.getElementById("rm_quantity").disabled = true; break; case '2': $scope.InputDisable(); document.getElementById("rm_dia").disabled = false; break; case '3': $scope.InputDisable(); document.getElementById("rm_thick").disabled = false; document.getElementById("rm_od").disabled = false; document.getElementById("rm_quantity").disabled = false; document.getElementById("Drawing_no").disabled = false; break; case '4': $scope.InputDisable(); document.getElementById("rm_length").disabled = false; document.getElementById("rm_id").disabled = false; document.getElementById("rm_od").disabled = false; break; case '5': $scope.InputDisable(); document.getElementById("rm_od").disabled = false; document.getElementById("rm_length").disabled = false; break; case '6': $scope.InputDisable(); document.getElementById("rm_id").disabled = false; document.getElementById("rm_pitch").disabled = false; document.getElementById("rm_quantity").disabled = false; document.getElementById("Drawing_no").disabled = false; break; case '7': $scope.InputDisable(); document.getElementById("rm_od").disabled = false; document.getElementById("rm_pitch").disabled = false; document.getElementById("rm_quantity").disabled = false; document.getElementById("Drawing_no").disabled = false; break; case '8': $scope.InputDisable(); document.getElementById("rm_id").disabled = false; document.getElementById("rm_pitch").disabled = false; document.getElementById("rm_quantity").disabled = false; document.getElementById("Drawing_no").disabled = false; break; } //$scope.enableID=true; }; // script to add multiple raw material in div $scope.rmArr = []; $scope.MachineSelectedArr = []; $scope.MachineArr = []; $scope.ProductsArr = []; $scope.machines = []; $scope.machinesSelected = []; $scope.req_materials = []; //$scope.machines = ''; //-----------------------------------------------------------------------------------------------------------------------------------// //creating array of sub products for add product master $scope.submitProduct = function () { var serial_no = $('#sr_no').val(); var item_code = $('#item_code').val(); var packingquantity_per_tray = $('#packingquantity_per_tray').val(); var net_finished_weight = $('#net_finished_weight').val(); var addedMachines_field = $('#addedMachines_field').val(); var addedRM_field = $('#addedRM_field').val(); //alert(net_finished_weight); var machine_details = $scope.MachineArr; var machineSelected_details = $scope.MachineSelectedArr; var requiredMaterial = $scope.rmArr; if (!serial_no) { $scope.errorForProductDetails = "

    Please Add Item Serial No.!

    "; return; } if (!item_code) { $scope.errorForProductDetails = "

    Please Add Item Code.!

    "; return; } if (!packingquantity_per_tray) { $scope.errorForProductDetails = "

    Please Add Item's Packing Quantity Per Tray.!

    "; return; } if (!net_finished_weight) { $scope.errorForProductDetails = "

    Please Add Item's Net Finished Weight.!

    "; return; } if (!machine_details) { $scope.errorForProductDetails = "

    Please Select Item's Required Machines Details.!

    "; return; } if (!requiredMaterial) { $scope.errorForProductDetails = "

    Please Select And Add Item's Required Raw Material.!

    "; return; } // $scope.ProductsArr.push({ // serial_no: serial_no, // item_code: item_code, // machine_details: machine_details, // machineSelected_details: machineSelected_details, // packingquantity_per_tray: packingquantity_per_tray, // net_finished_weight: net_finished_weight, // requiredMaterial: requiredMaterial // }); // $scope.addedProducts = ($scope.ProductsArr); $scope.errorForProductDetails = ''; addedMachines_field = ''; addedRM_field = ''; $scope.productsDiv = 'true'; $scope.getAllProducts(serial_no, item_code, $scope.MachineArr, $scope.MachineSelectedArr, packingquantity_per_tray, net_finished_weight, $scope.rmArr); $('#packingquantity_per_tray').val(''); $('#net_finished_weight').val(''); $('#sr_no').val(''); $('#item_code').val(''); // $("#operations option:selected").text(''); // $("#machine option:selected").text(''); $("#qtyhr").val(''); // $("#rm_type option:selected").text(''); // $("#rm_grade option:selected").text(''); document.getElementById("rm_thick").value = ''; document.getElementById("rm_dia").value = ''; document.getElementById("rm_id").value = ''; document.getElementById("rm_od").value = ''; document.getElementById("rm_pitch").value = ''; document.getElementById("rm_weight").value = ''; document.getElementById("rm_length").value = ''; document.getElementById("rm_quantity").value = ''; document.getElementById("Drawing_no").value = ''; $scope.MachineArr = []; $scope.MachineSelectedArr = []; $scope.rmArr = []; }; $scope.AllProduct = []; $scope.getAllProducts = function (serial_no, item_code, machine_details, machineSelected_details, packingquantity_per_tray, net_finished_weight, requiredMaterial) { $scope.AllProduct.push({ serial_no: serial_no, item_code: item_code, machine_details: machine_details, machineSelected_details: machineSelected_details, packingquantity_per_tray: packingquantity_per_tray, net_finished_weight: net_finished_weight, requiredMaterial: requiredMaterial }); $scope.addedProducts = ($scope.AllProduct); }; $scope.removeProductDetails = function (x) { $scope.errorForProductDetails = ""; $scope.AllProduct.splice(x, 1); $scope.addedProducts = JSON.stringify($scope.AllProduct); }; //---------------------------------------------------------------------------------------------------------------------------------------------- $scope.addMachineDetails = function () { var operations = document.getElementById("operations").value; var machine = document.getElementById("machine").value; var qtyhr = document.getElementById("qtyhr").value; var operationSelected = $("#operations option:selected").text(); var machineSelected = $("#machine option:selected").text(); var qtyhrAdded = $("#qtyhr").val(); //alert(operationSelected); if (!operations) { $scope.errorMachine = "

    Please select Raw Material Type!

    "; return; } if (!machine) { $scope.errorMachine = "

    Please Select Machine name and Type!

    "; return; } if (!qtyhr) { $scope.errorMachine = "

    Quantity Per Hour required!

    "; return; } $scope.MachineArr.push({ operations: operations, machine: machine, qtyhr: qtyhr }); $scope.MachineSelectedArr.push({ operationSelected: operationSelected, machineSelected: machineSelected, qtyhrAdded: qtyhrAdded }); $scope.addedMachines = ($scope.MachineArr); $scope.addedMachineSelectedArr = ($scope.MachineSelectedArr); $scope.errorMachine = ""; operations = ''; machine = ''; qtyhr = ''; $scope.machineDiv = 'true'; //alert($scope.machineDiv); }; // remove material from temp table $scope.removeMachineDetails = function (x) { //alert(x); $scope.errorMachine = ""; $scope.MachineArr.splice(x, 1); $scope.addedMachines = JSON.stringify($scope.MachineArr); $scope.MachineSelectedArr.splice(x, 1); $scope.addedMachineSelectedArr = JSON.stringify($scope.MachineSelectedArr); }; //---------------------------------------------------------------------------------------------------------------------------------------------- // add skill to temp $scope.addRM = function () { //alert(index); var type = document.getElementById("rm_type").value; var grade = document.getElementById("rm_grade").value; var thickness = document.getElementById("rm_thick").value; var diameter = document.getElementById("rm_dia").value; var id = document.getElementById("rm_id").value; var od = document.getElementById("rm_od").value; var pitch = document.getElementById("rm_pitch").value; var weight = document.getElementById("rm_weight").value; var length = document.getElementById("rm_length").value; var quantity = document.getElementById("rm_quantity").value; var drawing_no = document.getElementById("Drawing_no").value; if (!type) { $scope.errorRM = "

    Please select Raw Material Type!

    "; return; } if (!grade) { $scope.errorRM = "

    Raw Material Grade is required!

    "; return; } if (!weight) { $scope.errorRM = "

    Raw Material Weight (in KGs) is required!

    "; return; } if (!thickness) { thickness = 0; } if (!diameter) { diameter = 0; } if (!id) { id = 0; } if (!od) { od = 0; } if (!pitch) { pitch = 0; } if (!length) { length = 0; } if (!quantity) { quantity = 0; } if (!drawing_no) { drawing_no = 0; } $scope.rmArr.push({ rm_type: type, rmgradeSelected: grade, rmthickSelected: thickness, rmdiaSelected: diameter, rmIDSelected: id, rmODSelected: od, rmPitchSelected: pitch, rmweightSelected: weight, rmlenSelected: length, rmqtySelected: quantity, rmdrawingSelected: drawing_no }); $scope.addedRM = ($scope.rmArr); $scope.errorRM = ""; grade = ''; weight = ''; thickness = ''; diameter = ''; id = ''; od = ''; pitch = ''; length = ''; quantity = ''; drawing_no = ''; $scope.rm_table = 'true'; }; // remove material from temp table $scope.removeMaterial = function (x) { $scope.errorRM = ""; $scope.rmArr.splice(x, 1); $scope.addedRM = JSON.stringify($scope.rmArr); }; //---------------------------------------------------------------------------------------------------------------------------------------------- $scope.getMaterialDetailsByCategory = function () { var material_category = $("#rm_type").val(); $.ajax({ type: "GET", url: BASE_URL + "materials/addmaterial/getMaterialDetailsByCategory", data: { material_category: material_category }, cache: false, success: function (data) { $("#rm_grade").empty(); $("#rm_grade").append(data); } }); }; $scope.getQuantityPerHr = function () { var machine_id = $("#machine").val(); $.ajax({ type: "GET", url: BASE_URL + "admin/machine/addmachine/getQuantityPerHr", data: { machine_id: machine_id }, cache: false, success: function (data) { if (data != '') { $('#qtyhr').val(data); } } }); }; }); // ------------POST form data to PHP controller-------------- $(function () { $("#addProduct").submit(function () { dataString = $("#addProduct").serialize(); // alert(dataString); $.ajax({ type: "POST", url: BASE_URL + "admin/products/addproduct/addNewProduct", dataType: 'text', data: dataString, return: false, //stop the actual form post !important! beforeSend: function () { $("#submitForm").attr("disabled", true); $('#submitForm').html(' Saving New Product details, Hold on... '); }, success: function (data) { //$.alert(data); $('#formOutput').html(data); //$('form :input').val(""); $('#submitForm').removeAttr("disabled"); $('#submitForm').html(' Save and Add New Product '); }, error: function (data) { $('#submitForm').removeAttr("disabled"); $('#formOutput').html('
    ×Failure! Something went wrong. Please refresh the page and try once again.
    '); $('#submitForm').html(' Save and Add New Product '); window.setTimeout(function () { $(".alert").fadeTo(500, 0).slideUp(500, function () { $(this).remove(); }); }, 5000); } }); return false; //stop the actual form post !important! }); }); // POST method to add product ends here-------------------------- // Angular js for all product view // Angular script to add required skills in ad product form var app = angular.module("allProductApp", ['ngSanitize']); app.controller("allProdCtrl", function ($scope, $http, $window) { // remove product from table $scope.removeProduct = function (prod_id) { $.confirm({ title: '

    Please confirm the action!

    Do yo really want to delete this product?', content: '', type: 'red', buttons: { confirm: function () { $http({ method: 'get', url: BASE_URL + 'admin/products/allproduct/delProduct', params: {prod_id: prod_id}, }).then(function successCallback(response) { $scope.message = response.data; $window.setTimeout(function () { $(".alert").fadeTo(500, 0).slideUp(500, function () { $(this).remove(); }); location.reload(); }, 2000); }); }, cancel: function () { } } }); }; });import { constantsKeyValuePairs, namesKeyValuePairs, abbreviationsKeyValuePairs, locationsKeyValuePairs, stringToKeyValuePairs, convertToTitleCase, convertToSentenceCase, } from '../src/constants.js'; const $ = require('jquery'); describe('constants file tests', function () { test('stringToKeyValuePairs', () => { expect(stringToKeyValuePairs({}, 'blah')).toStrictEqual({ blah: 'blah' }); }); test('convertToTitleCase', () => { expect(convertToTitleCase({ whats: "what's" })).toStrictEqual({ Whats: "What's", }); }); test('convertToSentenceCase', () => { expect(convertToSentenceCase({ np: 'no problem' })).toStrictEqual({ Np: 'No problem', }); }); }); /** * Pricing Block Wrapper */ // Setup the block const { Component } = wp.element; // Import block dependencies and components import classnames from 'classnames'; /** * Create a Pricing wrapper Component */ export default class Pricing extends Component { constructor( props ) { super( ...arguments ); } render() { // Setup the attributes const { attributes: { columns, align }, } = this.props; const className = classnames( [ this.props.className, 'ab-pricing-columns-' + columns ], { [ 'align' + align ]: align, } ); return (
    { this.props.children }
    ); } } leftstick/wetalk-server 'use strict'; var UserPool = require('../chat/UserPool'); class UserConnection{ constructor(socket, event){ this.socket = socket; this.event = event; this.user = null; } initialize(id){ this.user = UserPool.get(id); this.event.emit('user-added', this.socket, this.user); } start(){ this.socket .on('init', this.initialize.bind(this)) .on('message', this.message.bind(this)) .on('disconnect', this.destroy.bind(this)); return this; } message(message){ this.event.emit('send-message', this.socket, message); } destroy(){ this.event.emit('user-offline', this.socket, this); } json(){ return this.user && this.user.json(); } } module.exports = UserConnection; G0li4th/cactbot 'use strict'; let Options = { Language: 'en', RefreshRateMs: 1000, PopSound: '../../resources/sounds/PowerAuras/sonar.ogg', PopVolume: 1.0, SuppressPopMs: 1700 * 1000, FlagTimeoutMs: 60000, ZoneInfo: { 'Eureka Anemos': { mapImage: 'anemos.png', mapWidth: 1300, mapHeight: 950, primaryWeather: ['Gales'], // TODO: these could be a little better tuned :C mapToPixelXScalar: 41.12, mapToPixelXConstant: -224.7, mapToPixelYScalar: 41.09, mapToPixelYConstant: -457.67, entityToMapXScalar: .02002870754, entityToMapXConstant: 21.45210725, entityToMapYScalar: .02000892816, entityToMapYConstant: 21.4665545, nms: { sabo: { label: { en: 'Sabo', de: 'Sabo', fr: 'Pampa', ja: 'サボ', }, mobName: { en: 'Sabotender Corrido', de: 'Sabotender Corrido', fr: 'Pampa Corrido', ja: 'サボテンダー・コリード', }, trackerName: { en: 'Sabo', de: 'Sabo', fr: 'Pampa', ja: 'サボテンダー', }, x: 13.9, y: 21.9, }, lord: { label: { en: 'Lord', de: 'Prinz', fr: 'Seigneur', ja: 'ロード', }, mobName: { en: 'The Lord Of Anemos', de: '', fr: 'Seigneur D\'anemos', ja: 'ロード・オブ・アネモス', }, trackerName: { en: 'Lord', de: 'Prinz[p]', fr: 'Seigneur', ja: 'ロード', }, x: 29.7, y: 27.1, }, teles: { label: { en: 'Teles', de: 'Teles', fr: 'Teles', ja: 'テレス', }, mobName: { en: 'Teles', de: 'Teles', fr: 'Teles', ja: 'テレス', }, trackerName: { en: 'Teles', de: 'Teles', fr: 'Teles', ja: 'テレス', }, x: 25.6, y: 27.4, }, emperor: { label: { en: 'Emp', de: 'Kaiser', fr: 'Emp', ja: 'アネモス', }, mobName: { en: 'The Emperor Of Anemos', de: 'Anemos-Kaiser', fr: '', ja: 'アネモス・エンペラー', }, trackerName: { en: 'Emperor', de: 'Kaiser', fr: 'Empereur', ja: 'アネモス', }, x: 17.2, y: 22.2, }, callisto: { label: { en: 'Calli', de: 'Callisto', fr: 'Callisto', ja: 'カリスト', }, mobName: { en: 'Callisto', de: 'Callisto', fr: 'Callisto', ja: 'カリスト', }, trackerName: { en: 'Callisto', de: 'Callisto', fr: 'Callisto', ja: 'カリスト', }, // 25.5, 22.3 from the tracker, but collides with number x: 26.2, y: 22.0, }, number: { label: { en: 'Number', de: 'Zahl', fr: 'Number', ja: 'ナンバーズ', }, mobName: { en: 'Number', de: 'Zahl', fr: 'Number', ja: 'ナンバーズ', }, trackerName: { en: 'Number', de: 'Zahl', fr: 'Number', ja: 'ナンバーズ', }, // 23.5, 22.7 from the tracker, but collides with callisto x: 23.5, y: 23.4, }, jaha: { label: { en: 'Jaha', de: 'Jaha', fr: 'Jaha', ja: 'ジャハ', }, mobName: { en: 'Jahannam', de: 'Jahannam', fr: 'Jahannam', ja: 'ジャハンナム', }, trackerName: { en: 'Jaha', de: 'Jaha', fr: 'Jaha', ja: 'ジャハンナム', }, x: 17.7, y: 18.6, weather: 'Gales', }, amemet: { label: { en: 'Amemet', de: 'Amemet', fr: 'Amemet', ja: 'アミメット', }, mobName: { en: 'Amemet', de: 'Amemet', fr: 'Amemet', ja: 'アミメット', }, trackerName: { en: 'Amemet', de: 'Amemet', fr: 'Amemet', ja: 'アミメット', }, x: 15.0, y: 15.6, }, caym: { label: { en: 'Caym', de: 'Caym', fr: 'Caym', ja: 'カイム', }, mobName: { en: 'Caym', de: 'Caym', fr: 'Caym', ja: 'カイム', }, trackerName: { en: 'Caym', de: 'Caym', fr: 'Caym', ja: 'カイム', }, x: 13.8, y: 12.5, }, bomb: { label: { en: 'Bomb', de: 'Bomba', fr: 'Bomba', ja: 'ボンバ', }, mobName: { en: 'Bombadeel', de: 'Bombadeel', fr: 'Bombadeel', ja: 'ボンバディール', }, trackerName: { en: 'Bomba', de: 'Bomba', fr: 'Bomba', ja: 'ボンバディール', }, x: 28.3, y: 20.4, time: 'Night', }, serket: { label: { en: 'Serket', de: 'Serket', fr: 'Serket', ja: 'セルケト', }, mobName: { en: 'Serket', de: 'Serket', fr: 'Serket', ja: 'セルケト', }, trackerName: { en: 'Serket', de: 'Serket', fr: 'Serket', ja: 'セルケト', }, x: 24.8, y: 17.9, }, juli: { label: { en: 'Juli', de: 'Julika', fr: 'Julika', ja: 'ジュリカ', }, mobName: { en: '', de: '', fr: 'Julika', ja: 'ジャッジメンタル・ジュリカ', }, trackerName: { en: 'Julika', de: 'Julika', fr: 'Julika', ja: 'ジュリカ', }, x: 21.9, y: 15.6, }, rider: { label: { en: 'Rider', de: 'Reiter', fr: 'Cavalier', ja: 'ライダー', }, mobName: { en: 'The ', de: '', fr: 'C', ja: 'ホワイトライダー', }, trackerName: { en: 'Rider', de: 'Reiter', fr: 'Cavalier', ja: 'ホワイトライダー', }, x: 20.3, y: 13.0, time: 'Night', }, poly: { label: { en: 'Poly', de: 'Poly', fr: 'Poly', ja: 'ポリ', }, mobName: { en: 'Polyphemus', de: 'Polyphemus', fr: 'Polyphemus', ja: 'ポリュペモス', }, trackerName: { en: 'Poly', de: 'Poly', fr: 'Poly', ja: 'ポリュペモス', }, x: 26.4, y: 14.3, }, strider: { label: { en: 'Strider', de: 'Simurghs', fr: 'Simurgh', ja: 'シームルグ', }, mobName: { en: '', de: '', fr: '', ja: 'シームルグ・ストライダー', }, trackerName: { en: 'Strider', de: 'Simurghs', fr: 'Simurgh', ja: 'シームルグ', }, x: 28.6, y: 13.0, }, hazmat: { label: { en: 'Hazmat', de: 'Hazmat', fr: 'Hazmat', ja: 'ハズマット', }, mobName: { en: '', de: 'Hazmat-König', fr: '', ja: 'キング・ハズマット', }, trackerName: { en: 'Hazmat', de: 'Hazmat', fr: 'Hazmat', ja: 'ハズマット', }, x: 35.3, y: 18.3, }, fafnir: { label: { en: 'Fafnir', de: 'Fafnir', fr: 'Fafnir', ja: 'ファヴニル', }, mobName: { en: 'Fafnir', de: 'Fafnir', fr: 'Fafnir', ja: 'ファヴニル', }, trackerName: { en: 'Fafnir', de: 'Fafnir', fr: 'Fafnir', ja: 'ファヴニル', }, x: 35.5, y: 21.5, time: 'Night', }, amarok: { label: { en: 'Amarok', de: 'Amarok', fr: 'Amarok', ja: 'アマロック', }, mobName: { en: 'Amarok', de: 'Amarok', fr: 'Amarok', ja: 'アマロック', }, trackerName: { en: 'Amarok', de: 'Amarok', fr: 'Amarok', ja: 'アマロック', }, x: 7.6, y: 18.2, }, lama: { label: { en: 'Lama', de: 'Lama', fr: 'Lama', ja: 'ラマ', }, mobName: { en: 'Lamashtu', de: 'Lamashtu', fr: 'Lamashtu', ja: 'ラマシュトゥ', }, trackerName: { en: 'Lamashtu', de: 'Lamashtu', fr: 'Lamashtu', ja: 'ラマシュトゥ', }, // 7.7, 23.3 from the tracker but mobs are farther south. x: 7.7, y: 25.3, time: 'Night', }, pazu: { label: { en: 'Pazu', de: 'Pazuzu', fr: 'Pazuzu', ja: 'パズズ', }, mobName: { en: 'Pazuzu', de: 'Pazuzu', fr: 'Pazuzu', ja: 'パズズ', }, trackerName: { en: 'Pazuzu', de: 'Pazuzu', fr: 'Pazuzu', ja: 'パズズ', }, x: 7.4, y: 21.7, weather: 'Gales', }, }, }, 'Eureka Pagos': { mapImage: 'pagos.png', mapWidth: 1500, mapHeight: 950, primaryWeather: ['Blizzards', 'Thunder', 'Fog'], mapToPixelXScalar: 41.08333, mapToPixelXConstant: -85.28333, mapToPixelYScalar: 41.09158, mapToPixelYConstant: -370.196, entityToMapXScalar: 0.02, entityToMapXConstant: 21.48, entityToMapYScalar: 0.02, entityToMapYConstant: 21.48, nms: { snowqueen: { label: { en: 'Queen', de: 'Snow Queen', fr: 'Snow Queen', ja: 'Snow Queen', }, mobName: { en: 'The Snow Queen', de: 'The Snow Queen', fr: 'The Snow Queen', ja: 'The Snow Queen', }, trackerName: { en: 'Snow Queen', de: 'Snow Queen', fr: 'Snow Queen', ja: 'Snow Queen', }, x: 21.5, y: 26.5, }, taxim: { label: { en: 'Taxim', de: 'Taxim', fr: 'Taxim', ja: 'Taxim', }, mobName: { en: 'Taxim', de: 'Taxim', fr: 'Taxim', ja: 'Taxim', }, trackerName: { en: 'Taxim', de: 'Taxim', fr: 'Taxim', ja: 'Taxim', }, x: 25.5, y: 28.3, time: 'Night', }, ashdragon: { label: { en: 'Dragon', de: 'Ash Dragon', fr: 'Ash Dragon', ja: 'Ash Dragon', }, mobName: { en: 'Ash Dragon', de: 'Ash Dragon', fr: 'Ash Dragon', ja: 'Ash Dragon', }, trackerName: { en: 'Ash Dragon', de: 'Ash Dragon', fr: 'Ash Dragon', ja: 'Ash Dragon', }, x: 29.7, y: 30.0, }, glavoid: { label: { en: 'Glavoid', de: 'Glavoid', fr: 'Glavoid', ja: 'Glavoid', }, mobName: { en: 'Glavoid', de: 'Glavoid', fr: 'Glavoid', ja: 'Glavoid', }, trackerName: { en: 'Glavoid', de: 'Glavoid', fr: 'Glavoid', ja: 'Glavoid', }, x: 33.0, y: 28.0, }, anapos: { label: { en: 'Anapos', de: 'Anapos', fr: 'Anapos', ja: 'Anapos', }, mobName: { en: 'Anapos', de: 'Anapos', fr: 'Anapos', ja: 'Anapos', }, trackerName: { en: 'Anapos', de: 'Anapos', fr: 'Anapos', ja: 'Anapos', }, x: 33.0, y: 21.5, weather: 'Fog', }, hakutaku: { label: { en: 'Haku', de: 'Hakutaku', fr: 'Hakutaku', ja: 'Hakutaku', }, mobName: { en: 'Hakutaku', de: 'Hakutaku', fr: 'Hakutaku', ja: 'Hakutaku', }, trackerName: { en: 'Hakutaku', de: 'Hakutaku', fr: 'Hakutaku', ja: 'Hakutaku', }, x: 29.0, y: 22.5, }, igloo: { label: { en: 'Igloo', de: 'Igloo', fr: 'Igloo', ja: 'Igloo', }, mobName: { en: 'King Igloo', de: 'King Igloo', fr: 'King Igloo', ja: 'King Igloo', }, trackerName: { en: 'Igloo', de: 'Igloo', fr: 'Igloo', ja: 'Igloo', }, x: 17, y: 16, }, asag: { label: { en: 'Asag', de: 'Asag', fr: 'Asag', ja: 'Asag', }, mobName: { en: 'Asag', de: 'Asag', fr: 'Asag', ja: 'Asag', }, trackerName: { en: 'Asag', de: 'Asag', fr: 'Asag', ja: 'Asag', }, x: 11.3, y: 10.5, }, surabhi: { label: { en: 'Surabhi', de: 'Surabhi', fr: 'Surabhi', ja: 'Surabhi', }, mobName: { en: 'Surabhi', de: 'Surabhi', fr: 'Surabhi', ja: 'Surabhi', }, trackerName: { en: 'Surabhi', de: 'Surabhi', fr: 'Surabhi', ja: 'Surabhi', }, x: 10.5, y: 20.5, }, kingarthro: { label: { en: 'Arthro', de: 'King Arthro', fr: 'King Arthro', ja: 'King Arthro', }, mobName: { en: 'King Arthro', de: 'King Arthro', fr: 'King Arthro', ja: 'King Arthro', }, trackerName: { en: 'King Arthro', de: 'King Arthro', fr: 'King Arthro', ja: 'King Arthro', }, x: 8.0, y: 15.2, }, minotaurs: { label: { en: 'Minotaurs', de: 'Minotaurs', fr: 'Minotaurs', ja: 'Minotaurs', }, mobName: { en: 'Mindertaur', de: 'Mindertaur', fr: 'Mindertaur', ja: 'Mindertaur', }, trackerName: { en: 'Minotaurs', de: 'Minotaurs', fr: 'Minotaurs', ja: 'Minotaurs', }, x: 13.8, y: 18.4, }, holycow: { label: { en: 'Holy Cow', de: 'Holy Cow', fr: 'Holy Cow', ja: 'Holy Cow', }, mobName: { en: 'Holy Cow', de: 'Holy Cow', fr: 'Holy Cow', ja: 'Holy Cow', }, trackerName: { en: 'Holy Cow', de: 'Holy Cow', fr: 'Holy Cow', ja: 'Holy Cow', }, x: 26, y: 16, }, hadhayosh: { label: { en: 'Hadha', de: 'Hadhayosh', fr: 'Hadhayosh', ja: 'Hadhayosh', }, mobName: { en: 'Hadhayosh', de: 'Hadhayosh', fr: 'Hadhayosh', ja: 'Hadhayosh', }, trackerName: { en: 'Hadhayosh', de: 'Hadhayosh', fr: 'Hadhayosh', ja: 'Hadhayosh', }, weather: 'Thunder', x: 30, y: 19, }, horus: { label: { en: 'Horus', de: 'Horus', fr: 'Horus', ja: 'Horus', }, mobName: { en: 'Eye of Horus', de: 'Eye of Horus', fr: 'Eye of Horus', ja: 'Eye of Horus', }, trackerName: { en: 'Horus', de: 'Horus', fr: 'Horus', ja: 'Horus', }, weather: 'Heat Waves', x: 26, y: 20, }, mainyu: { label: { en: 'Mainyu', de: 'Mainyu', fr: 'Mainyu', ja: 'Mainyu', }, mobName: { en: 'Arch Angra Mainyu', de: 'Arch Angra Mainyu', fr: 'Arch Angra Mainyu', ja: 'Arch Angra Mainyu', }, trackerName: { en: 'Mainyu', de: 'Mainyu', fr: 'Mainyu', ja: 'Mainyu', }, x: 25, y: 24, }, cassie: { label: { en: 'Cassie', de: 'Cassie', fr: 'Cassie', ja: 'Cassie', }, mobName: { en: '', de: '', fr: 'Copycat Cassie', ja: '', }, trackerName: { en: 'Cassie', de: 'Cassie', fr: 'Cassie', ja: 'Cassie', }, weather: 'Blizzards', x: 22, y: 14, }, louhi: { label: { en: 'Louhi', de: 'Louhi', fr: 'Louhi', ja: 'Louhi', }, mobName: { en: 'Louhi', de: 'Louhi', fr: 'Louhi', ja: 'Louhi', }, trackerName: { en: 'Louhi', de: 'Louhi', fr: 'Louhi', ja: 'Louhi', }, x: 36, y: 18.5, }, }, }, }, }; let gFlagRegex = Regexes.Parse(/00:00..:(.*)Eureka (?:Anemos|Pagos) \( (\y{Float})\s*, (\y{Float}) \)(.*$)/); let gTrackerRegex = Regexes.Parse(/(?:https:\/\/)?ffxiv-eureka\.com\/(\S*)\/?/); let gImportRegex = Regexes.Parse(/00:00..:(.*)NMs on cooldown: (\S.*\))/); let gWeatherIcons = { 'Gales': '🌀', 'Fog': '☁', 'Blizzards': '❄', 'Thunder': '⚡', 'Heat Waves': '☀', }; let gNightIcon = '🌙'; let gDayIcon = '☀'; let gTracker; class EurekaTracker { constructor(options) { this.options = options; this.zoneInfo = null; this.ResetZone(); this.updateTimesHandle = null; } SetStyleFromMap(style, mx, my) { if (mx === undefined) { style.display = 'none'; return; } let zi = this.zoneInfo; let px = zi.mapToPixelXScalar * mx + zi.mapToPixelXConstant; let py = zi.mapToPixelYScalar * my + zi.mapToPixelYConstant; style.left = (px / zi.mapWidth * 100) + '%'; style.top = (py / zi.mapHeight * 100) + '%'; } SetStyleFromEntity(style, ex, ey) { let zi = this.zoneInfo; let mx = zi.entityToMapXScalar * ex + zi.entityToMapXConstant; let my = zi.entityToMapYScalar * ey + zi.entityToMapYConstant; this.SetStyleFromMap(style, mx, my); } InitNMs() { this.nms = this.options.ZoneInfo[this.zoneName].nms; this.nmKeys = Object.keys(this.nms); let container = document.getElementById('nm-labels'); for (let i = 0; i < this.nmKeys.length; ++i) { let nm = this.nms[this.nmKeys[i]]; let label = document.createElement('div'); label.classList.add('nm'); label.id = this.nmKeys[i]; this.SetStyleFromMap(label.style, nm.x, nm.y); let icon = document.createElement('span'); icon.classList.add('nm-icon'); let name = document.createElement('span'); name.classList.add('nm-name'); name.classList.add('text'); name.innerText = nm.label[this.options.Language]; let time = document.createElement('span'); time.classList.add('nm-time'); time.classList.add('text'); label.appendChild(icon); label.appendChild(name); label.appendChild(time); container.appendChild(label); nm.element = label; nm.timeElement = time; let mobName = nm.mobName[this.options.Language]; nm.addRegex = Regexes.Parse('03:Added new combatant ' + mobName + '\\.'); nm.removeRegex = Regexes.Parse('04:Removing combatant ' + mobName + '\\.'); nm.respawnTimeMsLocal = undefined; nm.respawnTimeMsTracker = undefined; } this.playerElement = document.createElement('div'); this.playerElement.classList.add('player'); container.appendChild(this.playerElement); } ResetZone() { let container = document.getElementById('nm-labels'); container.innerHTML = ''; this.currentTracker = null; } OnPlayerChange(e) { if (!this.zoneInfo) return; this.SetStyleFromEntity(this.playerElement.style, e.detail.pos.x, e.detail.pos.y); } OnZoneChange(e) { this.zoneName = e.detail.zoneName; if (this.zoneName == 'Unknown Zone (2Fb)') this.zoneName = 'Eureka Pagos'; this.zoneInfo = this.options.ZoneInfo[this.zoneName]; let container = document.getElementById('container'); if (this.zoneInfo) { this.ResetZone(); document.getElementById('map-image').src = this.zoneInfo.mapImage; this.InitNMs(); this.UpdateTimes(); container.classList.remove('hide'); this.updateTimesHandle = window.setInterval((function() { this.UpdateTimes(); }).bind(this), this.options.RefreshRateMs); } else { if (this.updateTimesHandle) window.clearInterval(this.updateTimesHandle); container.classList.add('hide'); } let flags = document.getElementById('flag-labels'); for (let i = 0; i < flags.children.length; ++i) flags.removeChild(flags.children[i]); } RespawnTime(nm) { let respawnTimeMs = 120 * 60 * 1000; return respawnTimeMs + (+new Date()); } OnPopNM(nm) { let now = +new Date(); if (nm.lastPopTimeMsLocal && now - nm.lastPopTimeMsLocal <= this.options.SuppressPopMs) return; nm.element.classList.add('nm-pop'); nm.element.classList.remove('nm-down'); let respawnTimeMs = 120 * 60 * 1000; nm.lastPopTimeMsLocal = +new Date(); nm.respawnTimeMsLocal = this.RespawnTime(nm); if (this.options.PopSound && this.options.PopVolume) { let audio = new Audio(this.options.PopSound); audio.volume = this.options.PopVolume; audio.play(); } } OnKillNM(nm) { nm.element.classList.remove('nm-pop'); this.UpdateTimes(); } UpdateTimes() { let nowMs = +new Date(); for (let i = 0; i < 5; ++i) { let primaryWeather = this.options.ZoneInfo[this.zoneName].primaryWeather[i]; if (!primaryWeather) { document.getElementById('label-weather' + i).innerHTML = ''; continue; } let weatherStr = gWeatherIcons[primaryWeather]; let weather = getWeather(nowMs, this.zoneName); if (weather == primaryWeather) { let stopTime = findNextWeatherNot(nowMs, this.zoneName, primaryWeather); if (stopTime) { let min = (stopTime - nowMs) / 1000 / 60; weatherStr += ' for ' + Math.ceil(min) + 'm'; } else { weatherStr += ' for ???'; } } else { let startTime = findNextWeather(nowMs, this.zoneName, primaryWeather); if (startTime) { let min = (startTime - nowMs) / 1000 / 60; weatherStr += ' in ' + Math.ceil(min) + 'm'; } else { weatherStr += ' in ???'; } } document.getElementById('label-weather' + i).innerHTML = weatherStr; } let nextDay = findNextNight(nowMs); let nextNight = findNextDay(nowMs); let timeStr = ''; let timeVal; if (nextDay > nextNight) timeStr = gNightIcon + ' for '; else timeStr = gDayIcon + ' for '; let dayNightMin = (Math.min(nextDay, nextNight) - nowMs) / 1000 / 60; timeStr += Math.ceil(dayNightMin) + 'm'; document.getElementById('label-time').innerHTML = timeStr; document.getElementById('label-tracker').innerHTML = this.currentTracker; for (let i = 0; i < this.nmKeys.length; ++i) { let nm = this.nms[this.nmKeys[i]]; let respawnMs = null; if (nm.respawnTimeMsLocal) respawnMs = nm.respawnTimeMsLocal; else if (nm.respawnTimeMsTracker) respawnMs = nm.respawnTimeMsTracker; let popRespawnMs = respawnMs; // Ignore respawns in the past. respawnMs = Math.max(respawnMs, nowMs); let respawnIcon = ''; if (nm.weather) { let respawnWeather = getWeather(respawnMs, this.zoneName); if (respawnWeather != nm.weather) { let weatherStartTime = findNextWeather(respawnMs, this.zoneName, nm.weather); if (weatherStartTime > respawnMs) { respawnIcon = gWeatherIcons[nm.weather]; respawnMs = weatherStartTime; } } } if (nm.time == 'Night') { let isNight = isNightTime(respawnMs); if (!isNight) { let nextNight = findNextNight(respawnMs); if (nextNight > respawnMs) { respawnIcon = gNightIcon; respawnMs = nextNight; } } } let remainingMs = respawnMs - nowMs; if (remainingMs <= 0) { let openUntil = null; if (nm.weather) { let weatherStartTime = findNextWeatherNot(nowMs, this.zoneName, nm.weather); respawnIcon = gWeatherIcons[nm.weather]; ; openUntil = weatherStartTime; } if (nm.time == 'Night') { respawnIcon = gNightIcon; openUntil = findNextDay(nowMs); } if (openUntil) { let openMin = (openUntil - nowMs) / 1000 / 60; nm.timeElement.innerHTML = respawnIcon + Math.ceil(openMin) + 'm'; } else { nm.timeElement.innerText = ''; } nm.element.classList.remove('nm-down'); } else { // If still waiting on pop, don't show an icon. if (popRespawnMs > nowMs) respawnIcon = ''; let remainingMinutes = Math.ceil(remainingMs / 1000 / 60); nm.timeElement.innerHTML = respawnIcon + remainingMinutes + 'm'; nm.element.classList.add('nm-down'); } } } ImportFromTracker(importText) { let trackerToNM = {}; for (let i = 0; i < this.nmKeys.length; ++i) { let nm = this.nms[this.nmKeys[i]]; trackerToNM[nm.trackerName[this.options.Language].toLowerCase()] = nm; } let regex = Regexes.Parse(/(.*) \((\d*)m\)/); let importList = importText.split(' > '); for (let i = 0; i < importList.length; i++) { let m = importList[i].match(regex); if (!m) { console.error('Unknown tracker entry: ' + importList[i]); continue; } let name = m[1]; let time = m[2]; let nm = trackerToNM[name.toLowerCase()]; if (nm) nm.respawnTimeMsTracker = (time * 60 * 1000) + (+new Date()); else console.error('Invalid NM Import: ' + name); } this.UpdateTimes(); } OnLog(e) { if (!this.zoneInfo) return; for (let idx = 0; idx < e.detail.logs.length; idx++) { let log = e.detail.logs[idx]; let match = log.match(gFlagRegex); if (match) this.AddFlag(match[2], match[3], match[1], match[4]); match = log.match(gTrackerRegex); if (match) this.currentTracker = match[1]; match = log.match(gImportRegex); if (match) { this.ImportFromTracker(match[2]); continue; } if (log.indexOf('03:Added new combatant ') >= 0) { for (let i = 0; i < this.nmKeys.length; ++i) { let nm = this.nms[this.nmKeys[i]]; if (log.match(nm.addRegex)) { this.OnPopNM(nm); continue; } } } if (log.indexOf('04:Removing combatant ') >= 0) { for (let i = 0; i < this.nmKeys.length; ++i) { let nm = this.nms[this.nmKeys[i]]; if (log.match(nm.removeRegex)) { this.OnKillNM(nm); continue; } } } } } SimplifyText(beforeText, afterText) { let str = (beforeText + ' ' + afterText).toLowerCase(); let dict = { train: [ 'train', 'tren', 'trian', 'tran', 'choo choo', 'train location', ], fairy: [ 'fairy', 'elemental', 'faerie', 'fary', ], raise: [ 'raise', 'rez', 'res ', ' res', 'raise plz', ], }; let keys = Object.keys(dict); for (let i = 0; i < keys.length; ++i) { let key = keys[i]; for (let j = 0; j < dict[key].length; ++j) { let m = dict[key][j]; if (str.indexOf(m) >= 0) return key; } } } AddFlag(x, y, beforeText, afterText) { // https://github.com/ravahn/FFXIV_ACT_Plugin/issues/160 beforeText = beforeText.replace(/[^\x00-\x7F]/g, '').trim(); afterText = afterText.replace(/[^\x00-\x7F]/g, '').trim(); beforeText = beforeText.replace(/(?: at|@)$/, ''); let simplify = this.SimplifyText(beforeText, afterText); if (simplify) { beforeText = simplify; afterText = ''; } let container = document.getElementById('flag-labels'); let label = document.createElement('div'); label.classList.add('flag'); this.SetStyleFromMap(label.style, x, y); let icon = document.createElement('span'); icon.classList.add('flag-icon'); let name = document.createElement('span'); name.classList.add('flag-name'); name.classList.add('text'); name.innerText = beforeText; if (beforeText != '' && afterText != '') name.innerText += ' '; name.innerText += afterText; label.appendChild(icon); label.appendChild(name); container.appendChild(label); window.setTimeout(function() { // Changing zones can also orphan all the labels. if (label.parentElement == container) container.removeChild(label); }, this.options.FlagTimeoutMs); } } document.addEventListener('onPlayerChangedEvent', function(e) { gTracker.OnPlayerChange(e); }); document.addEventListener('onZoneChangedEvent', function(e) { gTracker.OnZoneChange(e); }); document.addEventListener('onLogEvent', function(e) { gTracker.OnLog(e); }); UserConfig.getUserConfigLocation('eureka', function(e) { gTracker = new EurekaTracker(Options); }); jiamindeng/tangoji /** * Formats and styles a {...definition} as an html string to be displayed on one page of the dialog window. * * @param {Object} definition of a word, part of the array fetched from the /definitions/:word * endpoint * @returns An html string containing
  • elements holding definition content for a word */ window.makeDefinitionReadable = async (definition) => { const _mapEnglishContext = async (englishContext) => { const colorId = await window.extensionStorage().getColorId(); return englishContext .map( ({ english, partsOfSpeech }) => `
  • ${english.join( '; ', )} (${partsOfSpeech.join('/').toLowerCase()})
  • `, ) .join(''); }; const _mapJapanese = (japanese) => `${japanese .map( ({ kanji, furigana }) => `${ kanji ? kanji : furigana } (${ kanji ? furigana : '' })`, ) .join(' ・ ')}`; const { japanese, englishContext } = definition; return `${_mapJapanese(japanese)}${await _mapEnglishContext(englishContext)}`; }; /** * Formats and styles [...sentences] as an html string to be displayed on one page of the dialog window. * * @param {Array} sentences Array of sentence objects, fetched from the /sentences/:word endpoint * @returns An html string containing
  • elements holding formatted sentences */ window.makeSentencesReadable = (sentences) => { const _mapSentence = ({ japanese, english }) => `${japanese .map(({ unlinked, furigana }) => furigana ? `${unlinked}(${furigana})` : unlinked, ) .join('')}。 ${english}`; return sentences.map((sentence) => `
  • ${_mapSentence(sentence)}
  • `).join(''); }; /** * Fetches vocabulary content. * * @param {string} word in either English or Japanese; Roman alphabet or kanji/kana * @param {string} contentType Corresponds to the tangoji endpoint content is fetched from * (eg. 'definitions', 'sentences') * @returns An array with content, if available; otherwise, an empty array [] */ window.fetchContent = async (word, contentType) => { try { return await (await fetch(`${window.jishoUrl}${contentType}/${word}`)).json(); } catch (err) { console.error(err); return []; } }; export const IfUri = ({condition, children}) => condition ? children : null; export const checkUri = (object) => { if(object){ if(object.logo_url.includes('.png') || object.logo_url.includes('.jpg')){ return false; }else{ return true; } } };lpcruz/theo const PATTERNS = require('../shared/patterns') describe('Patterns', () => { describe('GREETINGS', () => { it('should retrieve a matching string if a user says "hi"', () => { const string = '@theo hi there my friend!'; const actual = string.match(PATTERNS.GREETINGS); expect(actual.join('')).toEqual('hi'); }); it('should retrieve a matching string if a user says "hey"', () => { const string = '@theo hey!'; const actual = string.match(PATTERNS.GREETINGS); expect(actual.join('')).toEqual('hey'); }); it('should retrieve a matching string if a user says "hey"', () => { const string = '@theo yo!!!'; const actual = string.match(PATTERNS.GREETINGS); expect(actual.join('')).toEqual('yo'); }); it('should retrieve a matching string if a user says "hello"', () => { const string = '@theo hello!'; const actual = string.match(PATTERNS.GREETINGS); expect(actual.join('')).toEqual('hello'); }); it('should be null when a string does not match', () => { const string = '@theo'; const actual = string.match(PATTERNS.GREETINGS); expect(actual).toEqual(null); }); }); describe('SEARCH', () => { it('should retrieve a matching string if a user says "search"', () => { const string = '@theo search for bars in nyc'; const actual = string.match(PATTERNS.SEARCH); expect(actual.join('')).toEqual('search'); }); }); describe('WEATHER', () => { it('should retrieve a matching string if a user says "weather in"', () => { const string = '@theo weather in nyc'; const actual = string.match(PATTERNS.WEATHER); expect(actual.pop()).toEqual('weather in'); }); it('should retrieve a matching string if a user says "temperature in"', () => { const string = '@theo temperature in nyc'; const actual = string.match(PATTERNS.WEATHER); expect(actual.pop()).toEqual('temperature in'); }); it('should retrieve a matching string if a user says "forecast in"', () => { const string = '@theo forecast in nyc'; const actual = string.match(PATTERNS.WEATHER); expect(actual.pop()).toEqual('forecast in'); }); }); describe('SPOTIFY_PLAYLIST', () => { it('should retrieve a matching string if a user says "feeling"', () => { const string = '@theo feeling happy and sad and mad and confused?!'; const actual = string.match(PATTERNS.SPOTIFY_PLAYLIST); expect(actual.join('')).toEqual('feeling'); }); }); describe('HELP', () => { it('should retrieve a matching string if a user says "help"', () => { const string = '@theo help'; const actual = string.match(PATTERNS.HELP); expect(actual.join('')).toEqual('help'); }); }); it('should retrieve a matching string if a user says "assist"', () => { const string = '@theo assist me!'; const actual = string.match(PATTERNS.HELP); expect(actual.join('')).toEqual('assist'); }); describe('RECIPES', () => { it('should retrieve a matching string if a user says "recipe for"', () => { const string = '@theo recipe for pizza'; const actual = string.match(PATTERNS.RECIPES); expect(actual.pop()).toEqual('recipe for'); }); }); it('should retrieve a matching string if a user says "recipes for"', () => { const string = '@theo recipes for pizza'; const actual = string.match(PATTERNS.RECIPES); expect(actual.pop()).toEqual('recipes for'); }); describe('INGREDIENTS_BASED_RECIPE', () => { it('should retrieve a matching string if a user says "recipe using"', () => { const string = '@theo recipe using sazon'; const actual = string.match(PATTERNS.INGREDIENTS_BASED_RECIPE); expect(actual.pop()).toEqual('recipe using'); }); it('should retrieve a matching string if a user says "recipes using ingredients"', () => { const string = '@theo recipes using ingredients salt and pepper'; const actual = string.match(PATTERNS.INGREDIENTS_BASED_RECIPE); expect(actual.pop()).toEqual('recipes using ingredients'); }); }); }); app/javascript/reducers/contacts.js import { ADD_CONTACT, DELETE_CONTACT } from "../constants"; function attachContact(state, action) { return { ...state, [action.email]: { email: action.email, first_name: action.first_name, last_name: action.last_name } }; } function deleteContact(state, action) { return Object.keys(state) .filter(email => email !== action.email) .reduce((newState, email) => { newState[email] = state[email]; return newState; }, {}); } export default function contacts(state = {}, action) { if (!action) return state; switch (action.type) { case ADD_CONTACT: return attachContact(state, action); case DELETE_CONTACT: return deleteContact(state, action); default: return state; } } 0 var _require = require('../helper'), validGATrackingId = _require.validGATrackingId, isEnabled = _require.isEnabled; exports.addGoogleAnalytics = function (_ref) { var trackingId = _ref.trackingId; return new Promise(function (resolve, reject) { if (window.gatsbyPluginGDPRCookiesGoogleAnalyticsAdded) return resolve(true); var head = document.getElementsByTagName('head')[0]; var script = document.createElement("script"); script.type = "text/javascript"; script.onload = function () { window.gatsbyPluginGDPRCookiesGoogleAnalyticsAdded = true; resolve(true); }; script.src = "https://www.googletagmanager.com/gtag/js?id=" + trackingId; head.appendChild(script); }); }; exports.initializeGoogleAnalytics = function (options) { if (!window.gatsbyPluginGDPRCookiesGoogleAnalyticsInitialized && isEnabled(options) && validGATrackingId(options)) { window.dataLayer = window.dataLayer || []; window.gtag = function () { window.dataLayer.push(arguments); }; window.gtag('js', new Date()); var gaAnonymize = options.anonymize; var gaAllowAdFeatures = options.allowAdFeatures; gaAnonymize = gaAnonymize !== undefined ? gaAnonymize : true; gaAllowAdFeatures = gaAllowAdFeatures !== undefined ? gaAllowAdFeatures : true; window.gtag('config', options.trackingId, { 'anonymize_ip': gaAnonymize, 'allow_google_signals': gaAllowAdFeatures }); window.gatsbyPluginGDPRCookiesGoogleAnalyticsInitialized = true; } }; exports.trackGoogleAnalytics = function (options, location) { if (isEnabled(options) && validGATrackingId(options) && typeof window.gtag === "function") { var pagePath = location ? location.pathname + location.search + location.hash : undefined; window.gtag("event", "page_view", { page_path: pagePath }); } };const mongoose = require('mongoose'); const Schema = mongoose.Schema; var validateEmail = function(email){ var re =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ return re.test(email) }; const userSchema = new Schema({ username:{ type :String, minLength:5, maxLength:20, required: true, unique:true }, password: { type:String, minLenght:5, maxLenght:1000, required:true, }, email:{ type:String, unique:true, requried:true, validate:[validateEmail,'email is appropreate'] } }) module.exports=mongoose.model('user',userSchema)0 /* * @Author: doramart * @Date: 2019-09-23 14:44:21 * @Last Modified by: doramart * @Last Modified time: 2020-09-04 23:14:26 */ const _ = require('lodash'); let ContentTemplateController = { async getDefaultTempInfo(ctx, app) { let defaultTempData = app.cache.get(app.config.session_secret + '_default_temp'); if (!_.isEmpty(defaultTempData)) { ctx.helper.renderSuccess(ctx, { data: defaultTempData }); } else { let defaultTemp = await ctx.service.contentTemplate.item({ query: { 'using': true }, include: [{ as: 'items', model: "TemplateItems" }] }) if (!_.isEmpty(defaultTemp)) { // 缓存1天 ctx.helper.setMemoryCache(app.config.session_secret + '_default_temp', defaultTemp, 1000 * 60 * 60 * 24); ctx.helper.renderSuccess(ctx, { data: defaultTemp }); } else { ctx.helper.renderSuccess(ctx, { data: {} }); } } } } module.exports = ContentTemplateController;Stepyyy/oldschoolbot const { Command } = require('klasa'); const { MessageAttachment } = require('discord.js'); const { createCanvas, Image, registerFont } = require('canvas'); const fs = require('fs'); const bg = fs.readFileSync('./resources/images/pm-bg.png'); const canvas = createCanvas(376, 174); const ctx = canvas.getContext('2d'); ctx.font = '16px OSRSFont'; registerFont('./resources/osrs-font.ttf', { family: 'Regular' }); module.exports = class extends Command { constructor(...args) { super(...args, { description: 'Fake a private message from someone.', cooldown: 3, requiredPermissions: ['ATTACH_FILES'], usage: '(username:rsn) ', usageDelim: ' ' }); } async run(msg, [username, message]) { const BG = new Image(); BG.src = bg; ctx.drawImage(BG, 0, 0, BG.width, BG.height); ctx.fillStyle = '#000000'; ctx.fillText(`From ${username}: ${message}`, 6, 98); ctx.fillStyle = '#00ffff'; ctx.fillText(`From ${username}: ${message}`, 5, 97); return msg.send(new MessageAttachment(canvas.toBuffer(), `${Math.round(Math.random() * 10000)}.jpg`)); } }; /** * Copyright 2017 Comcast Cable Communications Management, LLC * * 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. * * @author () */ (function () { 'use strict'; angular .module('uxData.urlParams') .controller('urlParamsController', urlParamsController); urlParamsController.$inject = ['$scope', 'RulesCommonValidationService']; function urlParamsController($scope, rulesCommonVS) { /* jshint validthis: true */ var vm = this; vm.server = $scope.server; vm.IP_PROTOCOL_VERSION_LIST = [{id: '4', name: 'IPv4'}, {id: '6', name: 'IPv6'}]; vm.onUrnChanged = onUrnChanged; vm.onPortChanged = onPortChanged; vm.onProtocolChanged = onProtocolChanged; vm.onIPProtocolVersionChanged = onIPProtocolVersionChanged; vm.hasError = rulesCommonVS.hasError; function onProtocolChanged () { $scope.onServerChanged({newProtocol: vm.server.protocol, newPort: vm.server.port, newUrn: vm.server.urn, newIPProtocolVersion: vm.server.ipProtocolVersion}); } function onPortChanged () { $scope.onServerChanged({newProtocol: vm.server.protocol, newPort: vm.server.port, newUrn: vm.server.urn, newIPProtocolVersion: vm.server.ipProtocolVersion}); } function onUrnChanged () { $scope.onServerChanged({newProtocol: vm.server.protocol, newPort: vm.server.port, newUrn: vm.server.urn, newIPProtocolVersion: vm.server.ipProtocolVersion}); } function onIPProtocolVersionChanged () { $scope.onServerChanged({newProtocol: vm.server.protocol, newPort: vm.server.port, newUrn: vm.server.urn, newIPProtocolVersion: vm.server.ipProtocolVersion}); } } })(); module.exports = { extends: 'godaddy', plugins: [], rules: {}, env: { mocha: true, jest: true } }; var struct_users = [ [ "admin", "struct_users.html#a2b91ea0bc21540d131b22cfdfe731575", null ], [ "error_counter", "struct_users.html#ac600fd46d2914d09fe3d45b3a2c7ac1f", null ], [ "ID", "struct_users.html#a505f98fde467109a9b37b3c7e008df91", null ], [ "PIN", "struct_users.html#a91ee63dd24a702a6b71474783c75a66c", null ] ];/** * @file OverrideRawPlugin * @author <> * @project pom-plugin-builder * @license MIT {@link http://opensource.org/licenses/MIT} */ "use strict"; const tap = require('tap') const ORP = require('../../../lib/Validator/Types/OverrideRawPlugin') const validplugin = { moduleName: 'test-override-plugin', loaded: { options: {workDir: '/path'}, metadata: {name: 'OverridePlugin', type: 'override'}, plugin: { load: function() {}, start: function() {}, stop: function() {} }, override: { module: 'test-raw-plugin', name: 'OverrideTest' } } } tap.test('Instantiate Override plugins', (t) =>{ t.throws(function() { new ORP() }, 'Throws with no args') let op = new ORP(validplugin); t.ok(op instanceof ORP, 'Constructs properly') t.end() }) tap.test('Sets override property.', (t) => { let op = new ORP(validplugin) t.type(op.override, 'object', 'Sets override property') t.ok(op.isOverride(), 'isOverride() returns true.') t.notOk(op.hasErrors(), 'No errors') t.end() }) tap.test('Sets override to false when missing', (t) => { let missing = { moduleName: 'test-override-plugin', loaded: { options: {workDir: '/path'}, metadata: {name: 'OverridePlugin', type: 'override'}, plugin: { load: function() {}, start: function() {}, stop: function() {} } } } let op = new ORP(missing) t.notOk(op.override, 'Is false ') t.ok(op.hasErrors(), 'Has Errors with no override set.'); t.end() })maker-x/GUI module.exports = { languages: { en: "English", cn: "简体中文", fr: "Français", ko: "한국어", de: "Deutsch", es: "Español", tr: "Turkish" }, header: { title: "MakerX", dashboard: "Accueil", explorer: "Explorer", exchange: "Échange", payments: "Paiments", logout: "Déconnexion", settings: "Options", current: "Mon Compte", create_account: "Créér un compte", create_asset: "Créér un actif", lock: "Vérouiller", unlock: "Dévérouiller" }, account: { asset: "Actif", market_value: "Valeur", hour_24: "24hrs", recent: "Activité recent", name: "", more: "voir plus", member: { stats: "Stats membre", join: "Inscription", reg: "Enregistré par", ref: "Recruté par", ref_percentage: "Pourcentage de frais pour le recruteur", network_percentage: "Pourcentage de frais pour le reseau", fees_paid: "Frais payé", fees_pending: "Frais en attente", fees_vested: "Frais en attente bloqué", in_orders: "Total de %(core_asset)s en ordres", referrals: "Recrutements", rewards: "Gains totaux", cashback: "Gagné", vested: "Bloqué", unknown: "Inconnu", lifetime: "Membre à vie", basic: "Membre basique", annual: "Abonné annuel" }, user_issued_assets: { symbol: "Symbol", name: "Asset Name", description: "Description", max_supply: "Maximum supply", precision: "Precision", to: "Issue to account", details: "Details" }, connections: { known: "Connu par", black: "Blacklisté par" }, perm: { active: "Permissions actifs", owner: "Permissions des proprietaires", memo_key: "Cléf mémo", publish: "Publier les changements", reset: "Annuler les changements", add: "Rajouter une permission", type: "Type", key: "Cléf/Nom", weight: "Poids", threshold: "Limite", confirm_add: "Rajouter", cancel: "Annuler", warning1: "Active permissions weights total of %(weights_total)s should be equal or exceed threshold of %(threshold)s", warning2: "Owner permissions weights total of %(weights_total)s should be equal or exceed threshold of %(threshold)s", warning3: "Account is already in the list", warning4: "Key is already in the list", action: "Action", acct_or_key:" Account/Key" }, votes: { proxy: "Proxy Voting Account", name: "Nom", info: "Info", support: "Support", workers: "Ouvriers", no_proxy: "No Proxy", votes: "Votes", url: "Webpage", publish: "Publish Changes", add_witness: "Add", remove_witness: "Remove", remove_committee: "Remove", add_committee: "Add", add_committee_label: "Committee Member", add_witness_label: "Witness" }, options: { num_witnesses: "Desired Witnesses", num_committee: "Desired Committee Members", memo_key: "Memo Key" }, upgrade: "Mettre à niveau", unfollow: "Unfollow", follow: "Follow", pay: "Payer", overview: "Sommaire", history: "Historique", payees: "Payees", permissions: "Permissions", voting: "Votes", orders: "Ordres", select_placeholder: "Selectionnez un compte..", errors: { not_found: "Le compte %(name)s n'existe pas, veuillez vérifier le nom", invalid: "Compte non valable", unknown: "Compte inconnu", not_yours: "Pas votre compte" }, settle: "Settle" }, transfer: { from: "De", amount: "Montant", to: "À", memo: "Message", fee: "Frais", send: "Envoyer", final: "Soldes finaux", balances: "Soldes", available: "Disponible", errors: { req: "Champ obligatoire", pos: "Le montant doit étre positif", valid: "Veuillez rentrer un chiffre positif", balance: "Le solde final doit être superieur à 0", insufficient: "Insufficient Balance" }, back: "REVENIR", confirm: "CONFIRMER", broadcast: "Votre transfert a bien été diffusé au reseau", again: "FAIRE UN AUTRE TRANSFERT", see: "VOIRE MES TRANSFERTS", close: "Fermer" }, operation: { pending: "%(blocks)s avant confirmation", no_recent: "Aucune transaction récente", reg_account: "{registrar} a créé le compte {new_account}", transfer: "{from} a envoyé {amount} à {to}", pending: "pending %(blocks)s blocks", proposal_create: "{account} a créé une transaction proposée", proposal_update: "{account} a mis à jour une transaction proposée", proposal_delete: "{account} a supprimé une transaction proposée", fill_order: "{account} a acheté {received} au prix de {price}", vesting_balance_withdraw: "{account} a retiré {amount} d'un solde bloqué", balance_claim: "{account} a recuperé un solde de {amount}", publish_feed: "{account} a publié un nouveau flux de {price}", set_proxy: "{account} a choisi {proxy} pour son nouveau proxy", update_account: "{account} a mis à jour les donnéees de son compte", limit_order_sell: "{account} a placé un ordre pour vendre {amount} au prix de {price}", limit_order_buy: "{account} a placé un ordre pour acheter {amount} au prix de {price}", call_order_update: "{account} a modifié sa debt de {debtSymbol} par {debt} et le collateral par {collateral}", asset_reserve: "{account} a détruit {amount}", asset_issue: "{account} à assigné {amount} à {to}", asset_create: "{account} a crée l'actif {asset}", asset_update: "{account} a mis à jour l'actif {asset}", lifetime_upgrade_account: "{account} a été converti en membre à vie", annual_upgrade_account: "{account} a été converti en membre annuel", unlisted_by: "{lister} a délisté le compte {listee}", whitelisted_by: "{lister} a whitelisté {listee}", blacklisted_by: "{lister} a blacklisté {listee}" }, transaction: { confirm: "Veuillez confirmer la transaction", broadcast_success: "La transaction a été diffusée", transaction_confirmed: "Transaction confirmed", broadcast_fail: "La diffusion de la transaction a échoué: %(message)s", broadcasting: "Diffusion de la transaction en cours..", broadcasting_short: "Diffusion en cours..", sent: "A envoyé", to: "à", received: "A reçu", from: "de", amount_sell: "Montant à vendre", expiration: "Expiration", fill_or: "Fill or kill", min_receive: "Montant minimum à recevoir", seller: "Vendeur", collateral: "Collateral", coll_ratio: "Ratio de collateral initiale", coll_maint: "Ratio de Collateral de maintenance", create_key: "A créé une cléf public", limit_order_cancel: "Annulation de l'ordre à limite avec id", short_order: "A placé un ordre à découvert pour vendre", at: "à", coll_of: "avec collateral de", upgrade_account: "A mis à niveau le compte", transfer_account: "A transferé le compte", update_feed_producers: "A mis à jour les fornisseurs de flux de l'actif", feed_producer: "Est devenu un fornisseur de flux pour l'actif", was_issued: "A été assigné", by: "par", burn_asset: "A détruit", fund_pool: "A financé un pot de frais avec", asset_settle: "Requested settlement of", asset_global_settle: "Requested global settlement of", committee_member_create: "A créé le délégué", witness_create: "A créé le témoin", witness_pay: "A retiré", withdraw_permission_create: "A donné une permission de retrait du compte", withdraw_permission_update: "A mis à jour les permissions de retrait du compte", withdraw_permission_claim: "A pris les permissions de retrait du compte", withdraw_permission_delete: "A supprimé les permissions de retrait du compte", paid: "A payé", obtain: "pour obtenir", global_parameters_update: "A mis à jour les parametres globaux", file_write: "A écrit un fichier", vesting_balance_create: "a créé un solde bloqué pour", for: "pour", bond_create_offer: "A créé une offre d'obligation", bond_cancel_offer: "A annulé l'offre d'obligation", bond_accept_offer: "A accepté l'offre d'obligation pour", bond_claim_collateral: "A récuperé un collateral de", bond_pay_collateral: "A payé un collateral de", create_worker: "A créé un ouvrier avec un salaire de", custom: "A créé une operation spéciale", order_id: "ID de l'ordre", balance_owner: "Clèf du solde", balance_id: "ID du solde", deposit_to: "Versé sur le compte", claimed: "Total recuperé", trxTypes: { transfer: "Transfert", limit_order_create: "Ordre à limite", limit_order_cancel: "Annulation d'ordre à limite", call_order_update: "Mise à jour d'ordre à découvert", account_create: "Création de compte", account_update: "Mise à jour de compte", account_whitelist: "Whiteliste de compte", account_upgrade: "Mise à niveau de compte", account_transfer: "Transfert de compte", asset_create: "Creation d'actif", asset_update: "Mise à jour d'actif", asset_update_bitasset: "Mise à jour d'actif de marché", asset_update_feed_producers: "Mise à jour des flux", asset_issue: "Assigner un actif", asset_reserve: "Destruction d'actif", asset_fund_fee_pool: "Financement de pot de frais", asset_settle: "Couvrement d'actif", asset_global_settle: "Couvrement global d'actif", asset_publish_feed: "Publication de flux", committee_member_create: "Création de délégué", witness_create: "Création de témoin", witness_withdraw_pay: "Retrait de salaire de témoin", proposal_create: "Création d'une proposition", proposal_update: "Mise à jour d'une proposition", proposal_delete: "Suppresion d'une proposition", withdraw_permission_create: "Accord de permission de retrait", withdraw_permission_update: "Mise à jour de permission de retrait", withdraw_permission_claim: "Prise de permissions de retrait", withdraw_permission_delete: "Suppresion des permissions de retrait", fill_order: "Execution d'ordre", committee_member_update_global_parameters: "Mise à jour des parametres globaux", vesting_balance_create: "Création de solde bloqué", vesting_balance_withdraw: "Retrait de solde bloqué", worker_create: "Création d'ouvrier", custom: "Spécial", assert: "Assert operation", balance_claim: "Récuperation de solde", override_transfer: "Forcing de transfert" } }, explorer: { accounts: { title: "Comptes" }, blocks: { title: "Blockchain", globals: "Parametres globaux", recent: "Blocs recent" }, block: { title: "Bloc", id: "ID du bloc", witness: "Témoin", count: "Nombre de transactions", date: "Date", previous: "Précédent", previous_secret: "Précédent secret", next_secret: "Prochain hash secret", op: "Operation", trx: "Transaction", op_type: "Type d'operation", fee_payer: "Compte payant le frai", key: "Cléf public", transactions: "Nombre de transactions", account_upgrade: "Compte à mettre à niveau", lifetime: "Devenir membre à vie", authorizing_account: "Compte donnant l'autorisation", listed_account: "Compte etant autorisé", new_listing: "Nouvel autorisation", asset_update: "Actif à mettre à jour", common_options: "Options", new_options: "Nouvelles options", new_producers: "Nouveaux fornisseurs de flux", asset_issue: "Montant à créer", max_margin_period_sec: "Periode max de marge (s)", call_limit: "Limite de couverture", short_limit: "Limite de short", settlement_price: "Prix de règlement" }, assets: { title: "Actifs", market: "SmartCoins", user: "Actifs des utilisateurs", symbol: "Symbol", id: "ID", issuer: "Créateur", precision: "Précision" }, asset: { title: "Actif", not_found: "L'actif %(name)s n'existe pas" }, witnesses: { title: "Témoins" }, committee_members: { title: "Délégués" }, committee_member: { title: "CommitteeMember" }, workers: { title: "Ouvriers" }, proposals: { title: "Propositions" }, account: { title: "Compte" } }, settings: { inverseMarket: "Orientation préféré pour les marchés", unit: "Unité de valeur préféré", confirmMarketOrder: "Demander une confirmation pour des ordres du marché", locale: "Changer de langue", confirm_yes: "Toujours", confirm_no: "Jamais", always_confirm: "Toujours demander une confirmation" }, footer: { title: "MakerX", block: "Bloc courant" }, exchange: { price_history: "Historique du prix", order_depth: "Carnet d'ordres", market_history: "Historique du marché", balance: "Solde", lowest_ask: "Offre le plus bas", highest_bid: "Demande le plus haut", total: "Total", value: "Valeur", price: "Prix", latest: "Dernier Prix", call: "Prix de flux", volume: "Volume", spread: "Spread", quantity: "Quantité", buy: "Acheter", sell: "Vendre", confirm_buy: "Confirmation d'ordre: Acheter %(buy_amount)s %(buy_symbol)s au prix de %(price_amount)s %(price_symbol)s", confirm_sell: "Confirmation d'ordre: Vendre %(sell_amount)s %(sell_symbol)s au prix de %(price_amount)s %(price_symbol)s" }, markets: { choose_base: "Selectionner l'actif de base", filter: "Filtrer", core_rate: "Taux de base", supply: "Réserve", search: "Chercher" }, wallet: { title: "Portefeuille", confirm: "Confirmer le mot de passe", password: "" }, refcode: { claim: "Claim", claim_refcode: "Claim Referral Code", refcode_optional: "Referral Code (optional)", enter_refcode: "Enter referral code" }, gateway: { bridge: "Bridge", gateway: "Gateway", symbol: "Symbol", deposit_to: "Deposit To", balance: "Balance", generate: "Generate", deposit: "Deposit", withdraw: "Withdraw", inventory: "Inventory", scan_qr: "Scan QR", transwiser: { gateway: "Transwiser", visit_weidian: "Click to deposit", deposit_title: "Deposit RMB to %(asset)s", withdraw_title: "Withdraw %(asset)s to RMB", alipay: "ALIPAY Account Name", withdraw_note: "Currently only ALIPAY withdraw is supported. Your asset will be converted at 1:1 ratio and send RMB to your ALIPAY account.", you_will_receive: "You will receive %(amount)s RMB" }, meta: { open_website: "Open Website" } } }; chungeric/udemy-redux-books export default function() { return [ { title: 'JavaScript: The Good Parts', pages: 101 }, { title: 'Harry Potter', pages: 470 }, { title: 'The Dark Tower', pages: 85 }, { title: 'Ready Player One', pages: 140 } ]; } 'use strict'; const Authorization = require('../../authorization/v1'); describe('authorization', function() { const url = 'http://ibm.com:80/text-to-speech-beta/api/foo/bar'; const service = { username: 'batman', password: '', url, version: 'v1', }; const rc_service = { iam_apikey: 'abc123', version: 'v1', }; const authorization = new Authorization(service); const rc_authorization = new Authorization(rc_service); const createRequestMock = jest.spyOn(authorization, 'createRequest'); createRequestMock.mockImplementation((params, cb) => cb(null, mock_token)); // tokens are URL-encoded when recieved from the service const mock_token = 'token'; function missingParameter(done) { return function(err) { expect(err).toBeInstanceOf(Error); expect(/required parameters/.test(err)).toBe(true); done(); }; } function checkToken(done) { return function(err, res) { expect(err).toBeNull(); expect(res).toBe(mock_token); done(); }; } describe('getToken()', function() { it('should check for missing url param', function(done) { const params = { noturl: url, }; authorization.getToken(params, missingParameter(done)); }); it('should generate a valid token payload', function(done) { authorization.getToken({ url: 'http://ibm.com/myservice/myresource' }, checkToken(done)); }); it('should default to url from credentials', function(done) { authorization.getToken(checkToken(done)); }); it('should return an iam access token if given iam_api_key', function(done) { expect(rc_authorization.tokenManager).not.toBeNull(); // mock the token manager request method const requestMock = jest.spyOn(rc_authorization.tokenManager, 'getToken'); requestMock.mockImplementation(cb => cb(null, mock_token)); rc_authorization.getToken(checkToken(done)); }); }); }); 0 /* * @Author: lijianzhang * @Date: 2017-12-31 18:16:06 * @Last Modified by: lijianzhang * @Last Modified time: 2017-12-31 18:16:58 */ import wrapDecorator from './wrapDecorator'; function enumerable(target, key, descriptor, enumerable = true) { descriptor.enumerable = enumerable; return descriptor; } export default wrapDecorator(enumerable); assets/js/organization/new.js $('#addAddressBtn').on('click', function(){ $('#addAddressModal').modal('show'); $('#createAddressBtn').on('click', function(){ $.post("/dashboard/address/new", { address: { line1: $('#address_line1').val(), line2: $('#address_line2').val(), post: $('#address_post').val(), _token: $('#address__token').val() } }, function(data, status){ $('#addAddressModal').modal('hide'); $('#clientAddress').append($('