�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  �T8   �� ����,�,�H<ӱ7 �7 �7���7�V���&.6>FMU\dlsz�����������������$+3;CJRYaiqx����������������� &.5<DKRYahpw~����������������� %-4;CKRZbipx����������������� "*19AHOV]elsy����������������� !(/7?GNV^fmt{����������������� #*29AGOV]elt|�����������������%,2:AIPX_gnu|����������������� ")19@GNU\cjrz�����������������   ' / 7 ? F N V ] c j r y � � � � � � � � � � � � � � � � � �     $ + 2 : B I Q Y a i p w ~ � � � � � � � � � � � � � � � � �    ( / 6 > E K S [ c j q w ~ � � � � � � � � � � � � � � � � �    " * 1 9 A H O V ^ f n v ~ � � � � � � � � � � � � � � � � � �    # * 2 : A H O U ] e l t { � � � � � � � � � � � � � � � � � � %-5=ELRY`gnu|�����������������$+2:?EMT[biqw����������������� "(/7>EKS[biqy������������������!)08?FNV^emu}����������������� #*19@GOV^fnu}����������������� ")08?GNU\dls{������������������ #+3;AHPX_gow~����������������� "*2:BJQY`how~�����������������$+2:AHOV^fnv}����������������� "*2:BJRZagov~�����������������#+3;CJQYaipw�����������������$+2:BHOW^fmu|������������������ ")06=EMU]dksz�����������������  (/6=CJQX`hpw~����������������� &,3:AGOW^elt{�����������������175794001987359534065533344343192130541741757017236400123226451460833892479561509850150045941834388013916860187959254612901914332112694917876838123083907324918184754218983953756479811286647893090012805885569359130992401972438810992977180845010142930192635166920513333742731852839237841284965150625581867630517848186131637913822508142298624500228186777101938574216781988758882416424367913223910012651385797614641510167302801815564645260581704004518365457124662773232417621861110912832116005571748727012148663298298026158935360232408767477708511235702210717891120124977501931293141255219724402132993697411795981777028915702018330778850755411150221273696881536997515776335204148453290819348668482247816151657151949172166668515909712906165940661242895414406151154986445778624057260804801327050525516078667372013105873533887591945961742573813173202548347910660485155064855917596870149819034350112718716101280167271831535247653765899016478120478054160725127894819008987217132110673022274935796650135557212430150016901413104054071404439744231593794659726247676503031583223856191671589837513945433617918216605269293641574183610697250990500944715613666971137827535405191736669825401025211989104565915378684130651731812130215823408516890478678371472986112774294104636651612577018396833146340481763646640927936763215107470603055687825426118161690160340241183165045421671435036917943126159375806292014955552966651099270145107550668054121134203421122936219540429334449658056242369574880064212037514113274651037957915952093119535034261839191108162726049195279361513752313795274110481827553914158704576924049102879258060471151383838576143383469144143822934547162898081016998815091764875590936420551144689710310410332701390064117010907390763998013901477103527878271582018881908461524231842433088797485473979018278251110789921403058084892815795516927792676126141125406597233175829606709878171659156032663129135222631140853383814925943505801777496417256639802237070102131396903740040433184522601588866863131055578718054944790810016790072121840891563223511618139130870721279811916279131115704016318338909914314317988157544168705108972596965852857573703188644135798826151662116030951864262113505722705842198988485460740172577631213182617881871194869111135475185121531141275144515273728665187729815205048912099816679043152688404432552167882301627844782315924759343152518421342843918571726186611319343601180724589316076976928440111915504230824523217050735124275761267302810785857154709111490718174683983588720151260242242040576872828301871855710432531217299488170147667968499603701112897945873190552847911454958964485995873282066744147678231064913298588801811778614269651190306981738125972513534701446974675587143371200990114860114135180899667401599265959019936731205120988168157861108868941711492427992891029657926301917630116265216111771227888043181063452553154766090218203530696980321292911890842266899965678051406361312771468145635066577189354030710868137533041423436318129917107868621435254969293541630151814356671897465132705725043995102595018338137147645613151815989606118463567433378898877120538191755439267035961426047518687520463071910041402166549168121195346452691614561440197214861875133392101496549915898602357200370152535747417127240481871619089844741892200261145687799976292931352143498855662723341021361577409718616146585695995350185634864137874896807738179342712309401328261317311204163965078304546641720929076742364841806082212234649928033214065794163829592699995691903402614595860726018366355851852627685234033267409214474684577743915469080181110101329168130501231123896128079051884528371341791918048265083811011255119289282189494441386724319447383161616366363017958205117944488917301751176395665332759993185334157886011270392323733344681766125317843875982135668755633128682808533944191141450396549721777713417653439636378112103074705878733647016172416363720290203718408714337784301435069274481510851172565912406143817251931752426158510463912209804110827136966451056316653741189943002148605936786296195146364492117234636104819699455831561766117384281324502119352571183806559596227539797547046011046381122352011196154615691094192570008635121494422123155863419586342927731813910653315127416637724453730522110120353130829571777616193214476946659735921610487732607659913742981356845876156011623296011716015131682663136112176494734061401380799284763171808483614947537557256948069541741996386651930679721590711424273326089604053295173339681128872115638335495507310564687103013741606497411165376188708719470965177536908832041163749161011540311105628703363110191817293184836902416324731119226944034526102062426763527159425721945221110272185565668121846369302791886652311849347442838312221901127258320872521349076410993604152726715463064146658011597743012404969686061216293081261877179955536087360159522071716100437816081873703413301062683317578068591536645713543112680719010966681089677125398791903322745778565694330820820514412531230962714144102370515034830992938009166916081943440228760431525081483002441909020227178281192233236542966827711135940461368343928338886581587460153343271847912831180208874635155042323874745146197381717492615641595199621564641291477573118605976146024681183230069009283453571788499517706415156556417578980152060061540741755181261108017712145315125809646870517112361505646856623231594125114401775227253233937751424628310044971655566010038205128439731916169633736031607065307071911209900722889714223484155227631214604412906272189120065191086143577479835587172894253986484107953532618840240793483716821843219417851830501033310328419107979085278809119249561931506093918391490153968919203403176711251121840793940367788163379507699391144681674771591353009157874121818520174733155158153173469882659333714885139311861769107219470201132618364575517196331211342364418923012136112598470215569342154390991168554518387424191275052833769101613761457245648855461109829186759405692843374387058105175770061535053411888046144417141212750615342566138692181151944612062087100777758224165357208121683231936459136272731477918383995241860124895985831783684255494395177671452395617829872170739581688581347195185565910170153131366206116977499834172112324015102616336376302153047826978011122707112620492108829751744977010954868866810180254681768131510004454914127979224561109937912834656125913092554607189232941144737625876215332901174655147810687531797131801511426916117226039132154895686008111213998504607884333517431183304198925192671327920451286505349163155214291649081850276239535861123665987954341695450356471821701824729188501031172018571354109717575099253676409158986801273038743801313143485407111771839175881346551284149392817075664602847741541722666242342927108939794955458879349517534963707127275880662954484972099103847021659025217574359155964029528777873817118448555552281735252955077194124435041166018317813892384858630167721776711116857959168755017638802106714581461794318430269461515165099031077922415385127467143315595749824273157547221060819490567249618374225949367390960153981840788936855918471860185936511384093931313413283842401612375430529318317113725326725518666603118169333403559526587731901583226822931364135503433812087566193027911224384487940794436721284250919355032186828781073829374452682081221146713557353249875106745154733171947068135866137752849786617415170732385937294012335921149524189478827187518751945111349805321950247451834573458586175591330161121822152610634604171927809828281477891fG�|'�2�5>7�9�DbN S�dShgj�vu���BO6^r�tysy)���o��������8�^������=��N 3$"D�q���H�����t�A�T�� �#�0I2�3�:�A�V�k\x ���a���L���;S7�9xD)P\�cu�G����i �#)K3N�d*���;������r��W �-:�CqFnw�~��/�������\�h�������/�W��������  m�"c)�3�7n]6k�m�p7tTv=y{�)�����Ư�� �\�a�����N? �C Cw "� )� �� ԣ � A� �� �� � g� D� p� �� �� �� �� e� �� �  �  � � 6$ �' ^+ �3 5 O6 �6 p8 �8 �A 4B �I � �� 5� �� p� �� �� � � � �� �� k� 1� �� � � = � - q. /6 �G �J �{ �� X � � c �' �� �� �� Q� 5� 2� �� �� &h�<Y@�G�H�T^Z�Zh�ielC�(�E�@�����)�+���D���D��#�3�6= AVD�HOIP�W�ZQ\�bzd�0�������Ҧc�� �����x�|�/�?���8�.!*�2 =�>T?�@�V Y�ZYdofY������{��κ��\�����������Q�����J 3 ,��&�C�Z�^�����F��� J!�"�&�314�?�A�COE�aQf�vw!�>�~������4�����b�#�4���`�-���������@R/�M SWY*f�j�n�s>� �������>�G�[����e�A$�&�+�2i8�9Y<�CTP�QhXY�Y�eXhUDSJ����������g�� � � % * �: jF �S U �X `Z \ �` �e �h Qu ӈ Ę � �� s� e� j� �� �� �� �� d� �� �� !�!�!�b!c!��![�!o�!��!��!�! "�R"Z_"�h"�{"~""׍"��"��"�"�"o�"i�"��"�"��":�"t�"��"��"v�"��"\+#�8#o;#y=#�A#G#�J#�b#�c#u# '�I':O';Q'nT'�V'W'y^'[a'�b'|�'^�'��'4�'��'��'��'p�'�'(\*(�1(�8(::(u;(�>(�?(C(}D(fH(�N(�P(8Q(�Q(VT(�T(�V(�Z(�\(oh(�s(~�(��(�(5�(��(��(��(��(��(�6)�7)�H)M)�d)�)�)ў)�)S�)��)�)�)�)0�)��)��)C�)$*i*�*�)*^+*�1*�4*Y8*y:* <*�A*�C*�H*�N*�U*�e*G~*`�*��*�*��*r�*o�*��*M+d+� +�+�"+c++?V+�W+Kj+�l+�m+_�+��+T�+��+3�+y�+E�+\�+ �+�,} ,�, ,�',3,,�,,�0,K8,@<,�=,:?,GA,�k,ځ,|�,��,ƴ,޸,ӽ,��,�-e`-�d-�f-�f-�q-�x-Y-��-s�-߇-H�-?�-��-F�-��-��-6�-;�-Z�-M�-��-��--�-+.�.�0.H=.�d.j.Q�.^/1/�2/�3/17/�7/�A/hK/:W/[/)\/ ^/G`/�b/fd/�i/"o/�|/}/�/��/�/(�/��/u�/�/�/��/J�/�/8�/N�/�/��/-0�<0*A0kA0Mb0ۘ0C�0��0G�0��0��0e�0��0�0l�08�0n�0F111N1�O1�W1�b1`c1�m1to1hs1�1��1 �17�1F�1 �1�1��1��1��1,�1��1��1��1��1�2�282q2S2�$2E(2 +2",2�12�42�92�G2�L2=N2�N2 R2PT2�V2[2�\2^^2;d2�y2|2��2��2�2M�24�2�2v�2Ӟ2<�2�2��2:�2p�2x�2��2��2��2��3Z�3��3��3�3��3��3��3T�3��3�.4�64u�4P�4�4� 5D 5�5�5_,5 05�:5�;5p?5[T5I�5+�5��5��5i�5t�5�5��5H6�6 6�6�6 6!6�!6�$6_,6�36]C6�I6IJ6�U6�[6W]6��6��6v�6K�6��6�60�6��6 �6[�6��6��6��6e�6,�6d7PO7�t7�v7/|7�7T�7��76�7��7��7F�7{�7t�7��7ӱ7package org.censorship.spring.enums; public enum ProviderType { BROAD_BAND, MOBILE_NETWORK } package cn.easy4j.admin.core.security; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; /** * @author yangzongmin * @since 2020/8/2 21:03 */ @Setter @Getter @ToString public class UserInfoResponse implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("openid") private String openId; @JsonProperty("unionid") private String unionId; private String nickname; private Integer sex; private String country; private String province; private String city; private String language; @JsonProperty("headimgurl") private String headImgUrl; } package com.lms.pojos.course; import com.lms.pojos.BasePojo; import com.lms.pojos.course.CourseQTAnswerPojo; import com.lms.pojos.course.CourseQTQuestionPojo; import lombok.Data; import java.util.List; @Data public class CourseQTUserAnswerPojo extends BasePojo { private String questionPublicKey; private List answerPublicKeys; private String text; } gagneet/hadoop-20 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.Test; import org.junit.After; import org.junit.BeforeClass; import org.junit.AfterClass; import static org.junit.Assert.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.util.InjectionEvent; import org.apache.hadoop.hdfs.util.InjectionHandler; import static org.apache.hadoop.hdfs.server.namenode.TestListCorruptFileBlocks. countPaths; public class TestAvatarAPI { final static Log LOG = LogFactory.getLog(TestAvatarAPI.class); private static final String FILE_PATH = "/dir1/dir2/myfile"; private static final String DIR_PATH = "/dir1/dir2"; private static final long FILE_LEN = 512L * 1024L; private static final long MAX_WAIT = 30000L; private Configuration conf; private MiniAvatarCluster cluster; private DistributedAvatarFileSystem dafs; private Path path; private Path dirPath; @BeforeClass public static void setUpClass() throws Exception { MiniAvatarCluster.createAndStartZooKeeper(); } /** * Set up MiniAvatarCluster. */ public void setUp(boolean federation, String name) throws Exception { LOG.info("------------------- test: " + name + " START ----------------"); conf = new Configuration(); // populate repl queues on standby (in safe mode) conf.setFloat("dfs.namenode.replqueue.threshold-pct", 0f); conf.setLong("fs.avatar.standbyfs.initinterval", 1000); conf.setLong("fs.avatar.standbyfs.checkinterval", 1000); if (!federation) { cluster = new MiniAvatarCluster(conf, 3, true, null, null); dafs = cluster.getFileSystem(); } else { cluster = new MiniAvatarCluster(conf, 3, true, null, null, 1, true); dafs = cluster.getFileSystem(0); } path = new Path(FILE_PATH); dirPath = new Path(DIR_PATH); DFSTestUtil.createFile(dafs, path, FILE_LEN, (short) 1, 0L); DFSTestUtil.waitReplication(dafs, path, (short) 1); try { Thread.sleep(4000); } catch (InterruptedException ignore) { } } private void checkPrimary() throws Exception { FileStatus fs = dafs.getFileStatus(path, false); FileStatus[] dir = dafs.listStatus(dirPath, false); RemoteIterator cfb = dafs.listCorruptFileBlocks(dirPath, false); assertTrue("DAFS file status has the wrong length", fs != null && fs.getLen() == FILE_LEN); assertTrue("DAFS directory listing has the wrong length", dir != null && dir.length == 1); assertTrue("DAFS expected 0 corrupt file blocks", countPaths(cfb) == 0); ContentSummary cs = dafs.getContentSummary(path, false); DatanodeInfo[] di = dafs.getDataNodeStats(false); assertTrue("DAFS datanode info should contain 3 data nodes", di.length == 3); } private void checkStandby() throws Exception { FileStatus fs = null; FileStatus[] dir = null; long startTime = System.currentTimeMillis(); while ((fs == null || dir == null || dir.length == 0 || dafs.getDataNodeStats(true).length != 3) && (System.currentTimeMillis() < startTime + MAX_WAIT)) { try { fs = dafs.getFileStatus(path, true); dir = dafs.listStatus(dirPath, true); } catch (FileNotFoundException fe) { LOG.info("DAFS File not found on standby avatar, retrying."); } if (fs == null) { LOG.info("DAFS file " + path.toString() + " not found"); } if (dir == null) { LOG.info("DAFS dir " + dirPath.toString() + " not found"); } else { if (dir.length == 0) { LOG.info("DAFS dir " + dirPath.toString() + " is empty"); } } try { Thread.sleep(100); } catch (InterruptedException ignore) { } } assertTrue("DAFS file status has the wrong length", fs != null && fs.getLen() == FILE_LEN); assertTrue("DAFS directory listing has the wrong length", dir != null && dir.length == 1); ContentSummary cs = dafs.getContentSummary(path, true); DatanodeInfo[] di = dafs.getDataNodeStats(true); assertEquals("DAFS datanode info should contain 3 data nodes", 3, di.length); } @Test public void testPrimaryShutdownFailure() throws Exception { setUp(false, "testPrimaryShutdownFailure"); InjectionHandler.set(new TestAvatarAPIHandler()); LOG.info("DAFS testPrimary"); try { cluster.killPrimary(); fail("Shutting down the node should fail"); } catch (IOException e) { assertTrue(e.toString().contains("number of required edit streams")); } InjectionHandler.clear(); } /** * Read from primary avatar. */ @Test public void testPrimary() throws Exception { setUp(false, "testPrimary"); LOG.info("DAFS testPrimary"); cluster.killStandby(); checkPrimary(); } /** * Read from standby avatar. */ @Test public void testStandby() throws Exception { setUp(false, "testStandby"); LOG.info("DAFS testStandby"); long lastTxId = getLastTxId(); cluster.killPrimary(false); // make sure to consume all transactions. cluster.getStandbyAvatar(0).avatar.quiesceStandby(lastTxId); checkStandby(); } /** * Test if we can still read standby after failover. */ @Test public void testFailOver() throws Exception { setUp(false, "testFailOver"); LOG.info("DAFS testFailOver"); long lastTxId = getLastTxId(); cluster.killPrimary(); cluster.failOver(); cluster.restartStandby(); cluster.waitAvatarNodesActive(); cluster.waitDataNodesActive(); // make sure to consume all transactions. cluster.getStandbyAvatar(0).avatar.quiesceStandby(lastTxId); try { Thread.sleep(2000); } catch (InterruptedException ignore) { } checkStandby(); checkPrimary(); } @Test public void testStandbyWithFederation() throws Exception { setUp(true, "testStandbyWithFederation"); LOG.info("DAFS testStandby"); long lastTxId = getLastTxId(); cluster.killPrimary(0, false); // make sure to consume all transactions cluster.getStandbyAvatar(0).avatar.quiesceStandby(lastTxId); checkStandby(); } @Test public void testPrimaryWithFederation() throws Exception { setUp(true, "testPrimaryWithFederation"); LOG.info("DAFS testPrimary"); cluster.killStandby(0); checkPrimary(); } @Test public void testFailOverWithFederation() throws Exception { setUp(true, "testFailoverWithFederation"); LOG.info("DAFS testFailOver"); long lastTxId = getLastTxId(); cluster.killPrimary(0); cluster.failOver(0); cluster.restartStandby(0); cluster.waitAvatarNodesActive(0); cluster.waitDataNodesActive(0); // make sure to consume all transactions. cluster.getStandbyAvatar(0).avatar.quiesceStandby(lastTxId); try { Thread.sleep(2000); } catch (InterruptedException ignore) { } checkStandby(); checkPrimary(); } private long getLastTxId(){ return cluster.getPrimaryAvatar(0).avatar.getFSImage().getEditLog() .getCurrentTxId() - 1; } @After public void shutDown() throws Exception { dafs.close(); cluster.shutDown(); } @AfterClass public static void shutDownClass() throws Exception { MiniAvatarCluster.shutDownZooKeeper(); } private static class TestAvatarAPIHandler extends InjectionHandler { @Override public boolean _falseCondition(InjectionEvent event, Object... args) { if (event == InjectionEvent.AVATARNODE_CHECKEDITSTREAMS) { return true; } return false; } } } 0 package com.google.android.gms.wearable; import android.os.Parcel; import android.os.Parcelable; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; import com.google.android.gms.internal.C1781jv; /* renamed from: com.google.android.gms.wearable.c */ public class C2703c implements SafeParcelable { public static final Parcelable.Creator CREATOR = new C2704d(); /* renamed from: CK */ final int f4531CK; /* renamed from: Gt */ private final int f4532Gt; /* renamed from: TW */ private final String f4533TW; private final int axc; private final boolean axd; private boolean axe; private String axf; private final String mName; C2703c(int i, String str, String str2, int i2, int i3, boolean z, boolean z2, String str3) { this.f4531CK = i; this.mName = str; this.f4533TW = str2; this.f4532Gt = i2; this.axc = i3; this.axd = z; this.axe = z2; this.axf = str3; } public int describeContents() { return 0; } public boolean equals(Object obj) { if (!(obj instanceof C2703c)) { return false; } C2703c cVar = (C2703c) obj; return C1781jv.equal(Integer.valueOf(this.f4531CK), Integer.valueOf(cVar.f4531CK)) && C1781jv.equal(this.mName, cVar.mName) && C1781jv.equal(this.f4533TW, cVar.f4533TW) && C1781jv.equal(Integer.valueOf(this.f4532Gt), Integer.valueOf(cVar.f4532Gt)) && C1781jv.equal(Integer.valueOf(this.axc), Integer.valueOf(cVar.axc)) && C1781jv.equal(Boolean.valueOf(this.axd), Boolean.valueOf(cVar.axd)); } public String getAddress() { return this.f4533TW; } public String getName() { return this.mName; } public int getRole() { return this.axc; } public int getType() { return this.f4532Gt; } public int hashCode() { return C1781jv.hashCode(Integer.valueOf(this.f4531CK), this.mName, this.f4533TW, Integer.valueOf(this.f4532Gt), Integer.valueOf(this.axc), Boolean.valueOf(this.axd)); } public boolean isConnected() { return this.axe; } public boolean isEnabled() { return this.axd; } /* renamed from: rj */ public String mo19409rj() { return this.axf; } public String toString() { StringBuilder sb = new StringBuilder("ConnectionConfiguration[ "); sb.append("mName=" + this.mName); sb.append(", mAddress=" + this.f4533TW); sb.append(", mType=" + this.f4532Gt); sb.append(", mRole=" + this.axc); sb.append(", mEnabled=" + this.axd); sb.append(", mIsConnected=" + this.axe); sb.append(", mEnabled=" + this.axf); sb.append("]"); return sb.toString(); } public void writeToParcel(Parcel parcel, int i) { C2704d.m7911a(this, parcel, i); } } 10-100 package com.readytalk.swt.text.navigation; import java.net.URL; /** * NavigationEvent is passed to a NavigationListener when the navigate * call is triggered (via a mouseup event in TextPainter falling within * a Hyperlink boundary). Its sole purpose is to notify the listener * of which URL was clicked enabling the listener to respond. */ public class NavigationEvent { Hyperlink hyperlink; /** * Creates a NavigationEvent containing the given Hyperlink. */ public NavigationEvent(Hyperlink hyperlink) { this.hyperlink = hyperlink; } /** * Gets the URL from the internal Hyperlink. * @return URL */ public URL getUrl() { return hyperlink.getURL(); } } 0 package de.hhn.mebike.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import de.hhn.mebike.model.Tour; import de.hhn.mebike.model.TourPoint; @Repository public interface TourPointRepository extends JpaRepository { List findByTour(Tour tour); } ncellar/caxap package util; /** * Unchecked exception wrapping checked exceptions that can happen * when using {@link util.MemberAccessor}. */ @SuppressWarnings("serial") public class MemberAccessException extends RuntimeException { /****************************************************************************/ public MemberAccessException(String message, Throwable cause) { super(message, cause); } /****************************************************************************/ public MemberAccessException(Throwable cause) { super(cause); } }aravindrajpalani/GoalApp /* * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://mindorks.com/license/apache-v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.social.goalapp.data.network; import com.social.goalapp.data.network.model.BlogResponse; import com.social.goalapp.data.network.model.LoginRequest; import com.social.goalapp.data.network.model.LoginResponse; import com.social.goalapp.data.network.model.Profile; import com.social.goalapp.data.network.model.Result; import okhttp3.ResponseBody; import retrofit2.Call; public class AppApiHelper implements ApiHelper { public static AppApiHelper INSTANCE; public static AppApiHelper getInstance() { if (INSTANCE == null) { INSTANCE = new AppApiHelper(); return INSTANCE; } else { return INSTANCE; } } @Override public Call registerUsers(LoginRequest params) { return APIClient.getClient().create(APIInterface.class).registerUsers(params); } @Override public Call getAllGoals(String token) { return APIClient.getClient().create(APIInterface.class).getAllGoals(token); } @Override public Call likeGoal(String token, int id) { return APIClient.getClient().create(APIInterface.class).likeGoal(token,id); } @Override public Call getMyGoal(String token) { return APIClient.getClient().create(APIInterface.class).getMyGoal(token); } @Override public Call addComment(String token, int id, String comment) { return APIClient.getClient().create(APIInterface.class).addComment(token,id,comment); } @Override public Call deleteGoal(String token, int id) { return APIClient.getClient().create(APIInterface.class).deleteGoal(token,id); } @Override public Call addGoal(String token, String content, int goaldays) { return APIClient.getClient().create(APIInterface.class).addGoal(token,content,goaldays); } @Override public Call getProfile(String token, int id) { return APIClient.getClient().create(APIInterface.class).getProfile(token,id); } @Override public Call patchGoalStatus(String token, int id, String status) { return APIClient.getClient().create(APIInterface.class).updateGoalStatus(token,id,status); } } /* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.container.glassfish.remote_3; import java.io.File; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; /** * A JUnit 4 test suite that manages the lifecycle of a locally-installed * GlassFish instance in order to test the JSR 88 deployment. * *

This class relies on the system property glassfish.install.dir * to point to a valid installation of GlassFish v3.

* * @author */ @RunWith(Suite.class) @SuiteClasses({ GlassFishJSR88RemoteContainerWARTestCase.class, GlassFishJSR88RemoteContainerEARTestCase.class}) public class GlassFishJSR88RemoteContainerTestSuite { @BeforeClass public static void startContainer() throws Exception { Runtime.getRuntime().exec(new String[] { getAsadminCommand(), "start-domain", "tests"}).waitFor(); } @AfterClass public static void stopContainer() throws Exception { Runtime.getRuntime().exec(new String[] { getAsadminCommand(), "stop-domain", "tests"}).waitFor(); } public static String getAsadminCommand() { File asadminFile = new File(System.getProperty("glassfish.install.dir") + File.separator + "bin" + File.separator + "asadmin"); if (!asadminFile.exists() || !asadminFile.isFile()) { Assert.fail("Path to asadmin command is invalid: " + asadminFile.getAbsolutePath()); } return asadminFile.getAbsolutePath(); } } package de.tu_darmstadt.sport.fvf.handler; import java.util.HashMap; import java.util.Map; import org.eclipse.ui.AbstractSourceProvider; import de.tu_darmstadt.sport.fvf.validators.OSValidator; public class OSProvider extends AbstractSourceProvider { public final static String OS = "de.tu_darmstadt.sport.fvf.os"; public final static String MAC = "mac"; public final static String WINDOWS = "windows"; public final static String SOLARIS = "solaris"; public final static String UNIX = "unix"; public final static String UNKNOWN = "unknown"; public OSProvider() { } @Override public void dispose() { } @Override public Map getCurrentState() { Map currentState = new HashMap(1); if (OSValidator.isMac()) { currentState.put(OS, MAC); } else if (OSValidator.isSolaris()) { currentState.put(OS, SOLARIS); } else if (OSValidator.isWindows()) { currentState.put(OS, WINDOWS); } else if (OSValidator.isUnix()) { currentState.put(OS, UNIX); } else { currentState.put(OS, UNKNOWN); } return currentState; } @Override public String[] getProvidedSourceNames() { return new String[] {OS}; } } package org.criteria4jpa; import static org.testng.Assert.fail; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.spi.PersistenceProvider; import org.dbunit.DatabaseUnitException; import org.dbunit.database.DatabaseConfig; import org.dbunit.database.DatabaseConnection; import org.dbunit.database.IDatabaseConnection; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.dbunit.ext.hsqldb.HsqldbDataTypeFactory; import org.dbunit.operation.DatabaseOperation; import org.testng.annotations.BeforeClass; public abstract class AbstractIntegrationTest extends AbstractTest { private final static String PERSISTENCE_UNIT = "integration-test"; private final static String JPA_PROVIDER_KEY = "jpa.provider"; private final String datasetName; protected EntityManager entityManager; public AbstractIntegrationTest(String relativeDatasetName) { this.datasetName = AbstractIntegrationTest.class.getPackage().getName().replace(".", "/")+ "/"+relativeDatasetName; } @BeforeClass public void initDatabase() { // check for JPA provider system property String selectedProvider = System.getProperty(JPA_PROVIDER_KEY, "default"); // Hibernate (default) if( selectedProvider.equals( "hibernate" ) ) { entityManager = createEntityManager("org.hibernate.ejb.HibernatePersistence"); } // OpenJPA else if( selectedProvider.equals( "openjpa" )) { entityManager = createEntityManager("org.apache.openjpa.persistence.PersistenceProviderImpl"); } // Toplink Essentials else if( selectedProvider.equals( "toplink" )) { entityManager = createEntityManager("oracle.toplink.essentials.PersistenceProvider"); } // Eclipse Link else if( selectedProvider.equals("eclipselink") ) { entityManager = createEntityManager("org.eclipse.persistence.jpa.PersistenceProvider"); } // auto-detect provider else { entityManager = createEntityManager(null); } // populate database try { // create JDBC connection Class.forName("org.hsqldb.jdbcDriver"); Connection connection = DriverManager.getConnection("jdbc:hsqldb:mem:testdb", "sa", ""); // load dataset ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL datasetUrl = classLoader.getResource(datasetName); IDataSet dataset = new FlatXmlDataSet(datasetUrl); // insert data IDatabaseConnection databaseConnection = new DatabaseConnection(connection); databaseConnection.getConfig().setProperty( DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory()); DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, dataset); } catch (SQLException e) { fail("Failed", e); } catch (ClassNotFoundException e) { fail("Cannot load JDBC driver", e); } catch (DatabaseUnitException e) { fail("Failed", e); } catch (IOException e) { fail("Failed", e); } } /** * Creates an {@link EntityManager} using the specified JPA SPI provider class. */ private static EntityManager createEntityManager(String providerClazz) { try { // the EntityManagerFactory EntityManagerFactory factory = null; // Do we want to use a specific provider? if( providerClazz != null ) { // create provider from class name PersistenceProvider provider = (PersistenceProvider) Class.forName(providerClazz).newInstance(); // use this provider to create EntityManagerFactory factory = provider.createEntityManagerFactory(PERSISTENCE_UNIT, null); } else { // create factory by auto-detecting the provider factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, null); } // build EntityManager return factory.createEntityManager(); } catch (InstantiationException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } } jorisdgff/SomeBigSystem package jorisdgffdemos.somebigsystem.crosscuttingconcerns; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class MongoLogger { private static MongoLogger instance; private MongoCollection collection; private MongoLogger(){ MongoClient mongoClient = new MongoClient(); MongoDatabase database = mongoClient.getDatabase("Logs"); collection = database.getCollection("logs"); } public void write(String message){ Document doc = new Document(); doc.append("message", message); collection.insertOne(doc); } public static MongoLogger getInstance() { if(instance == null){ instance = new MongoLogger(); } return instance; } } src/main/java/cn/edu/nwpu/dao/MixDefenderMapper.java package cn.edu.nwpu.dao; import cn.edu.nwpu.pojo.MixDefender; import java.util.List; public interface MixDefenderMapper { int deleteByPrimaryKey(Integer id); int insert(MixDefender record); int insertSelective(MixDefender record); List selectDefenderAll(); MixDefender selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(MixDefender record); int updateByPrimaryKey(MixDefender record); }/** * NSGAII_Settings.java * * @author * @version 1.0 * * NSGAII_Settings class of algorithm NSGAII */ package jmetal.experiments.settings; import jmetal.metaheuristics.nsgaII.*; import jmetal.base.*; import jmetal.base.operator.crossover.Crossover; import jmetal.base.operator.mutation.Mutation; import jmetal.base.operator.crossover.CrossoverFactory; import jmetal.base.operator.mutation.MutationFactory; import jmetal.base.operator.selection.Selection; import jmetal.base.operator.selection.SelectionFactory; import jmetal.experiments.Settings; import jmetal.qualityIndicator.QualityIndicator; import jmetal.util.JMException; /** * @author */ public class NSGAII_Settings extends Settings { public int populationSize_ = 100 ; public int maxEvaluations_ = 25000 ; public double mutationProbability_ = 1.0/problem_.getNumberOfVariables() ; public double crossoverProbability_ = 0.9 ; public double mutationDistributionIndex_ = 20.0 ; public double crossoverDistributionIndex_ = 20.0 ; /** * Constructor * @throws JMException */ public NSGAII_Settings(Problem problem) throws JMException { super(problem) ; } // NSGAII_Settings /** * Configure NSGAII with user-defined parameter settings * @return A NSGAII algorithm object * @throws jmetal.util.JMException */ public Algorithm configure() throws JMException { Algorithm algorithm ; Selection selection ; Crossover crossover ; Mutation mutation ; QualityIndicator indicators ; // Creating the algorithm. There are two choices: NSGAII and its steady- // state variant ssNSGAII algorithm = new NSGAII(problem_) ; //algorithm = new ssNSGAII(problem_) ; // Algorithm parameters algorithm.setInputParameter("populationSize",populationSize_); algorithm.setInputParameter("maxEvaluations",maxEvaluations_); // Mutation and Crossover for Real codification crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover"); crossover.setParameter("probability",crossoverProbability_); crossover.setParameter("distributionIndex",crossoverDistributionIndex_); mutation = MutationFactory.getMutationOperator("PolynomialMutation"); mutation.setParameter("probability",mutationProbability_); mutation.setParameter("distributionIndex",crossoverDistributionIndex_); // Selection Operator selection = (Selection) SelectionFactory.getSelectionOperator("BinaryTournament2") ; // Add the operators to the algorithm algorithm.addOperator("crossover",crossover); algorithm.addOperator("mutation",mutation); algorithm.addOperator("selection",selection); // Creating the indicator object if ((paretoFrontFile_!=null) && (!paretoFrontFile_.equals(""))) { indicators = new QualityIndicator(problem_, paretoFrontFile_); algorithm.setInputParameter("indicators", indicators) ; } // if return algorithm ; } // configure } // NSGAII_Settings /* * Copyright 2015 . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teavm.flavour.templates.emitting; import static org.teavm.metaprogramming.Metaprogramming.exit; import static org.teavm.metaprogramming.Metaprogramming.getClassLoader; import static org.teavm.metaprogramming.Metaprogramming.getDiagnostics; import static org.teavm.metaprogramming.Metaprogramming.unsupportedCase; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.List; import org.teavm.flavour.expr.ClassPathClassResolver; import org.teavm.flavour.expr.Diagnostic; import org.teavm.flavour.expr.type.meta.ClassPathClassDescriberRepository; import org.teavm.flavour.templates.BindTemplate; import org.teavm.flavour.templates.Fragment; import org.teavm.flavour.templates.parsing.ClassPathResourceProvider; import org.teavm.flavour.templates.parsing.Parser; import org.teavm.flavour.templates.tree.TemplateNode; import org.teavm.metaprogramming.Diagnostics; import org.teavm.metaprogramming.Metaprogramming; import org.teavm.metaprogramming.ReflectClass; import org.teavm.metaprogramming.SourceLocation; import org.teavm.metaprogramming.Value; public class TemplatingProxyGenerator { public void generate(Value model, ReflectClass modelType) { TemplateInfo template = parseForModel(modelType, Metaprogramming.getLocation()); if (template != null) { TemplateEmitter emitter = new TemplateEmitter(template.locationMapper); Value fragment = emitter.emitTemplate(model, template.sourceFileName, template.body); exit(() -> fragment.get()); } else { unsupportedCase(); } } private TemplateInfo parseForModel(ReflectClass cls, SourceLocation location) { Diagnostics diagnostics = getDiagnostics(); BindTemplate annot = cls.getAnnotation(BindTemplate.class); if (annot == null) { return null; } String path = annot.value(); ClassLoader classLoader = getClassLoader(); ClassPathClassDescriberRepository classRepository = new ClassPathClassDescriberRepository(classLoader); ClassPathClassResolver classResolver = new ClassPathClassResolver(classLoader); ClassPathResourceProvider resourceProvider = new ClassPathResourceProvider(classLoader); Parser parser = new Parser(classRepository, classResolver, resourceProvider); List fragment; try (InputStream input = classLoader.getResourceAsStream(path)) { if (input == null) { diagnostics.error(location, "Can't create template for {{c0}}: " + "template " + path + " was not found", cls.getName()); return null; } fragment = parser.parse(new InputStreamReader(input, "UTF-8"), cls.getName()); } catch (IOException e) { diagnostics.error(location, "Can't create template for {{c0}}: " + "template " + path + " was not found", cls.getName()); return null; } OffsetToLineMapper mapper = new OffsetToLineMapper(); try (Reader reader = new InputStreamReader(classLoader.getResourceAsStream(path), "UTF-8")) { mapper.prepare(reader); } catch (IOException e) { diagnostics.error(location, "Can't create template for {{c0}}: template " + path + " was not found", cls.getName()); return null; } if (!parser.getDiagnostics().isEmpty()) { for (Diagnostic diagnostic : parser.getDiagnostics()) { SourceLocation diagnosticLocation = location != null ? new SourceLocation(location.getMethod(), path, mapper.getLine(diagnostic.getStart()) + 1) : null; diagnostics.error(diagnosticLocation, diagnostic.getMessage()); } } TemplateInfo info = new TemplateInfo(); info.sourceFileName = path; info.body = fragment; info.locationMapper = mapper; return info; } static class TemplateInfo { String sourceFileName; OffsetToLineMapper locationMapper; List body; } } MickeyJS/GoGame-3 package com.javago.test.client;lucas-bremond/ccsds10-100 /* * Copyright (c) 2019 (https://www.dariolucia.eu) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.dariolucia.ccsds.tmtc.cop1.fop; import eu.dariolucia.ccsds.tmtc.datalink.pdu.TcTransferFrame; import eu.dariolucia.ccsds.tmtc.ocf.pdu.Clcw; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Supplier; /** * This class implements the FOP side of the COP-1 protocol, as defined by CCSDS 232.1-B-2 Cor. 1. * * This class is thread-safe. */ @SuppressWarnings("StatementWithEmptyBody") public class FopEngine { public static final String ANNOTATION_BC_FRAME_TAG = "##BC_FRAME_TAG"; private final int virtualChannelId; private final Supplier nextVirtualChannelFrameCounterGetter; private final Consumer nextVirtualChannelFrameCounterSetter; private final Supplier bcFrameUnlockFactory; private final IntFunction bcFrameSetVrFactory; private final ExecutorService fopExecutor; private volatile Thread confinementThread; // NOSONAR only used for reference equality comparison private final ExecutorService lowLevelExecutor; private final List observers = new CopyOnWriteArrayList<>(); private final AtomicReference pendingAcceptRejectResult = new AtomicReference<>(); private final AtomicReference pendingAcceptRejectFrame = new AtomicReference<>(); private final AtomicReference pendingEventResult = new AtomicReference<>(); private final AtomicReference pendingInitAd = new AtomicReference<>(); /** * This is the variable encapsulating what the standard calls 'Lower Level Procedures' or 'Lower Procedures'. In this implementation, * this is a function called asynchronously by the lowLevelExecutor, which returns true (frame accepted) or false * (frame rejected). There is no abort() operation defined in this implementation. */ private final Function output; private final Timer fopTimer; private TimerTask currentTimer; // --------------------------------------------------------------------------------------------------------- // FOP variables as per CCSDS 232.1-B-2 Cor. 1, section 5.1 // --------------------------------------------------------------------------------------------------------- /** * This variable represents the state of FOP-1 for the specific Virtual Channel. */ private AbstractFopState state; /* * The Transmitter_Frame_Sequence_Number, V(S), contains the value of the Frame Sequence * Number, N(S), to be put in the Transfer Frame Primary Header of the next Type-AD * Transfer Frame to be transmitted. * In this implementation, this information is in the tcVc object: tcVc.getNextVirtualChannelFrameCounter() */ /** * When Type-AD FDUs are received from the Higher Procedures, they shall be held in the * Wait_Queue until they can be accepted by FOP-1. The Wait_Queue has a maximum * capacity of one FDU. * The Wait_Queue and 'Accept Response to Request to Transfer FDU' form the primary * mechanism by which flow control as seen by the Higher Procedures is governed. When an * FDU is on the Wait_Queue, this means that the Higher Procedures have not yet received an * 'Accept Response' for the corresponding 'Request to Transfer FDU'. */ private final AtomicReference waitQueue = new AtomicReference<>(null); /** * Whether or not a ‘Transmit Request for Frame’ can be sent for AD. If true, means READY. */ private volatile boolean adOutReadyFlag = true; /** * Whether or not a ‘Transmit Request for Frame’ can be sent for BD. If true, means READY. */ private volatile boolean bdOutReadyFlag = true; /** * Whether or not a ‘Transmit Request for Frame’ can be sent for BC. If true, means READY. */ private volatile boolean bcOutReadyFlag = true; /** * The Sent_Queue is a Virtual Channel data structure in which the master copy of all Type-AD * and Type-BC Transfer Frames on a Virtual Channel is held between the time a copy of the * Transfer Frame is first passed to the Lower Procedures for transmission, and the time the * FOP-1 has finished processing the Transfer Frame. */ private final Queue sentQueue = new LinkedList<>(); /** * The Expected_Acknowledgement_Frame_Sequence_Number, NN(R), contains the Frame * Sequence Number of the oldest unacknowledged AD Frame, which is on the Sent_Queue. * This value is often equal to the value of N(R) from the previous CLCW on that Virtual * Channel. */ private int expectedAckFrameSequenceNumber; // NN(R) /** * Whenever a Type-AD or Type-BC Transfer Frame is transmitted, the Timer shall be started * or restarted with an initial value of Timer_Initial_Value (T1_Initial). */ private int timerInitialValue; /** * The Transmission_Limit holds a value which represents the maximum number of times the * first Transfer Frame on the Sent_Queue may be transmitted. This includes the first * 'transmission' and any subsequent 'retransmissions' of the Transfer Frame. */ private int transmissionLimit; /** * The Timeout_Type variable may take one of two values, '0' or '1'. * It specifies the action to be performed when both the Timer expires and the * Transmission_Count has reached the Transmission_Limit. */ private int timeoutType; // TT /** * The Transmission_Count variable is used to count the number of transmissions of the first * Transfer Frame on the Sent_Queue. The Transmission_Count shall be incremented each * time the first Transfer Frame is retransmitted. */ private int transmissionCount; /** * The Suspend_State variable may take one of five values, from '0' to * '4'. It records the state that FOP-1 was in when the AD Service was suspended. This is the state to * which FOP-1 will return should the AD Service be resumed. If SS = 0, the AD Service is deemed not suspended. */ private int suspendState; // SS /** * The FOP Sliding Window is a mechanism which limits the number of Transfer Frames which * can be transmitted ahead of the last acknowledged Transfer Frame, i.e., before a CLCW * report is received which updates the status of acknowledged Transfer Frames. This is done * to prevent sending a new Transfer Frame with the same sequence number as a rejected * Transfer Frame. */ private int fopSlidingWindow; // K /** * Constructor of the FOP engine. * * Being this class fully decoupled from the way {@link TcTransferFrame} are constructed and forwarded to the encoding * layer, the constructor accepts functional objects for the operations to be delegated to the external interfaces. * * @param virtualChannelId the TC virtual channel ID controlled by this FOP entity * @param nextVirtualChannelFrameCounterGetter a {@link Supplier} function to retrieve the next virtual channel frame counter * @param nextVirtualChannelFrameCounterSetter a {@link Consumer} function to set the next virtual channel frame counter * @param bcFrameUnlockFactory a {@link Function} to build a BC frame for FARM unlock * @param bcFrameSetVrFactory a {@link Function} to build a BC frame for FARM Set_V(R) * @param output a {@link Consumer} function to forward {@link TcTransferFrame} as output of the FOP engine */ public FopEngine(int virtualChannelId, Supplier nextVirtualChannelFrameCounterGetter, Consumer nextVirtualChannelFrameCounterSetter, Supplier bcFrameUnlockFactory, IntFunction bcFrameSetVrFactory, Function output) { this.virtualChannelId = virtualChannelId; this.nextVirtualChannelFrameCounterGetter = nextVirtualChannelFrameCounterGetter; this.nextVirtualChannelFrameCounterSetter = nextVirtualChannelFrameCounterSetter; this.bcFrameUnlockFactory = bcFrameUnlockFactory; this.bcFrameSetVrFactory = bcFrameSetVrFactory; this.output = output; this.fopExecutor = Executors.newSingleThreadExecutor(r -> { Thread t = new Thread(r); t.setDaemon(true); t.setName("FOP Entity Processor for TC VC " + virtualChannelId); FopEngine.this.confinementThread = t; return t; }); this.lowLevelExecutor = Executors.newSingleThreadExecutor(r -> { Thread t = new Thread(r); t.setDaemon(true); t.setName("FOP Entity Low Level for TC VC " + virtualChannelId); return t; }); // this.state = new S6FopState(this); // In principle, the ‘Initial’ State is the first state entered by the state machine for a particular Virtual Channel. // this.fopTimer = new Timer("FOP TC VC " + virtualChannelId + " Timer"); } /** * Return the TC virtual channel ID. * * @return the TC virtual channel ID */ public int getVirtualChannelId() { return virtualChannelId; } /** * Register an {@link IFopObserver} as listener to FOP state changes, alerts and suspends notifications, as well as * transfer frame and directive notifications. * * @param observer the observer to register */ public void register(IFopObserver observer) { this.observers.add(observer); } /** * Deregister an {@link IFopObserver} listener. * * @param observer the observer to deregister */ public void deregister(IFopObserver observer) { this.observers.remove(observer); } // --------------------------------------------------------------------------------------------------------- // FOP-1 public operations as per CCSDS definition for event injection // --------------------------------------------------------------------------------------------------------- /** * Request the FOP engine to execute a COP-1 directive. * * @param tag the request tag, which will be returned in the callback on the {@link IFopObserver} interface * @param directive the directive ID * @param qualifier the directive qualifier: if not meaningful, this argument can assume any value */ public void directive(Object tag, FopDirective directive, int qualifier) { fopExecutor.execute(() -> processDirective(tag, directive, qualifier)); } /** * Request the FOP engine to transmit a AD or BD frame. This operation allows simple flow control, as the method will * return when the frame will be either accepted or rejected by the FOP engine. * * The use of this operation is a convenience operation and shall not be mixed with the other transmit operation. The * behaviour of this class if the two operations are mixed is undefined. * * @param frame the frame to transmit * @param timeoutMillis the timeout in milliseconds waiting for acceptance or rejection of the request * @return true if the request was accepted, false it is was rejected or the timeout expired * @throws InterruptedException in case the invoking thread is interrupted */ public boolean transmit(TcTransferFrame frame, int timeoutMillis) throws InterruptedException { long expirationTime = System.currentTimeMillis() + timeoutMillis; if(frame.getFrameType() == TcTransferFrame.FrameType.BD) { return transmitSyncBD(frame, expirationTime); } else if(frame.getFrameType() == TcTransferFrame.FrameType.AD) { return transmitSyncAD(frame, expirationTime); } else { throw new IllegalArgumentException("This method can be invoked only for BD and AD frames"); } } /** * BD frames can be unblocked as soon as a REJECT_RESPONSE is received (event E22), or events E45 or E46 are received. * * @param frame the frame to send * @param expirationTime the absolute expiration time in ms since Java epoch * @return true if the request was accepted, false it is was rejected or the timeout expired * @throws InterruptedException in case the invoking thread is interrupted */ private boolean transmitSyncBD(TcTransferFrame frame, long expirationTime) throws InterruptedException { synchronized (pendingAcceptRejectFrame) { pendingAcceptRejectFrame.set(frame); pendingEventResult.set(null); transmit(frame); while (pendingEventResult.get() == null) { long timeout = expirationTime - System.currentTimeMillis(); if (timeout > 0) { pendingAcceptRejectFrame.wait(timeout); } if (System.currentTimeMillis() >= expirationTime) { break; } } FopEvent.EventNumber operationResult = pendingEventResult.getAndSet(null); pendingAcceptRejectFrame.set(null); return operationResult == FopEvent.EventNumber.E45; } } /** * AD frames can be unblocked as soon as an ACCEPT_RESPONSE or REJECT_RESPONSE is received. * * @param frame the frame to send * @param expirationTime the absolute expiration time in ms since Java epoch * @return true if the request was accepted, false it is was rejected or the timeout expired * @throws InterruptedException in case the invoking thread is interrupted */ private boolean transmitSyncAD(TcTransferFrame frame, long expirationTime) throws InterruptedException { synchronized (pendingAcceptRejectFrame) { pendingAcceptRejectFrame.set(frame); pendingAcceptRejectResult.set(null); transmit(frame); while (pendingAcceptRejectResult.get() == null) { long timeout = expirationTime - System.currentTimeMillis(); if (timeout > 0) { pendingAcceptRejectFrame.wait(timeout); } if (System.currentTimeMillis() >= expirationTime) { break; } } FopOperationStatus operationResult = pendingAcceptRejectResult.getAndSet(null); pendingAcceptRejectFrame.set(null); return operationResult == FopOperationStatus.ACCEPT_RESPONSE; } } /** * Request the FOP engine to transmit a AD or BD frame. This operation is fully asynchronous and does not implement * any flow control mechanism, as per COP-1 standard. Users of this method shall wait for the acceptance or rejection * of the frame as reported by the callback method on the {@link IFopObserver} interface. * * The use of this operation shall not be mixed with the other transmit operation. The behaviour of this class if * the two operations are mixed is undefined. * * @param frame the frame to transmit */ public void transmit(TcTransferFrame frame) { switch(frame.getFrameType()) { case AD: fopExecutor.execute(() -> processAdFrame(frame)); break; case BD: fopExecutor.execute(() -> processBdFrame(frame)); break; default: throw new IllegalArgumentException("TC Transfer Frame detected unsupported type for transmit operation: " + frame.getFrameType()); } } /** * Inform the FOP entity about the arrival of a new CLCW. The CLCW is processed only if reports COP-1 in effect, and * matches the TC VC specified at FOP engine construction time. * * @param clcw the CLCW to process */ public void clcw(Clcw clcw) { if(clcw.getCopInEffect() == Clcw.CopEffectType.COP1 && clcw.getVirtualChannelId() == virtualChannelId) { fopExecutor.execute(() -> processClcw(clcw)); } } /** * Dispose the FOP entity. This operation has the following effects: *
    *
  • the timer is cancelled
  • *
  • the wait and the sent queues are purged and related notifications are provided
  • *
  • the internal executors are shutdown
  • *
* * Calling other methods after that this method is invoked will likely cause the raising of {@link java.lang.reflect.InvocationTargetException} * due to the fact that the executors are shut down. */ public void dispose() { fopExecutor.submit(() -> { cancelTimer(); purgeWaitQueue(); purgeSentQueue(); }); this.fopExecutor.shutdown(); try { this.fopExecutor.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.lowLevelExecutor.shutdownNow(); } // --------------------------------------------------------------------------------------------------------- // FOP-1 actions defined as per CCSDS definition. All these actions are performed by the state transitions // and executed by the fopExecutor service. Thread access is enforced to avoid misuse. // --------------------------------------------------------------------------------------------------------- /** * This action includes clearing the Sent_Queue by generating a 'Negative Confirm Response to Request to * Transfer FDU' for each Transfer Frame on the queue and deleting the Transfer Frame. * * Ref. 5.2.2 */ void purgeSentQueue() { checkThreadAccess(); for(TransferFrameStatus tfs : this.sentQueue) { if(tfs.getFrame().getFrameType() == TcTransferFrame.FrameType.BC && this.pendingInitAd.get() != null) { // Directive: not on the standard Object[] directive = this.pendingInitAd.getAndSet(null); observers.forEach(o -> o.directiveNotification(this, FopOperationStatus.NEGATIVE_CONFIRM, directive[0], (FopDirective) directive[1], (int) directive[2])); } else { // Frame observers.forEach(o -> o.transferNotification(this, FopOperationStatus.NEGATIVE_CONFIRM, tfs.getFrame())); } } this.sentQueue.clear(); } /** * This action includes clearing the Wait_Queue and generating a 'Reject Response to Request to Transfer * FDU' for the queued FDU. * * Ref. 5.2.3 */ void purgeWaitQueue() { checkThreadAccess(); if(this.waitQueue.get() != null) { reject(this.waitQueue.get()); } this.waitQueue.set(null); } /** * This action includes all the functions necessary to prepare a Type-AD Transfer Frame for * transmission. * * Ref. 5.2.4 * * @param frame the frame to send */ void transmitTypeAdFrame(TcTransferFrame frame) { checkThreadAccess(); // a) // Not needed, handled by tcVc object boolean sentQueueWasEmpty = this.sentQueue.isEmpty(); // in preparation for c) this.sentQueue.add(new TransferFrameStatus(frame)); // b) if(sentQueueWasEmpty) { this.transmissionCount = 1; // c) } restartTimer(); // d) setAdOutReadyFlag(false); // e) lowLevelExecutor.execute(() -> forwardToOutput(frame)); // f) } /** * This action includes all the functions necessary to prepare a Type-BC Transfer Frame for * transmission. * * Ref. 5.2.5 * * @param frame the frame to send */ void transmitTypeBcFrame(TcTransferFrame frame) { checkThreadAccess(); this.sentQueue.add(new TransferFrameStatus(frame)); // a) this.transmissionCount = 1; // b) restartTimer(); // c) setBcOutReadyFlag(false); // d) lowLevelExecutor.execute(() -> forwardToOutput(frame)); // e) } /** * This action includes all the functions necessary to prepare a Type-BD Transfer Frame for * transmission. * * Ref. 5.2.6 * * @param frame the frame to send */ void transmitTypeBdFrame(TcTransferFrame frame) { checkThreadAccess(); setBdOutReadyFlag(false); // a) lowLevelExecutor.execute(() -> forwardToOutput(frame)); // b) } /** * Ref. 5.2.7 for AD */ void initiateAdRetransmission() { checkThreadAccess(); // a) Abort request to lower procedures not provided this.transmissionCount++; // b) restartTimer(); // c) this.sentQueue.stream().filter(o -> o.getFrame().getFrameType() == TcTransferFrame.FrameType.AD).forEach(o -> o.setToBeRetransmitted(true)); // d) } /** * Ref. 5.2.7 for BC */ void initiateBcRetransmission() { checkThreadAccess(); // a) Abort request to lower procedures not provided this.transmissionCount++; // b) restartTimer(); // c) this.sentQueue.stream().filter(o -> o.getFrame().getFrameType() == TcTransferFrame.FrameType.BC).forEach(o -> o.setToBeRetransmitted(true)); // d) } /** * Ref. 5.2.8 * * @param clcw the CLCW */ void removeAckFramesFromSentQueue(Clcw clcw) { checkThreadAccess(); boolean acked = true; while(acked && !this.sentQueue.isEmpty()) { TransferFrameStatus next = this.sentQueue.element(); // Inspect the first frame // No BC frames should be present here if(next.getFrame().getFrameType() == TcTransferFrame.FrameType.BC) { throw new IllegalStateException("No BC frames should be present in the sent queue when calling removeAckFramesFromSentQueue()"); } // The frame is acked if its frame counter is lower than the CLCW reported value (mod 256) // taking into account the FOP sliding window. // Compute the set of values that actually acknowledge the frame int currentNNR = next.getFrame().getVirtualChannelFrameCount(); Set expander = new HashSet<>(); for(int i = 0; i < fopSlidingWindow; ++i) { expander.add((currentNNR + 1 + i) % 256); } // If the set contains the clcw report, all fine if(expander.contains((int) clcw.getReportValue())) { // Acked - Confirm confirm(next.getFrame()); // a) this.sentQueue.remove(); // Update NN(R) this.expectedAckFrameSequenceNumber = (this.expectedAckFrameSequenceNumber + 1) % 256; // b) // Reset transmission count this.transmissionCount = 1; // c) // acked = true; } else { // Not acked yet acked = false; } } } /** * Ref. 5.2.9 */ void lookForDirective() { checkThreadAccess(); if(!bcOutReadyFlag) { // a) // If not, no further processing can be performed for retransmitting the Type-BC Transfer Frame until // a 'BC_Accept' Response is received from the Lower Procedures for the outstanding 'Transmit // Request for (BC) Frame', setting the BC_Out_Flag to 'Ready'. // NOSONAR not a block of code } else { // b) Optional optBcFrame = this.sentQueue.stream().filter(o -> o.getFrame().getFrameType() == TcTransferFrame.FrameType.BC).findFirst(); if(optBcFrame.isPresent() && optBcFrame.get().isToBeRetransmitted()) { setBcOutReadyFlag(false); optBcFrame.get().setToBeRetransmitted(false); // Not specified by the state machine, but if this is not done, the accept() of the lower procedure will trigger again a lookDirective that will send this lowLevelExecutor.execute(() -> forwardToOutput(optBcFrame.get().getFrame())); } } } /** * Ref. 5.2.10 */ void lookForFrame() { checkThreadAccess(); if(!adOutReadyFlag) { // a) // If not, no further processing can be performed for transmitting Type-AD Transfer Frames. In fact, when an 'AD_Accept' // Response is received from the Lower Procedures for the outstanding 'Transmit Request for (AD) Frame', FOP-1 will set // NOSONAR not a block of code // the AD_Out_Flag to 'Ready' and execute a new 'Look for FDU'. } else { // Checking if a Type-AD Transfer Frame on the Sent_Queue is flagged 'To_Be_Retransmitted'. If so, the flag // is set to 'Not_Ready' and a copy of the first such AD Transfer Frame is passed to the Lower Procedures as a parameter // of a 'Transmit Request for (AD) Frame' and the To_Be_Retransmitted_Flag for that Transfer Frame is reset. // NOSONAR not a block of code Optional optAdFrame = this.sentQueue.stream().filter(o -> o.getFrame().getFrameType() == TcTransferFrame.FrameType.AD).filter(TransferFrameStatus::isToBeRetransmitted).findFirst(); if(optAdFrame.isPresent()) { // b) optAdFrame.get().setToBeRetransmitted(false); setAdOutReadyFlag(false); lowLevelExecutor.execute(() -> forwardToOutput(optAdFrame.get().getFrame())); } else { // c) // If no Type-AD Transfer Frame is marked 'To_Be_Retransmitted', checking if both V(S) < NN(R) + K and // a Type-AD FDU is available on the Wait_Queue. If so, the FDU is removed from the Wait_Queue, an // 'Accept Response to Request to Transfer FDU' is passed to the Higher Layer, and the 'Transmit Type-AD Frame' // action for the FDU is performed. if(waitQueue.get() != null && waitQueue.get().getFrameType() == TcTransferFrame.FrameType.AD && lessThan(waitQueue.get().getVirtualChannelFrameCount(), (expectedAckFrameSequenceNumber + fopSlidingWindow), fopSlidingWindow)) { TcTransferFrame toTransmit = waitQueue.getAndSet(null); accept(toTransmit); transmitTypeAdFrame(toTransmit); } else { // d) // If no FDU is available on the Wait_Queue, or cannot be sent out, no further processing is performed. } } } } /** * Ref. 5.2.11 * * @param frame the frame to notify as accepted */ void accept(TcTransferFrame frame) { checkThreadAccess(); observers.forEach(o -> o.transferNotification(this, FopOperationStatus.ACCEPT_RESPONSE, frame)); synchronized (pendingAcceptRejectFrame) { if(pendingAcceptRejectFrame.get() == frame) { pendingAcceptRejectResult.set(FopOperationStatus.ACCEPT_RESPONSE); pendingAcceptRejectFrame.notifyAll(); } } } /** * Ref. 5.2.11 * * @param tag the directive tag to report as accepted * @param directive the directive type * @param qualifier the qualifier */ void accept(Object tag, FopDirective directive, int qualifier) { checkThreadAccess(); observers.forEach(o -> o.directiveNotification(this, FopOperationStatus.ACCEPT_RESPONSE, tag, directive, qualifier)); } /** * Ref. 5.2.12 * * @param frame the frame to notify as rejected */ void reject(TcTransferFrame frame) { checkThreadAccess(); synchronized (pendingAcceptRejectFrame) { if(pendingAcceptRejectFrame.get() == frame) { pendingAcceptRejectResult.set(FopOperationStatus.ACCEPT_RESPONSE); pendingAcceptRejectFrame.notifyAll(); } } observers.forEach(o -> o.transferNotification(this, FopOperationStatus.REJECT_RESPONSE, frame)); } /** * Ref. 5.2.12 * * @param tag the directive tag to report as rejected * @param directive the directive type * @param qualifier the qualifier */ void reject(Object tag, FopDirective directive, int qualifier) { checkThreadAccess(); observers.forEach(o -> o.directiveNotification(this, FopOperationStatus.REJECT_RESPONSE, tag, directive, qualifier)); } /** * Utility method to discriminate between frame or directive. To be called ONLY by the state machine handlers. * * @param fopEvent the event linked to the action to reject */ void reject(FopEvent fopEvent) { checkThreadAccess(); if(fopEvent.getFrame() != null) { reject(fopEvent.getFrame()); } else if(fopEvent.getDirectiveId() != null) { reject(fopEvent.getDirectiveTag(), fopEvent.getDirectiveId(), fopEvent.getDirectiveQualifier()); } else { throw new IllegalArgumentException("FOP event " + fopEvent + " not recognised for reject"); } } void confirm(TcTransferFrame frame) { checkThreadAccess(); observers.forEach(o -> o.transferNotification(this, FopOperationStatus.POSIIVE_CONFIRM, frame)); } void confirm(Object tag, FopDirective directive, int qualifier) { checkThreadAccess(); observers.forEach(o -> o.directiveNotification(this, FopOperationStatus.POSIIVE_CONFIRM, tag, directive, qualifier)); } void addToWaitQueue(FopEvent fopEvent) { checkThreadAccess(); this.waitQueue.set(fopEvent.getFrame()); } /** * Ref. 5.2.14 */ void initialise() { checkThreadAccess(); purgeSentQueue(); // a) purgeWaitQueue(); // b) this.transmissionCount = 1; // c) this.suspendState = 0; // d) } /** * Ref. 5.2.15 * * @param code the alert code */ void alert(FopAlertCode code) { checkThreadAccess(); cancelTimer(); // a) purgeSentQueue(); // b) purgeWaitQueue(); // c) // d) not understood: if the wait and the sent queues are purged, there is no other frame stored in the FOP engine at this stage observers.forEach(o -> o.alert(this, code)); // e) } /** * Ref. 5.2.16 */ void suspend() { checkThreadAccess(); observers.forEach(o -> o.suspend(this)); } /** * Ref. 5.2.17 */ void resume() { checkThreadAccess(); restartTimer(); // a) this.suspendState = 0; // b) } void restartTimer() { checkThreadAccess(); synchronized (fopTimer) { if(currentTimer != null) { currentTimer.cancel(); currentTimer = null; } currentTimer = new TimerTask() { @Override public void run() { timerExpired(this); } }; fopTimer.schedule(currentTimer, this.timerInitialValue * 1000L); } } void cancelTimer() { checkThreadAccess(); synchronized (fopTimer) { if(currentTimer != null) { currentTimer.cancel(); currentTimer = null; } } } void setFopSlidingWindow(int fopSlidingWindow) { checkThreadAccess(); this.fopSlidingWindow = fopSlidingWindow; } void setT1Initial(int t1initial) { checkThreadAccess(); this.timerInitialValue = t1initial; } void setTransmissionLimit(int limit) { checkThreadAccess(); this.transmissionLimit = limit; } void setTimeoutType(int type) { checkThreadAccess(); this.timeoutType = type; } void setAdOutReadyFlag(boolean flag) { checkThreadAccess(); this.adOutReadyFlag = flag; } void setBcOutReadyFlag(boolean flag) { checkThreadAccess(); this.bcOutReadyFlag = flag; } void setBdOutReadyFlag(boolean flag) { checkThreadAccess(); this.bdOutReadyFlag = flag; // Notify the state change: note that bdOutReadyFlag is volatile synchronized (pendingAcceptRejectFrame) { pendingAcceptRejectFrame.notifyAll(); } } void transmitTypeBcFrameUnlock(Object tag) { checkThreadAccess(); TcTransferFrame frame = bcFrameUnlockFactory.get(); frame.setAnnotationValue(ANNOTATION_BC_FRAME_TAG, tag); transmitTypeBcFrame(frame); } void transmitTypeBcFrameSetVr(Object tag, int vr) { checkThreadAccess(); TcTransferFrame frame = bcFrameSetVrFactory.apply(vr); frame.setAnnotationValue(ANNOTATION_BC_FRAME_TAG, tag); transmitTypeBcFrame(frame); } void setSuspendState(int suspendState) { checkThreadAccess(); this.suspendState = suspendState; } void prepareForSetVr(int vstarr) { checkThreadAccess(); nextVirtualChannelFrameCounterSetter.accept(vstarr); this.expectedAckFrameSequenceNumber = vstarr; } void setVs(int vstars) { checkThreadAccess(); nextVirtualChannelFrameCounterSetter.accept(vstars); this.expectedAckFrameSequenceNumber = vstars; } void registerPendingInitAd(Object directiveTag, FopDirective directiveId, int directiveQualifier) { checkThreadAccess(); this.pendingInitAd.set(new Object[] {directiveTag, directiveId, directiveQualifier}); } void confirmPendingInitAdWithClcw(Clcw clcw) { checkThreadAccess(); Object[] pendingDirective = this.pendingInitAd.getAndSet(null); if(pendingDirective != null) { // Set the V(S) and NN(R) to the value in the CLCW? setVs(clcw.getReportValue()); confirm(pendingDirective[0], (FopDirective) pendingDirective[1], (int) pendingDirective[2]); } } void confirmPendingInitAdWithBcFrame() { checkThreadAccess(); Object[] pendingDirective = this.pendingInitAd.getAndSet(null); if(pendingDirective != null) { confirm(pendingDirective[0], (FopDirective) pendingDirective[1], (int) pendingDirective[2]); } } void releaseBcFrame() { checkThreadAccess(); Optional optBcFrame = this.sentQueue.stream().filter(o -> o.getFrame().getFrameType() == TcTransferFrame.FrameType.BC).findFirst(); optBcFrame.ifPresent(this.sentQueue::remove); } // --------------------------------------------------------------------------------------------------------- // FOP-1 methods performed by the fopExecutor (thread confinement) // --------------------------------------------------------------------------------------------------------- private void processClcw(Clcw clcw) { FopEvent event; if(!clcw.isLockoutFlag()) { // Lockout == 0 if(clcw.getReportValue() == nextVirtualChannelFrameCounterGetter.get()) { // Valid N(R) and all outstanding type AD frames acknowledged if(!clcw.isRetransmitFlag()) { // Retransmit == 0 if(!clcw.isWaitFlag()) { // Wait == 0 if(clcw.getReportValue() == this.expectedAckFrameSequenceNumber) { // N(R) == NN(R) event = new FopEvent(FopEvent.EventNumber.E1, clcw, this.suspendState); } else { // N(R) != NN(R) event = new FopEvent(FopEvent.EventNumber.E2, clcw, this.suspendState); } } else { // Wait == 1 event = new FopEvent(FopEvent.EventNumber.E3, clcw, this.suspendState); } } else { // Retransmit == 1 event = new FopEvent(FopEvent.EventNumber.E4, clcw, this.suspendState); } } else if(lessThan(clcw.getReportValue(), nextVirtualChannelFrameCounterGetter.get(), fopSlidingWindow) && (clcw.getReportValue() == this.expectedAckFrameSequenceNumber || greaterThan(clcw.getReportValue(), this.expectedAckFrameSequenceNumber, fopSlidingWindow))) { // Valid N(R) and some outstanding type AD frames not yet acknowledged if(!clcw.isRetransmitFlag()) { // Retransmit == 0 if(!clcw.isWaitFlag()) { // Wait == 0 if(clcw.getReportValue() == this.expectedAckFrameSequenceNumber) { // N(R) == NN(R) event = new FopEvent(FopEvent.EventNumber.E5, clcw, this.suspendState); } else { // N(R) != NN(R) event = new FopEvent(FopEvent.EventNumber.E6, clcw, this.suspendState); } } else { // Wait == 1 event = new FopEvent(FopEvent.EventNumber.E7, clcw, this.suspendState); } } else { // Retransmit == 1 if(this.transmissionLimit == 1) { // Transmission limit == 1 event = new FopEvent(clcw.getReportValue() != this.expectedAckFrameSequenceNumber ? FopEvent.EventNumber.E101 : FopEvent.EventNumber.E102, clcw, this.suspendState); } else { // Transmission limit > 1 (cannot be <= 0) if(clcw.getReportValue() != this.expectedAckFrameSequenceNumber) { // N(R) != NN(R) event = new FopEvent(!clcw.isWaitFlag() ? FopEvent.EventNumber.E8 : FopEvent.EventNumber.E9, clcw, this.suspendState); } else { // N(R) == NN(R) if(this.transmissionCount < this.transmissionLimit) { // Transmission count < Transmission limit event = new FopEvent(!clcw.isWaitFlag() ? FopEvent.EventNumber.E10 : FopEvent.EventNumber.E11, clcw, this.suspendState); } else { // Transmission count >= Transmission limit event = new FopEvent(!clcw.isWaitFlag() ? FopEvent.EventNumber.E12 : FopEvent.EventNumber.E103, clcw, this.suspendState); } } } } } else { // Invalid N(R) event = new FopEvent(FopEvent.EventNumber.E13, clcw, this.suspendState); } } else { // Lockout == 1 event = new FopEvent(FopEvent.EventNumber.E14, clcw, this.suspendState); } applyStateTransition(event); } /** * Perform comparison to check if num is less than otherNum mod 256, given the provided window. * Basically, the window tells how much otherNum can be greater than num, including wrap around. * * @param num the first term to compare * @param otherNum the second term to compare * @param window the window size * @return true if num is less than otherNum, otherwise false */ private boolean lessThan(int num, int otherNum, int window) { // Expand num to window elements Set expandedSet = new HashSet<>(); for(int i = 0; i < window; ++i) { expandedSet.add((num + 1 + i) % 256); } // If otherNum is within the expanded set, return true, else return false return expandedSet.contains(otherNum); } /** * Perform comparison to check if num is greater than otherNum mod 256, given the provided window. * Basically, the window tells how much num can be greater than otherNum, including wrap around. * * @param num the first term to compare * @param otherNum the second term to compare * @param window the window size * @return true if num is greater than otherNum, otherwise false */ private boolean greaterThan(int num, int otherNum, int window) { // Expand otherNum to window elements Set expandedSet = new HashSet<>(); for(int i = 0; i < window; ++i) { expandedSet.add((otherNum + 1 + i) % 256); } // If num is within the expanded set, return true, else return false return expandedSet.contains(num); } private void processTimerExpired() { FopEvent event; if(this.transmissionCount < this.transmissionLimit) { // Transmission count < Transmission limit event = new FopEvent(timeoutType == 0 ? FopEvent.EventNumber.E16 : FopEvent.EventNumber.E104, this.suspendState); } else { // Transmission count >= Transmission limit event = new FopEvent(timeoutType == 0 ? FopEvent.EventNumber.E17 : FopEvent.EventNumber.E18, this.suspendState); } applyStateTransition(event); } private void processBdFrame(TcTransferFrame frame) { FopEvent event; if(bdOutReadyFlag) { // event = new FopEvent(FopEvent.EventNumber.E21, frame, this.suspendState); } else { // event = new FopEvent(FopEvent.EventNumber.E22, frame, this.suspendState); } applyStateTransition(event); } private void processAdFrame(TcTransferFrame frame) { FopEvent event; if(waitQueue.get() == null) { // Wait queue empty event = new FopEvent(FopEvent.EventNumber.E19, frame, this.suspendState); } else { // Wait queue not empty event = new FopEvent(FopEvent.EventNumber.E20, frame, this.suspendState); } applyStateTransition(event); } private void processDirective(Object tag, FopDirective directive, int qualifier) { FopEvent event; switch(directive) { case INIT_AD_WITHOUT_CLCW: event = new FopEvent(FopEvent.EventNumber.E23, tag, directive, qualifier, this.suspendState); break; case INIT_AD_WITH_CLCW: event = new FopEvent(FopEvent.EventNumber.E24, tag, directive, qualifier, this.suspendState); break; case INIT_AD_WITH_UNLOCK: event = new FopEvent(bcOutReadyFlag ? FopEvent.EventNumber.E25 : FopEvent.EventNumber.E26, tag, directive, qualifier, this.suspendState); break; case INIT_AD_WITH_SET_V_R: event = new FopEvent(bcOutReadyFlag ? FopEvent.EventNumber.E27 : FopEvent.EventNumber.E28, tag, directive, qualifier, this.suspendState); break; case TERMINATE: event = new FopEvent(FopEvent.EventNumber.E29, tag, directive, qualifier, this.suspendState); break; case RESUME: switch (this.suspendState) { case 0: event = new FopEvent(FopEvent.EventNumber.E30, tag, directive, qualifier, this.suspendState); break; case 1: event = new FopEvent(FopEvent.EventNumber.E31, tag, directive, qualifier, this.suspendState); break; case 2: event = new FopEvent(FopEvent.EventNumber.E32, tag, directive, qualifier, this.suspendState); break; case 3: event = new FopEvent(FopEvent.EventNumber.E33, tag, directive, qualifier, this.suspendState); break; case 4: event = new FopEvent(FopEvent.EventNumber.E34, tag, directive, qualifier, this.suspendState); break; default: throw new IllegalStateException("Suspend state for TC VC " + virtualChannelId + " not supported: " + this.suspendState); } break; case SET_V_S: event = new FopEvent(FopEvent.EventNumber.E35, tag, directive, qualifier, this.suspendState); break; case SET_FOP_SLIDING_WINDOW: event = new FopEvent(FopEvent.EventNumber.E36, tag, directive, qualifier, this.suspendState); break; case SET_T1_INITIAL: event = new FopEvent(FopEvent.EventNumber.E37, tag, directive, qualifier, this.suspendState); break; case SET_TRANSMISSION_LIMIT: event = new FopEvent(FopEvent.EventNumber.E38, tag, directive, qualifier, this.suspendState); break; case SET_TIMEOUT_TYPE: event = new FopEvent(FopEvent.EventNumber.E39, tag, directive, qualifier, this.suspendState); break; default: event = new FopEvent(FopEvent.EventNumber.E40, tag, directive, qualifier, this.suspendState); break; } applyStateTransition(event); } private void processLowerLayer(TcTransferFrame frame, boolean accepted) { FopEvent event; switch(frame.getFrameType()) { case AD: event = new FopEvent(accepted ? FopEvent.EventNumber.E41 : FopEvent.EventNumber.E42, frame, this.suspendState); break; case BC: event = new FopEvent(accepted ? FopEvent.EventNumber.E43 : FopEvent.EventNumber.E44, frame, this.suspendState); break; case BD: event = new FopEvent(accepted ? FopEvent.EventNumber.E45 : FopEvent.EventNumber.E46, frame, this.suspendState); break; default: throw new IllegalArgumentException("Frame type " + frame.getFrameType() + " not supported"); } applyStateTransition(event); } private void reportStatus(FopState previousState, FopState currentState, FopEvent.EventNumber number) { FopStatus status = new FopStatus(expectedAckFrameSequenceNumber, sentQueue.size(), waitQueue.get() != null, adOutReadyFlag, bcOutReadyFlag, bdOutReadyFlag, previousState, currentState, number); observers.forEach(o -> o.statusReport(this, status)); // Unlock transmit thread if any if(number == FopEvent.EventNumber.E22 || number == FopEvent.EventNumber.E45 || number == FopEvent.EventNumber.E46) { synchronized (pendingAcceptRejectFrame) { pendingEventResult.set(number); pendingAcceptRejectFrame.notifyAll(); } } } private void applyStateTransition(FopEvent event) { FopState previousState = this.state.getState(); this.state = this.state.event(event); FopState currentState = this.state.getState(); reportStatus(previousState, currentState, event.getNumber()); } // --------------------------------------------------------------------------------------------------------- // FOP members to interact with low level output executed by the lowLevelExecutor (thread confinement) // --------------------------------------------------------------------------------------------------------- private void forwardToOutput(TcTransferFrame frame) { boolean result = false; if(output != null) { result = output.apply(frame); } lowerLayer(frame, result); } private void lowerLayer(TcTransferFrame frame, boolean accepted) { if(fopExecutor.isTerminated()) { return; } fopExecutor.execute(() -> processLowerLayer(frame, accepted)); } // --------------------------------------------------------------------------------------------------------- // Other members // --------------------------------------------------------------------------------------------------------- private void checkThreadAccess() { if(Thread.currentThread() != this.confinementThread) { throw new IllegalAccessError("Violation on thread confinement for class FopEngine: method can only be accessed by thread " + this.confinementThread.getName()); } } private void timerExpired(TimerTask expiredTask) { synchronized (fopTimer) { if(currentTimer == expiredTask) { fopExecutor.execute(this::processTimerExpired); } } } private static class TransferFrameStatus { private final TcTransferFrame frame; private boolean toBeRetransmitted; public TransferFrameStatus(TcTransferFrame frame) { this.frame = frame; this.toBeRetransmitted = false; } public void setToBeRetransmitted(boolean toBeRetransmitted) { this.toBeRetransmitted = toBeRetransmitted; } public boolean isToBeRetransmitted() { return toBeRetransmitted; } public TcTransferFrame getFrame() { return frame; } } } 100-1000 package com.propertycross.mgwt.nestoria.gwt; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; import com.propertycross.mgwt.nestoria.RequestSender.Callback; import com.propertycross.mgwt.nestoria.Response; final class ResponseValidator implements ResponseParser { private final ResponseParser wrapped; public ResponseValidator(ResponseParser wrapped) { this.wrapped = wrapped; } @Override public void parse(JSONObject root, Callback c) throws ParseException { validate(root); wrapped.parse(root, c); } private void validate(JSONObject root) throws ParseException { if(!root.containsKey("response") || root.get("response").isObject() == null) { throw new ParseException("missing response field"); } JSONObject json = root.get("response").isObject(); switch(validateCode(json)) { case UNAMIBIGUOUS: case BEST_GUESS: case LARGE: validateLocations(json, 1); validateResults(json); break; default: validateLocations(json, 0); } } private void validateLocations(JSONObject json, int minimumExpected) throws ParseException { if(minimumExpected == 0 && !json.containsKey("locations")) return; JSONArray arr = json.get("locations").isArray(); if(arr == null) { throw new ParseException("locations is not an array"); } if(arr.size() < minimumExpected) { throw new ParseException("too few locations"); } for(int i = 0, j = arr.size(); i < j; ++i) { JSONObject o = arr.get(i).isObject(); if(o == null) { throw new ParseException("location not object: " + arr.get(i)); } validateString(o, "long_title"); validateString(o, "place_name"); } } private void validateResults(JSONObject json) throws ParseException { if(!json.containsKey("listings")) { throw new ParseException("listings not in response"); } JSONArray arr = json.get("listings").isArray(); if(arr == null) { throw new ParseException("listings is not an array"); } for(int i = 0, j = arr.size(); i < j; ++i) { JSONObject o = arr.get(i).isObject(); if(o == null) { throw new ParseException("listing not object: " + arr.get(i)); } validateString(o, "guid"); validateString(o, "title"); validateString(o, "price_formatted"); validateString(o, "bedroom_number"); validateString(o, "bathroom_number"); validateString(o, "property_type"); validateString(o, "img_url"); validateString(o, "summary"); } } private String validateString(JSONObject j, String key) throws ParseException { if(!j.containsKey(key)) { throw new ParseException(key + " not in response"); } JSONString js = j.get(key).isString(); if(js == null) { throw new ParseException(key + " is not a string"); } return js.stringValue().trim(); } private Response.Code validateCode(JSONObject json) throws ParseException { String code = validateString(json, "application_response_code"); try { return Response.Code.valueOf(Integer.parseInt(code)); } catch(IllegalArgumentException ex) { throw new ParseException("unknown response code: " + code); } } } BurgherJon/LTHOIHarness2 /* * 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. */ /* * This code was generated by https://code.google.com/p/google-apis-client-generator/ * (build: 2016-02-18 22:11:37 UTC) * on 2016-03-22 at 22:34:36 UTC * Modify at your own risk. */ package com.appspot.lthoi_test_harness.playerAPI.model; /** * Model definition for Me. * *

This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the playerAPI. For a detailed explanation see: * http://code.google.com/p/google-http-java-client/wiki/JSON *

* * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Me extends com.google.api.client.json.GenericJson { /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String email; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fname; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer id; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String linitial; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String lname; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer losses; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer pushes; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Double winnings; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer wins; /** * @return value or {@code null} for none */ public java.lang.String getEmail() { return email; } /** * @param email email or {@code null} for none */ public Me setEmail(java.lang.String email) { this.email = email; return this; } /** * @return value or {@code null} for none */ public java.lang.String getFname() { return fname; } /** * @param fname fname or {@code null} for none */ public Me setFname(java.lang.String fname) { this.fname = fname; return this; } /** * @return value or {@code null} for none */ public java.lang.Integer getId() { return id; } /** * @param id id or {@code null} for none */ public Me setId(java.lang.Integer id) { this.id = id; return this; } /** * @return value or {@code null} for none */ public java.lang.String getLinitial() { return linitial; } /** * @param linitial linitial or {@code null} for none */ public Me setLinitial(java.lang.String linitial) { this.linitial = linitial; return this; } /** * @return value or {@code null} for none */ public java.lang.String getLname() { return lname; } /** * @param lname lname or {@code null} for none */ public Me setLname(java.lang.String lname) { this.lname = lname; return this; } /** * @return value or {@code null} for none */ public java.lang.Integer getLosses() { return losses; } /** * @param losses losses or {@code null} for none */ public Me setLosses(java.lang.Integer losses) { this.losses = losses; return this; } /** * @return value or {@code null} for none */ public java.lang.Integer getPushes() { return pushes; } /** * @param pushes pushes or {@code null} for none */ public Me setPushes(java.lang.Integer pushes) { this.pushes = pushes; return this; } /** * @return value or {@code null} for none */ public java.lang.Double getWinnings() { return winnings; } /** * @param winnings winnings or {@code null} for none */ public Me setWinnings(java.lang.Double winnings) { this.winnings = winnings; return this; } /** * @return value or {@code null} for none */ public java.lang.Integer getWins() { return wins; } /** * @param wins wins or {@code null} for none */ public Me setWins(java.lang.Integer wins) { this.wins = wins; return this; } @Override public Me set(String fieldName, Object value) { return (Me) super.set(fieldName, value); } @Override public Me clone() { return (Me) super.clone(); } } package src.main.java.io.github.heltonricardo.creational_patterns.abstract_factory.example_01.model.iphone; import src.main.java.io.github.heltonricardo.creational_patterns.abstract_factory.example_01.factory.abstractFactory.CountryRulesAbstractFactory; public class IPhone11 extends IPhone { public IPhone11(CountryRulesAbstractFactory rules) { super(rules); } @Override public void getHardware() { System.out.println("Hardware list"); System.out.println("\t- 6.1in Screen"); System.out.println("\t- A13 Chipset"); System.out.println("\t- 4Gb RAM"); System.out.println("\t- 256Gb Memory"); } } package com.lachesis.mnis.core.liquor.entity; import java.util.ArrayList; import java.util.List; /** * 未执行医嘱记录信息 * @author ThinkPad * */ public class OrderUnExecRecord { private String patId; private String patName; private String bedCode; private String deptCode; private List orderUnExecRecordItems = new ArrayList(); public String getPatId() { return patId; } public void setPatId(String patId) { this.patId = patId; } public String getPatName() { return patName; } public void setPatName(String patName) { this.patName = patName; } public String getBedCode() { return bedCode; } public void setBedCode(String bedCode) { this.bedCode = bedCode; } public String getDeptCode() { return deptCode; } public void setDeptCode(String deptCode) { this.deptCode = deptCode; } public List getOrderUnExecRecordItems() { return orderUnExecRecordItems; } public void setOrderUnExecRecordItems( List orderUnExecRecordItems) { this.orderUnExecRecordItems = orderUnExecRecordItems; } } Lab10/src/Drivable.java public interface Drivable { boolean isValid(Automobile a); } /* * Copyright ©2018 vbill.cn. *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *

*/ package cn.vbill.middleware.porter.common.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; /** * @author: zhangkewei[] * @date: 2017年12月20日 13:50 * @version: V1.0 * @review: zhangkewei[]/2017年12月20日 13:50 */ public class MachineUtils { /** * HOST_NAME */ public static final String HOST_NAME = System.getProperty("user.name"); /** * CURRENT_JVM_PID */ public static final long CURRENT_JVM_PID = getPID(); /** * IP_ADDRESS */ public static final String IP_ADDRESS = localhost(); /** * CPU_NUMBER */ public static final int CPU_NUMBER = Runtime.getRuntime().availableProcessors(); /** * LOCAL_EXCEPT_IP */ private static final String LOCAL_EXCEPT_IP = "127.0.0.1,192.168.2.1,192.168.122.1"; private static final Logger LOGGER = LoggerFactory.getLogger(MachineUtils.class); /** * getPID * * @return */ public static long getPID() { String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); if (processName != null && processName.length() > 0) { try { return Long.parseLong(processName.split("@")[0]); } catch (Exception e) { return 0; } } return 0; } /** * getLocalInetAddress * * @return */ private static List getLocalInetAddress() { List inetAddressList = new ArrayList(); try { Enumeration enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) { NetworkInterface networkInterface = enumeration.nextElement(); Enumeration addrs = networkInterface.getInetAddresses(); boolean ifUnUse = networkInterface.isLoopback() || networkInterface.isPointToPoint() || networkInterface.isVirtual() || !networkInterface.isUp(); while (addrs.hasMoreElements() && !ifUnUse) { inetAddressList.add(addrs.nextElement().getHostAddress()); } } } catch (SocketException e) { throw new RuntimeException("get local inet address fail", e); } return inetAddressList; } /** * localhost * * @return */ public static String localhost() { List list = getLocalInetAddress(); for (String i : list) { if (!LOCAL_EXCEPT_IP.contains(i) && i.indexOf(':') < 0) { return i; } } return "127.0.0.1"; } } Server/src/main/java/uc/entities/Plants.java package uc.entities; public class Plants { private String piid; private String plantId; private String name; private int quantity; public Plants() { } public String getPiId() { return piid; } public void setPiId(String piid) { this.piid = piid; } public String getPlantId() { return plantId; } public void setPlantId(String plantId) { this.plantId = plantId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public static Plants fromSwaggerObject(io.swagger.model.Plants plants) { Plants result = new Plants(); result.setPiId(plants.getPiid()); result.setPlantId(plants.getPlantid()); result.setName(plants.getName()); result.setQuantity(plants.getQuantity()); return result; } public io.swagger.model.Plants toSwaggerObject() { io.swagger.model.Plants result = new io.swagger.model.Plants(); result.setPiid(getPiId()); result.setPlantid(getPlantId()); result.setName(getName()); result.setQuantity(getQuantity()); return result; } }0 package com.bayraktar.servicesexample.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; import androidx.core.content.ContextCompat; import com.bayraktar.servicesexample.services.WebSocketService; import org.java_websocket.server.WebSocketServer; /** * Created by on 2/13/2021. */ public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { if (context != null) { webSocketServiceOperation(context, isOnline(context)); } } public boolean isOnline(@org.jetbrains.annotations.NotNull Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); //should check null because in airplane mode it will be null return (netInfo != null && netInfo.isConnected()); } private void webSocketServiceOperation(Context context, boolean isStart) { Intent intent = new Intent(context, WebSocketService.class); intent.putExtra(WebSocketService.IS_ACTION_START, isStart); context.startService(intent); // ContextCompat.startForegroundService(context, intent); } } package flex2.tools; public class Mxmlc { public static void mxmlc( String[] args ) { flex2.tools.Compiler.mxmlc( args ); } } /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Other; /** * * @author cvielma */ public class MaxProduct { public static int maxProduct(int[] A) { if (A == null || A.length == 0) { return 0; } int max = A[0]; int min = A[0]; int result = A[0]; for (int i = 1; i < A.length; i++) { int currMaxProd = max * A[i]; int currMinProd = min * A[i]; max = Math.max(Math.max(currMaxProd, currMinProd), A[i]); min = Math.min(Math.min(currMaxProd, currMinProd), A[i]); if (max > result) { result = max; } } return result; } public static void main(String[] args) { // System.out.println(maxProduct(new int[]{-2, -3, 7})); System.out.println(maxProduct(new int[]{-4, -3, -2})); } } package com.p2pgate.bank_gate.rest.domain.gateways.tcs; /** * * Created by OAKutsenko on 10.04.2017. */ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "currency", "value" }) class Value { @JsonProperty("currency") private Currency currency; @JsonProperty("value") private Float value; @JsonProperty("currency") Currency getCurrency() { return currency; } @JsonProperty("currency") public void setCurrency(Currency currency) { this.currency = currency; } @JsonProperty("value") public Float getValue() { return this.value; } @JsonProperty("value") public void setValue(Float value) { this.value = value; } } KNIGHTTH0R/datumbox0 /** * Copyright (C) 2013-2016 <> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datumbox.framework.core.machinelearning.common.abstracts.algorithms; import com.datumbox.framework.common.Configuration; import com.datumbox.framework.common.concurrency.ForkJoinStream; import com.datumbox.framework.common.concurrency.StreamMethods; import com.datumbox.framework.common.dataobjects.AssociativeArray; import com.datumbox.framework.common.dataobjects.Dataframe; import com.datumbox.framework.common.dataobjects.Record; import com.datumbox.framework.common.dataobjects.TypeInference; import com.datumbox.framework.common.persistentstorage.interfaces.BigMap; import com.datumbox.framework.common.persistentstorage.interfaces.DatabaseConnector; import com.datumbox.framework.common.persistentstorage.interfaces.DatabaseConnector.MapType; import com.datumbox.framework.common.persistentstorage.interfaces.DatabaseConnector.StorageHint; import com.datumbox.framework.core.machinelearning.common.abstracts.AbstractTrainer; import com.datumbox.framework.core.machinelearning.common.abstracts.modelers.AbstractClassifier; import com.datumbox.framework.core.machinelearning.common.interfaces.PredictParallelizable; import com.datumbox.framework.core.machinelearning.common.interfaces.TrainParallelizable; import com.datumbox.framework.core.machinelearning.common.validators.ClassifierValidator; import com.datumbox.framework.core.statistics.descriptivestatistics.Descriptives; import java.util.*; /** * Base class for Naive Bayes Models. * * @author <> * @param * @param * @param */ public abstract class AbstractNaiveBayes extends AbstractClassifier implements PredictParallelizable, TrainParallelizable { /** * Flag that indicates whether the algorithm binarizes the provided activated * features. */ private final boolean isBinarized; /** {@inheritDoc} */ public static abstract class AbstractModelParameters extends AbstractClassifier.AbstractModelParameters { private Map logPriors = new HashMap<>(); //prior log probabilities of the classes @BigMap(mapType=MapType.HASHMAP, storageHint=StorageHint.IN_MEMORY, concurrent=true) private Map, Double> logLikelihoods; //posterior log probabilities of features-classes combination /** * @param dbc * @see AbstractTrainer.AbstractModelParameters#AbstractModelParameters(DatabaseConnector) */ protected AbstractModelParameters(DatabaseConnector dbc) { super(dbc); } /** * Getter for the log of priors of the classes. * * @return */ public Map getLogPriors() { return logPriors; } /** * Setter for the log of priors of the classes. * * @param logPriors */ protected void setLogPriors(Map logPriors) { this.logPriors = logPriors; } /** * Getter for the log likelihood of P(x|c). * * @return */ public Map, Double> getLogLikelihoods() { return logLikelihoods; } /** * Setter for the log likelihood of P(x|c). * * @param logLikelihoods */ protected void setLogLikelihoods(Map, Double> logLikelihoods) { this.logLikelihoods = logLikelihoods; } } /** {@inheritDoc} */ public static abstract class AbstractTrainingParameters extends AbstractClassifier.AbstractTrainingParameters { private boolean multiProbabilityWeighted=false; //whether the classifier weights the probabilities based on the number of occurences. (multiple occurences are taken into account when we estimate the classification scores) /** * Getter for whether the algorithm weights the probabilities based on the * multiple occurrences of a feature. * * @return */ public boolean isMultiProbabilityWeighted() { return multiProbabilityWeighted; } /** * Setter for whether the algorithm weights the probabilities based on the * multiple occurrences of a feature. * * @param multiProbabilityWeighted */ public void setMultiProbabilityWeighted(boolean multiProbabilityWeighted) { this.multiProbabilityWeighted = multiProbabilityWeighted; } } /** * @param dbName * @param conf * @param mpClass * @param tpClass * @param vmClass * @param isBinarized * @see AbstractTrainer#AbstractTrainer(java.lang.String, Configuration, java.lang.Class, java.lang.Class...) */ protected AbstractNaiveBayes(String dbName, Configuration conf, Class mpClass, Class tpClass, Class vmClass, boolean isBinarized) { super(dbName, conf, mpClass, tpClass, vmClass, new ClassifierValidator<>()); streamExecutor = new ForkJoinStream(kb().getConf().getConcurrencyConfig()); this.isBinarized = isBinarized; } private boolean parallelized = true; /** * This executor is used for the parallel processing of streams with custom * Thread pool. */ protected final ForkJoinStream streamExecutor; /** {@inheritDoc} */ @Override public boolean isParallelized() { return parallelized; } /** {@inheritDoc} */ @Override public void setParallelized(boolean parallelized) { this.parallelized = parallelized; } /** {@inheritDoc} */ @Override protected void _predictDataset(Dataframe newData) { DatabaseConnector dbc = kb().getDbc(); Map resultsBuffer = dbc.getBigMap("tmp_resultsBuffer", MapType.HASHMAP, StorageHint.IN_DISK, true, true); _predictDatasetParallel(newData, resultsBuffer, kb().getConf().getConcurrencyConfig()); dbc.dropBigMap("tmp_resultsBuffer", resultsBuffer); } /** {@inheritDoc} */ @Override public Prediction _predictRecord(Record r) { AbstractModelParameters modelParameters = kb().getModelParameters(); Map, Double> logLikelihoods = modelParameters.getLogLikelihoods(); Map logPriors = modelParameters.getLogPriors(); Set classesSet = modelParameters.getClasses(); Object someClass = classesSet.iterator().next(); //initialize scores with the scores of the priors AssociativeArray predictionScores = new AssociativeArray(new HashMap<>(logPriors)); for(Map.Entry entry : r.getX().entrySet()) { Object feature = entry.getKey(); //EVERY feature within our dictionary has a value for EVERY class //So if the feature has no value for one random class (someClass has //no particular significance), then it will not have for any class //and thus the feature is not in the dictionary and can be ignored. if(!logLikelihoods.containsKey(Arrays.asList(feature, someClass))) { continue; } //extract the feature scores for each class for the particular feature AssociativeArray classLogScoresForThisFeature = new AssociativeArray(); for(Object theClass : classesSet) { Double logScore = logLikelihoods.get(Arrays.asList(feature, theClass)); classLogScoresForThisFeature.put(theClass, logScore); } Double occurrences=TypeInference.toDouble(entry.getValue()); if((!kb().getTrainingParameters().isMultiProbabilityWeighted() || isBinarized) && occurrences>0) { occurrences=1.0; } for(Map.Entry entry2 : classLogScoresForThisFeature.entrySet()) { Object theClass = entry2.getKey(); Double logScore = TypeInference.toDouble(entry2.getValue()); Double previousValue = predictionScores.getDouble(theClass); predictionScores.put(theClass, previousValue+occurrences*logScore); } //classLogScoresForThisFeature=null; } Object predictedClass=getSelectedClassFromClassScores(predictionScores); Descriptives.normalizeExp(predictionScores); return new Prediction(predictedClass, predictionScores); } /** {@inheritDoc} */ @Override protected void _fit(Dataframe trainingData) { AbstractModelParameters modelParameters = kb().getModelParameters(); int n = modelParameters.getN(); int d = modelParameters.getD(); Map, Double> logLikelihoods = modelParameters.getLogLikelihoods(); Map logPriors = modelParameters.getLogPriors(); Set classesSet = modelParameters.getClasses(); //calculate first statistics about the classes Map totalFeatureOccurrencesForEachClass = new HashMap<>(); for(Record r : trainingData) { Object theClass=r.getY(); if(classesSet.add(theClass)) { //is it new class? add it logPriors.put(theClass, 1.0); totalFeatureOccurrencesForEachClass.put(theClass, 0.0); } else { //already exists? increase counter logPriors.put(theClass,logPriors.get(theClass)+1.0); } } //Loop through all the classes to ensure that the feature-class combination is initialized for ALL the classes //The math REQUIRE us to have scores for all classes to make the probabilities comparable. /* Implementation note: The code below uses the metadata from the Dataframe to avoid looping through all the data. This means that if the metadata are stale (contain more columns than the actual data due to updates/removes) we will initialize more parameters here. Nevertheless this should not have any effects on the results of the algorithm since the scores will be the same in all classes and it will be taken care by the normalization. */ streamExecutor.forEach(StreamMethods.stream(trainingData.getXDataTypes().keySet().stream(), isParallelized()), feature -> { for(Object theClass : classesSet) { List featureClassTuple = Arrays.asList(feature, theClass); logLikelihoods.put(featureClassTuple, 0.0); //the key is unique across threads and the map is concurrent } }); //now calculate the statistics of features streamExecutor.forEach(StreamMethods.stream(trainingData.stream(), isParallelized()), r -> { Object theClass = r.getY(); //store the occurrances of the features double sumOfOccurrences = 0.0; for(Map.Entry entry : r.getX().entrySet()) { Object feature = entry.getKey(); Double occurrences=TypeInference.toDouble(entry.getValue()); if(occurrences!= null && occurrences>0.0) { if(isBinarized) { occurrences=1.0; } List featureClassTuple = Arrays.asList(feature, theClass); logLikelihoods.put(featureClassTuple, logLikelihoods.get(featureClassTuple)+occurrences); //each thread updates a unique key and the map is cuncurrent sumOfOccurrences+=occurrences; } } synchronized(totalFeatureOccurrencesForEachClass) { totalFeatureOccurrencesForEachClass.put(theClass,totalFeatureOccurrencesForEachClass.get(theClass)+sumOfOccurrences); } }); //calculate prior log probabilities for(Map.Entry entry : logPriors.entrySet()) { Object theClass = entry.getKey(); Double count = entry.getValue(); //updated log priors logPriors.put(theClass, Math.log(count/n)); } //update log likelihood streamExecutor.forEach(StreamMethods.stream(logLikelihoods.entrySet().stream(), isParallelized()), featureClassCounts -> { List featureClassTuple = featureClassCounts.getKey(); Object theClass = featureClassTuple.get(1); Double occurrences = featureClassCounts.getValue(); if(occurrences==null) { occurrences=0.0; } //We perform laplace smoothing (also known as add-1) Double smoothedProbability = (occurrences+1.0)/(totalFeatureOccurrencesForEachClass.get(theClass)+d); // the d is also known in NLP problems as the Vocabulary size. logLikelihoods.put(featureClassTuple, Math.log( smoothedProbability )); //calculate the logScore }); } }package starwars.swapi.api.stub; import org.junit.Ignore; import org.junit.Test; import projectconfiguration.CreatePageDatabase; import java.io.IOException; @Ignore("To avoid accidental database creation") public class CreateAllSwapiPageDatabase { // Create object for class CreatePageDatabase CreatePageDatabase createPageDatabase = new CreatePageDatabase(); @Test public void canCreateSWAPIPageDatabase() throws IOException { createPageDatabase.canCreatePageDatabaseForAnySwapiAPI("api"); } @Test public void canCreatepeoplePageDatabase() throws IOException { createPageDatabase.canCreatePageDatabaseForAnySwapiAPI("people"); } @Test public void canCreateplanetsPageDatabase() throws IOException { createPageDatabase.canCreatePageDatabaseForAnySwapiAPI("planets"); } @Test public void canCreatefilmsPageDatabase() throws IOException { createPageDatabase.canCreatePageDatabaseForAnySwapiAPI("films"); } @Test public void canCreatepspeciesPageDatabase() throws IOException { createPageDatabase.canCreatePageDatabaseForAnySwapiAPI("species"); } @Test public void canCreatevehiclesPageDatabase() throws IOException { createPageDatabase.canCreatePageDatabaseForAnySwapiAPI("vehicles"); } @Test public void canCreatestarshipsPageDatabase() throws IOException { createPageDatabase.canCreatePageDatabaseForAnySwapiAPI("starships"); } } package rocks.inspectit.agent.java.analyzer; /** * This interface is used to delegate the analysis and instrumentation of the given bytecode from * the javaagent. * * @author * */ public interface IByteCodeAnalyzer { /** * The method returns the instrumented bytecode of the class which is passed to this method as * the first parameter. * * @param byteCode * The bytecode, which is necessary to check if a parent class is registered by a * sensor and needs to be installed for every child class. * @param className * The class name. * @param classLoader * The class loader. * @return The instrumented byte code or null if nothing was done (or an error * happened) */ byte[] analyzeAndInstrument(byte[] byteCode, String className, ClassLoader classLoader); } pablopdomingos/nfse package com.pablodomingos.classes.rps.builders; import com.pablodomingos.classes.rps.RpsIntermediario; import com.pablodomingos.classes.rps.RpsIntermediarioCpfCnpj; public class IntermediarioBuilder extends AbstractBuilder{ private RpsIntermediarioCpfCnpj cpfCnpj; private String nome; private String inscricaoMunicipal; public IntermediarioBuilder(String documento, String nome) { this.cpfCnpj = new IntermediarioCpfCnpjBuilder().comDocumento(documento).build(); this.nome = nome; } public IntermediarioBuilder comInscricaoMunicipal(String inscricaoMunicipal){ this.inscricaoMunicipal = inscricaoMunicipal; return this; } @Override protected RpsIntermediario buildInternal() { return new RpsIntermediario(this); } public RpsIntermediarioCpfCnpj getCpfCnpj() { return cpfCnpj; } public String getNome() { return nome; } public String getInscricaoMunicipal() { return inscricaoMunicipal; } } app/src/main/java/net/pietu1998/wordbasehacker/solver/Scoring.java package net.pietu1998.wordbasehacker.solver; public class Scoring { public final int letter, mine, tileGain, tileKill, progressGain, progressKill, winBonus, loseMinus; public Scoring(int letter, int mine, int tileGain, int tileKill, int progressGain, int progressKill, int winBonus, int loseMinus) { this.letter = letter; this.mine = mine; this.tileGain = tileGain; this.tileKill = tileKill; this.progressGain = progressGain; this.progressKill = progressKill; this.winBonus = winBonus; this.loseMinus = loseMinus; } public static final Scoring DEFAULT = new Scoring( 1, 0, 10, 40, 100, 400, 1000000, -1000000); public int calculateScore(Score score) { int result = 0; result += score.wordLength * letter; result += score.minesExploded * mine; result += score.tilesGained * tileGain; result += score.tilesKilled * tileKill; result += score.progressGained * progressGain; result += score.progressKilled * progressKill; if (score.gameWon) result += winBonus; return result; } @Override public boolean equals(Object o) { if (!(o instanceof Scoring)) return false; Scoring other = (Scoring) o; return letter == other.letter && mine == other.mine && tileGain == other.tileGain && tileKill == other.tileKill && progressGain == other.progressGain && progressKill == other.progressKill && winBonus == other.winBonus && loseMinus == other.loseMinus; } } 1-10 /******************************************************************************* * Copyright (c) 2019 UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.epics.pva.client; import static org.epics.pva.PVASettings.logger; import java.nio.ByteBuffer; import java.util.logging.Level; import org.epics.pva.common.PVAHeader; import org.epics.pva.common.RequestEncoder; /** Send a 'ECHO' request to server * @author */ @SuppressWarnings("nls") class EchoRequest implements RequestEncoder { static final byte[] CHECK = new byte[] { 'e', 'c', 'h', 'o' }; @Override public void encodeRequest(final byte version, final ByteBuffer buffer) throws Exception { // Protocol always required server to echo the payload, but version 1 servers didn't if (version < 2) { logger.log(Level.FINE, () -> "Sending ECHO request (Version " + version + " without content)"); PVAHeader.encodeMessageHeader(buffer, PVAHeader.FLAG_NONE, PVAHeader.CMD_ECHO, 0); } else { logger.log(Level.FINE, () -> "Sending ECHO request (Version " + version + ")"); PVAHeader.encodeMessageHeader(buffer, PVAHeader.FLAG_NONE, PVAHeader.CMD_ECHO, CHECK.length); buffer.put(CHECK); } } } Isaac-Bi/quarantine-appapp/src/main/java/com/example/app/SeventhQuestion.java1-10 package com.example.app; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class SeventhQuestion extends AppCompatActivity { // Question Label private TextView questionSeven; //Next Question button private Button next7; //Number assigned to choice private int questionSevenChoice; QuestionBank q7 = new QuestionBank(); Question seventhQ; ListView lvAnswers7; Answer[] answers7; ArrayList answersStr = new ArrayList(); Answer rScore; int score; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_seventh_question); seventhQ = q7.getQuestion(6); //Sets question questionSeven = (TextView) findViewById(R.id.questionSeven); questionSeven.setText(seventhQ.getPrompt()); //Listview for question lvAnswers7=findViewById(R.id.LVAnswers7); answers7 = seventhQ.getChoices(); for(int i =0; i< answers7.length;i++) { answersStr.add(answers7[i].getContent()); } AnswerArrayAdapter ansAdapter = new AnswerArrayAdapter(this, android.R.layout.simple_list_item_1, answers7); lvAnswers7.setAdapter(ansAdapter); //Listener for answer button lvAnswers7.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapter, View view, final int position, long id) { Answer response = (Answer)lvAnswers7.getItemAtPosition(position); rScore = answers7[answersStr.indexOf(response.getContent())]; score = rScore.getRiskScore(); } }); //Next question button next7 = (Button)findViewById(R.id.nextBtn7); //next question button next7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { UserData.getInstance().setScore(score); startActivity(new Intent(getApplicationContext(),EighthQuestion.class)); } }); } }package org.blub.controller; import org.blub.domain.Document; import org.blub.domain.External_object_reference; import org.blub.repository.External_object_reference_repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value = "/api/eor") public class External_object_reference_controller { //// TODO: 31.01.16 deleting External_object_references can lead to an inconsistent state(for this prototype a benevolent user is assumed) @Autowired private External_object_reference_repository eorRepository; @RequestMapping(method = RequestMethod.GET) public Iterable list() { return eorRepository.findAll(1); } @RequestMapping(method = RequestMethod.POST, consumes = "application/json") public External_object_reference create(@RequestBody External_object_reference eor){ eorRepository.save(eor, 1); return eorRepository.findOne(eor.getGraphId(), 1); } @RequestMapping(method = RequestMethod.GET, value = "/{id}") public External_object_reference find(@PathVariable Long id){ return eorRepository.findOne(id, 1); } @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") public void delete(@PathVariable Long id){ eorRepository.delete(id); } @RequestMapping(method = RequestMethod.PUT, value = "/{id}", consumes = "application/json") public External_object_reference update(@PathVariable Long id, @RequestBody External_object_reference eor){ if(null == eor.getGraphId()){ eor.setGraphId(id); //would otherwise create new node in neo4J instead of updating this one } eorRepository.save(eor, 1); return eorRepository.findOne(id, 1); } } /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.filesystem.stream; import org.apache.flink.runtime.state.StateInitializationContext; import org.apache.flink.runtime.state.StateSnapshotContext; import org.apache.flink.streaming.api.functions.sink.filesystem.Bucket; import org.apache.flink.streaming.api.functions.sink.filesystem.BucketLifeCycleListener; import org.apache.flink.streaming.api.functions.sink.filesystem.Buckets; import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink; import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSinkHelper; import org.apache.flink.streaming.api.operators.AbstractStreamOperator; import org.apache.flink.streaming.api.operators.BoundedOneInput; import org.apache.flink.streaming.api.operators.ChainingStrategy; import org.apache.flink.streaming.api.operators.OneInputStreamOperator; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import org.apache.flink.table.data.RowData; import org.apache.flink.table.filesystem.stream.StreamingFileCommitter.CommitMessage; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * Operator for file system sink. It is a operator version of {@link StreamingFileSink}. * It sends partition commit message to downstream for committing. * *

See {@link StreamingFileCommitter}. */ public class StreamingFileWriter extends AbstractStreamOperator implements OneInputStreamOperator, BoundedOneInput{ private static final long serialVersionUID = 1L; // ------------------------ configuration fields -------------------------- private final long bucketCheckInterval; private final StreamingFileSink.BucketsBuilder> bucketsBuilder; // --------------------------- runtime fields ----------------------------- private transient Buckets buckets; private transient StreamingFileSinkHelper helper; private transient long currentWatermark; private transient Set inactivePartitions; public StreamingFileWriter( long bucketCheckInterval, StreamingFileSink.BucketsBuilder> bucketsBuilder) { this.bucketCheckInterval = bucketCheckInterval; this.bucketsBuilder = bucketsBuilder; setChainingStrategy(ChainingStrategy.ALWAYS); } @Override public void initializeState(StateInitializationContext context) throws Exception { super.initializeState(context); buckets = bucketsBuilder.createBuckets(getRuntimeContext().getIndexOfThisSubtask()); // Set listener before the initialization of Buckets. inactivePartitions = new HashSet<>(); buckets.setBucketLifeCycleListener(new BucketLifeCycleListener() { @Override public void bucketCreated(Bucket bucket) { } @Override public void bucketInactive(Bucket bucket) { inactivePartitions.add(bucket.getBucketId()); } }); helper = new StreamingFileSinkHelper<>( buckets, context.isRestored(), context.getOperatorStateStore(), getRuntimeContext().getProcessingTimeService(), bucketCheckInterval); currentWatermark = Long.MIN_VALUE; } @Override public void snapshotState(StateSnapshotContext context) throws Exception { super.snapshotState(context); helper.snapshotState(context.getCheckpointId()); } @Override public void processWatermark(Watermark mark) throws Exception { super.processWatermark(mark); currentWatermark = mark.getTimestamp(); } @Override public void processElement(StreamRecord element) throws Exception { helper.onElement( element.getValue(), getProcessingTimeService().getCurrentProcessingTime(), element.hasTimestamp() ? element.getTimestamp() : null, currentWatermark); } /** * Commit up to this checkpoint id, also send inactive partitions to downstream for committing. */ @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { super.notifyCheckpointComplete(checkpointId); commitUpToCheckpoint(checkpointId); } private void commitUpToCheckpoint(long checkpointId) throws Exception { helper.commitUpToCheckpoint(checkpointId); CommitMessage message = new CommitMessage( checkpointId, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getNumberOfParallelSubtasks(), new ArrayList<>(inactivePartitions)); output.collect(new StreamRecord<>(message)); inactivePartitions.clear(); } @Override public void endInput() throws Exception { buckets.onProcessingTime(Long.MAX_VALUE); helper.snapshotState(Long.MAX_VALUE); output.emitWatermark(new Watermark(Long.MAX_VALUE)); commitUpToCheckpoint(Long.MAX_VALUE); } @Override public void dispose() throws Exception { super.dispose(); if (helper != null) { helper.close(); } } } package com.caizi.caizimall.ware; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class CaizimallWareApplicationTests { @Test void contextLoads() { } } ut4/enj0 package net.mdh.enj.mapping; import org.junit.Test; import org.junit.Assert; import org.junit.Before; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.Mockito; import org.mockito.Mock; import java.sql.SQLException; import java.sql.ResultSet; @RunWith(MockitoJUnitRunner.class) public class NoDupeMapperTest { @Mock private ResultSet mockResultSet; private TestMapper testNoDupeMapper; @Before public void beforeEach() { this.testNoDupeMapper = new TestMapper(); } /** * Testaa, että mapRow() ei mappaa riviä (kutsu doMapRow:ia), jos kyseinen * rivi on jo kerätty, tai sinä ei ole dataa (rivin getString({primaryKeyColumn}) * palauttaa arvon null). */ @Test public void mapRowIgnorettaaRivitJotkaOnJoKerätty() throws SQLException { // Mockaa rivien primääriavain-arvot Mockito.when(this.mockResultSet.getString(TestMapper.TEST_ID_COL)) .thenReturn("mockuuid1") .thenReturn("mockuuid1") .thenReturn("mockuuid2") .thenReturn(null) .thenReturn(null); // Simuloi muutama mappaus (normaalisti Spring Jdbc:n tekee tämän) TestEntity mapped1 = this.testNoDupeMapper.mapRow(this.mockResultSet, 0); TestEntity mapped2 = this.testNoDupeMapper.mapRow(this.mockResultSet, 1); TestEntity mapped3 = this.testNoDupeMapper.mapRow(this.mockResultSet, 2); TestEntity mapped4 = this.testNoDupeMapper.mapRow(this.mockResultSet, 3); TestEntity mapped5 = this.testNoDupeMapper.mapRow(this.mockResultSet, 4); TestEntity mapped6 = this.testNoDupeMapper.mapRow(this.mockResultSet, 5); // Assertoi Assert.assertNotNull("Pitäisi mapata ensimmäisen normaalisti", mapped1); Assert.assertNull("Pitäisi ignorettaa, koska id mockuuid1 jo kerätty", mapped2); Assert.assertNotNull("Pitäisi mapata normaalisti", mapped3); Assert.assertNull("Pitäisi ignorettaa, koska id null", mapped4); Assert.assertNull("Pitäisi ignorettaa, koska id null", mapped5); Assert.assertNull("Pitäisi ignorettaa, koska id mockuuid2 jo kerätty", mapped6); } public static class TestMapper extends NoDupeRowMapper { private static final String TEST_ID_COL = "foo"; protected TestMapper() { super(TEST_ID_COL); } @Override protected TestEntity doMapRow(ResultSet rs, int rowNum) throws SQLException { return new TestEntity(); } } private static class TestEntity {} } MPChartLib/src/main/java/com/github/mikephil/charting/interfaces/datasets/ILineScatterCandleRadarDataSet.java package com.github.mikephil.charting.interfaces.datasets; import com.github.mikephil.charting.data.Entry; import android.graphics.DashPathEffect; /** * Created by on 21/10/15. */ public interface ILineScatterCandleRadarDataSet extends IBarLineScatterCandleBubbleDataSet { /** * Returns true if vertical highlight indicator lines are enabled (drawn) * * @return */ boolean isVerticalHighlightIndicatorEnabled(); /** * Returns true if vertical highlight indicator lines are enabled (drawn) * * @return */ boolean isHorizontalHighlightIndicatorEnabled(); /** * Returns the line-width in which highlight lines are to be drawn. * * @return */ float getHighlightLineWidth(); /** * Returns the DashPathEffect that is used for highlighting. * * @return */ DashPathEffect getDashPathEffectHighlight(); } 0 package app.components; import app.controller.common.BaseController; import app.data.redis.HashData; import app.data.redis.RedisData; import app.data.zk.ZkData; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.control.cell.TextFieldListCell; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.layout.VBox; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.net.URL; import java.util.*; /** * @author: * @date: 2020-06-22 **/ public class DetailController extends BaseController implements Initializable { private static final Logger logger = LogManager.getLogger(DetailController.class); @FXML private VBox container; @Override public void initialize(URL location, ResourceBundle resources) { } @Override public boolean isNeedLogin() { return false; } @Override public void loadWithData(Object data) { if (data == null) { return; } if (data instanceof RedisData) { RedisData redisData = (RedisData) data; Label keyLabel = new Label("KEY:"); TextField keyTextField = new TextField(redisData.getCanonicalName()); Label valueLabel = new Label("VALUE:"); container.getChildren().addAll(keyLabel, keyTextField, valueLabel); switch (redisData.getType()) { case STRING: String v = (String) redisData.getValue(); TextArea valueTextField = null; if (v.startsWith("{")) { try { ObjectMapper objectMapper = new ObjectMapper(); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); valueTextField = new TextArea(writer.writeValueAsString(objectMapper.readValue(v, Map.class))); container.getChildren().addAll(keyLabel, keyTextField, valueLabel, valueTextField); valueTextField.prefHeightProperty().bind(container.heightProperty()); } catch (JsonProcessingException e) { logger.error(e.getMessage(), e); } ; } else if (v.startsWith("[")) { try { ObjectMapper objectMapper = new ObjectMapper(); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); valueTextField = new TextArea(writer.writeValueAsString(objectMapper.readValue(v, List.class))); container.getChildren().addAll(keyLabel, keyTextField, valueLabel, valueTextField); valueTextField.prefHeightProperty().bind(container.heightProperty()); } catch (JsonProcessingException e) { logger.error(e.getMessage(), e); } } else { valueTextField = new TextArea(v); } container.getChildren().add(valueTextField); valueTextField.prefHeightProperty().bind(container.heightProperty()); break; case LIST: List listItems = (List) redisData.getValue(); ListView valueListView = new ListView<>(FXCollections.observableList(listItems)); valueListView.setEditable(true); valueListView.setCellFactory(TextFieldListCell.forListView()); container.getChildren().add(valueListView); valueListView.prefHeightProperty().bind(container.heightProperty()); break; case SET: Set setItems = (Set) redisData.getValue(); ListView setListView = new ListView<>(FXCollections.observableList(new ArrayList<>(setItems))); setListView.setEditable(true); setListView.setCellFactory(TextFieldListCell.forListView()); container.getChildren().add(setListView); setListView.prefHeightProperty().bind(container.heightProperty()); break; case HASH: Map map = (Map) redisData.getValue(); List list = new ArrayList<>(); for (String key : map.keySet()) { list.add(new HashData(key, map.get(key))); } ObservableList items = FXCollections.observableList(list); TableView tableView = new TableView<>(); TableColumn keyCol = new TableColumn<>("Key"); keyCol.setCellValueFactory(new PropertyValueFactory<>("key")); keyCol.setCellFactory(TextFieldTableCell.forTableColumn()); TableColumn valueCol = new TableColumn("Value"); valueCol.setCellValueFactory(new PropertyValueFactory<>("value")); valueCol.setCellFactory(TextFieldTableCell.forTableColumn()); keyCol.prefWidthProperty().bind(tableView.widthProperty().divide(2).subtract(5)); valueCol.prefWidthProperty().bind(tableView.widthProperty().divide(2).subtract(5)); tableView.getColumns().addAll(keyCol, valueCol); tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); tableView.setItems(items); tableView.setEditable(true); container.getChildren().add(tableView); tableView.prefHeightProperty().bind(container.heightProperty()); break; default: break; } } else if (data instanceof ZkData) { ZkData zkData = (ZkData) data; Label keyLabel = new Label("KEY:"); TextField keyTextField = new TextField(zkData.getCanonicalName()); Label valueLabel = new Label("VALUE:"); String v = zkData.getValue(); if (v.startsWith("{")) { try { ObjectMapper objectMapper = new ObjectMapper(); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); TextArea valueTextField = new TextArea(writer.writeValueAsString(objectMapper.readValue(v, Map.class))); container.getChildren().addAll(keyLabel, keyTextField, valueLabel, valueTextField); } catch (JsonProcessingException e) { logger.error(e.getMessage(), e); } ; } else if (v.startsWith("[")) { try { ObjectMapper objectMapper = new ObjectMapper(); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); TextArea valueTextField = new TextArea(writer.writeValueAsString(objectMapper.readValue(v, List.class))); container.getChildren().addAll(keyLabel, keyTextField, valueLabel, valueTextField); } catch (JsonProcessingException e) { logger.error(e.getMessage(), e); } ; } else { TextArea valueTextField = new TextArea(v); container.getChildren().addAll(keyLabel, keyTextField, valueLabel, valueTextField); } } } } Cselwood/ColourPicker package com.example.colourpicker; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { RelativeLayout relativeLayout; TextView nameLabel; TextView hexLabel; TextView rgbLabel; TextView rgbaLabel; TextView hexPrompt; TextView rgbPrompt; TextView rgbaPrompt; View divider; Button[] allButtons; Button greenButton; Button yellowGreenButton; Button yellowButton; Button orangeYellowButton; Button orangeButton; Button redOrangeButton; Button redButton; Button violetRedButton; Button violetButton; Button blueVioletButton; Button blueButton; Button blueGreenButton; Button blackButton; Button greyButton; Button whiteButton; // Made global for scope reasons int count; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout); allButtons = new Button[15]; // Text Labels nameLabel = (TextView) findViewById(R.id.colourName); hexLabel = (TextView) findViewById(R.id.hexColourEdit); rgbLabel = (TextView) findViewById(R.id.rgbColourEdit); rgbaLabel = (TextView) findViewById(R.id.rgbaColourEdit); // Text Prompts hexPrompt = (TextView) findViewById(R.id.hexPrompt); rgbPrompt = (TextView) findViewById(R.id.rgbPrompt); rgbaPrompt = (TextView) findViewById(R.id.rgbaPrompt); divider = (View) findViewById(R.id.divider); // Color Buttons greenButton = (Button) findViewById(R.id.greenButton); greenButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("green"); } }); yellowGreenButton = (Button) findViewById(R.id.yellowGreenButton); yellowGreenButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("yellowGreen"); } }); yellowButton = (Button) findViewById(R.id.yellowButton); yellowButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("yellow"); } }); orangeYellowButton = (Button) findViewById(R.id.orangeYellowButton); orangeYellowButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("orangeYellow"); } }); orangeButton = (Button) findViewById(R.id.orangeButton); orangeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("orange"); } }); redOrangeButton = (Button) findViewById(R.id.redOrangeButton); redOrangeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("redOrange"); } }); redButton = (Button) findViewById(R.id.redButton); redButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("red"); } }); violetRedButton = (Button) findViewById(R.id.violetRedButton); violetRedButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("violetRed"); } }); violetButton = (Button) findViewById(R.id.violetButton); violetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("violet"); } }); blueVioletButton = (Button) findViewById(R.id.blueVioletButton); blueVioletButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("blueViolet"); } }); blueButton = (Button) findViewById(R.id.blueButton); blueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("blue"); } }); blueGreenButton = (Button) findViewById(R.id.blueGreenButton); blueGreenButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("blueGreen"); } }); blackButton = (Button) findViewById(R.id.blackButton); blackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("black"); } }); greyButton = (Button) findViewById(R.id.greyButton); greyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("grey"); } }); whiteButton = (Button) findViewById(R.id.whiteButton); whiteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFromColourButton("white"); } }); // Setup Background Colors initialiseButtons(); // Start Program on White Background updateInitial(); } protected void updateFromColourButton(String colour) { switch (colour) { case "green": nameLabel.setText("Green"); hexLabel.setText("#00FF00"); rgbLabel.setText("0, 255, 0"); rgbaLabel.setText(convertToRgba(0, 255, 0)); nameLabel.setBackgroundResource(R.color.green); hexLabel.setBackgroundResource(R.color.green); rgbLabel.setBackgroundResource(R.color.green); rgbaLabel.setBackgroundResource(R.color.green); relativeLayout.setBackgroundResource(R.color.green); hexPrompt.setBackgroundResource(R.color.green); rgbPrompt.setBackgroundResource(R.color.green); rgbaPrompt.setBackgroundResource(R.color.green); nameLabel.setTextColor(Color.BLACK); hexLabel.setTextColor(Color.BLACK); rgbLabel.setTextColor(Color.BLACK); rgbaLabel.setTextColor(Color.BLACK); hexPrompt.setTextColor(Color.BLACK); rgbPrompt.setTextColor(Color.BLACK); rgbaPrompt.setTextColor(Color.BLACK); divider.setBackgroundResource(R.color.black); break; case "yellowGreen": nameLabel.setText("Yellow Green"); hexLabel.setText("#C3D938"); rgbLabel.setText("195, 217, 56"); rgbaLabel.setText(convertToRgba(195, 217, 56)); nameLabel.setBackgroundResource(R.color.yellowGreen); hexLabel.setBackgroundResource(R.color.yellowGreen); rgbLabel.setBackgroundResource(R.color.yellowGreen); rgbaLabel.setBackgroundResource(R.color.yellowGreen); relativeLayout.setBackgroundResource(R.color.yellowGreen); hexPrompt.setBackgroundResource(R.color.yellowGreen); rgbPrompt.setBackgroundResource(R.color.yellowGreen); rgbaPrompt.setBackgroundResource(R.color.yellowGreen); nameLabel.setTextColor(Color.BLACK); hexLabel.setTextColor(Color.BLACK); rgbLabel.setTextColor(Color.BLACK); rgbaLabel.setTextColor(Color.BLACK); hexPrompt.setTextColor(Color.BLACK); rgbPrompt.setTextColor(Color.BLACK); rgbaPrompt.setTextColor(Color.BLACK); divider.setBackgroundResource(R.color.black); break; case "yellow": nameLabel.setText("Yellow"); hexLabel.setText("#FFFF00"); rgbLabel.setText("255, 255, 0"); rgbaLabel.setText(convertToRgba(255, 255, 0)); nameLabel.setBackgroundResource(R.color.yellow); hexLabel.setBackgroundResource(R.color.yellow); rgbLabel.setBackgroundResource(R.color.yellow); rgbaLabel.setBackgroundResource(R.color.yellow); relativeLayout.setBackgroundResource(R.color.yellow); hexPrompt.setBackgroundResource(R.color.yellow); rgbPrompt.setBackgroundResource(R.color.yellow); rgbaPrompt.setBackgroundResource(R.color.yellow); nameLabel.setTextColor(Color.BLACK); hexLabel.setTextColor(Color.BLACK); rgbLabel.setTextColor(Color.BLACK); rgbaLabel.setTextColor(Color.BLACK); hexPrompt.setTextColor(Color.BLACK); rgbPrompt.setTextColor(Color.BLACK); rgbaPrompt.setTextColor(Color.BLACK); divider.setBackgroundResource(R.color.black); break; case "orangeYellow": nameLabel.setText("Orange Yellow"); hexLabel.setText("#FFAE42"); rgbLabel.setText("255, 174, 66"); rgbaLabel.setText(convertToRgba(255, 174, 66)); nameLabel.setBackgroundResource(R.color.orangeYellow); hexLabel.setBackgroundResource(R.color.orangeYellow); rgbLabel.setBackgroundResource(R.color.orangeYellow); rgbaLabel.setBackgroundResource(R.color.orangeYellow); relativeLayout.setBackgroundResource(R.color.orangeYellow); hexPrompt.setBackgroundResource(R.color.orangeYellow); rgbPrompt.setBackgroundResource(R.color.orangeYellow); rgbaPrompt.setBackgroundResource(R.color.orangeYellow); nameLabel.setTextColor(Color.BLACK); hexLabel.setTextColor(Color.BLACK); rgbLabel.setTextColor(Color.BLACK); rgbaLabel.setTextColor(Color.BLACK); hexPrompt.setTextColor(Color.BLACK); rgbPrompt.setTextColor(Color.BLACK); rgbaPrompt.setTextColor(Color.BLACK); divider.setBackgroundResource(R.color.black); break; case "orange": nameLabel.setText("Orange"); hexLabel.setText("#FF8B10"); rgbLabel.setText("255, 139, 16"); rgbaLabel.setText(convertToRgba(255, 139, 16)); nameLabel.setBackgroundResource(R.color.orange); hexLabel.setBackgroundResource(R.color.orange); rgbLabel.setBackgroundResource(R.color.orange); rgbaLabel.setBackgroundResource(R.color.orange); relativeLayout.setBackgroundResource(R.color.orange); hexPrompt.setBackgroundResource(R.color.orange); rgbPrompt.setBackgroundResource(R.color.orange); rgbaPrompt.setBackgroundResource(R.color.orange); nameLabel.setTextColor(Color.BLACK); hexLabel.setTextColor(Color.BLACK); rgbLabel.setTextColor(Color.BLACK); rgbaLabel.setTextColor(Color.BLACK); hexPrompt.setTextColor(Color.BLACK); rgbPrompt.setTextColor(Color.BLACK); rgbaPrompt.setTextColor(Color.BLACK); divider.setBackgroundResource(R.color.black); break; case "redOrange": nameLabel.setText("Red Orange"); hexLabel.setText("#FA5711"); rgbLabel.setText("250, 87, 17"); rgbaLabel.setText(convertToRgba(250, 87, 17)); nameLabel.setBackgroundResource(R.color.redOrange); hexLabel.setBackgroundResource(R.color.redOrange); rgbLabel.setBackgroundResource(R.color.redOrange); rgbaLabel.setBackgroundResource(R.color.redOrange); relativeLayout.setBackgroundResource(R.color.redOrange); hexPrompt.setBackgroundResource(R.color.redOrange); rgbPrompt.setBackgroundResource(R.color.redOrange); rgbaPrompt.setBackgroundResource(R.color.redOrange); nameLabel.setTextColor(Color.WHITE); hexLabel.setTextColor(Color.WHITE); rgbLabel.setTextColor(Color.WHITE); rgbaLabel.setTextColor(Color.WHITE); hexPrompt.setTextColor(Color.WHITE); rgbPrompt.setTextColor(Color.WHITE); rgbaPrompt.setTextColor(Color.WHITE); divider.setBackgroundResource(R.color.white); break; case "red": nameLabel.setText("Red"); hexLabel.setText("#FF0000"); rgbLabel.setText("255, 0, 0"); rgbaLabel.setText(convertToRgba(255, 0, 0)); nameLabel.setBackgroundResource(R.color.red); hexLabel.setBackgroundResource(R.color.red); rgbLabel.setBackgroundResource(R.color.red); rgbaLabel.setBackgroundResource(R.color.red); relativeLayout.setBackgroundResource(R.color.red); hexPrompt.setBackgroundResource(R.color.red); rgbPrompt.setBackgroundResource(R.color.red); rgbaPrompt.setBackgroundResource(R.color.red); nameLabel.setTextColor(Color.WHITE); hexLabel.setTextColor(Color.WHITE); rgbLabel.setTextColor(Color.WHITE); rgbaLabel.setTextColor(Color.WHITE); hexPrompt.setTextColor(Color.WHITE); rgbPrompt.setTextColor(Color.WHITE); rgbaPrompt.setTextColor(Color.WHITE); divider.setBackgroundResource(R.color.white); break; case "violetRed": nameLabel.setText("Violet Red"); hexLabel.setText("#8B0137"); rgbLabel.setText("139, 1, 55"); rgbaLabel.setText(convertToRgba(139, 1, 55)); nameLabel.setBackgroundResource(R.color.violetRed); hexLabel.setBackgroundResource(R.color.violetRed); rgbLabel.setBackgroundResource(R.color.violetRed); rgbaLabel.setBackgroundResource(R.color.violetRed); relativeLayout.setBackgroundResource(R.color.violetRed); hexPrompt.setBackgroundResource(R.color.violetRed); rgbPrompt.setBackgroundResource(R.color.violetRed); rgbaPrompt.setBackgroundResource(R.color.violetRed); nameLabel.setTextColor(Color.WHITE); hexLabel.setTextColor(Color.WHITE); rgbLabel.setTextColor(Color.WHITE); rgbaLabel.setTextColor(Color.WHITE); hexPrompt.setTextColor(Color.WHITE); rgbPrompt.setTextColor(Color.WHITE); rgbaPrompt.setTextColor(Color.WHITE); divider.setBackgroundResource(R.color.white); break; case "violet": nameLabel.setText("Violet"); hexLabel.setText("#9000FF"); rgbLabel.setText("144, 0, 255"); rgbaLabel.setText(convertToRgba(144, 0, 255)); nameLabel.setBackgroundResource(R.color.violet); hexLabel.setBackgroundResource(R.color.violet); rgbLabel.setBackgroundResource(R.color.violet); rgbaLabel.setBackgroundResource(R.color.violet); relativeLayout.setBackgroundResource(R.color.violet); hexPrompt.setBackgroundResource(R.color.violet); rgbPrompt.setBackgroundResource(R.color.violet); rgbaPrompt.setBackgroundResource(R.color.violet); nameLabel.setTextColor(Color.WHITE); hexLabel.setTextColor(Color.WHITE); rgbLabel.setTextColor(Color.WHITE); rgbaLabel.setTextColor(Color.WHITE); hexPrompt.setTextColor(Color.WHITE); rgbPrompt.setTextColor(Color.WHITE); rgbaPrompt.setTextColor(Color.WHITE); divider.setBackgroundResource(R.color.white); break; case "blueViolet": nameLabel.setText("Blue Violet"); hexLabel.setText("#54459E"); rgbLabel.setText("84, 69, 158"); rgbaLabel.setText(convertToRgba(84, 69, 158)); nameLabel.setBackgroundResource(R.color.blueViolet); hexLabel.setBackgroundResource(R.color.blueViolet); rgbLabel.setBackgroundResource(R.color.blueViolet); rgbaLabel.setBackgroundResource(R.color.blueViolet); relativeLayout.setBackgroundResource(R.color.blueViolet); hexPrompt.setBackgroundResource(R.color.blueViolet); rgbPrompt.setBackgroundResource(R.color.blueViolet); rgbaPrompt.setBackgroundResource(R.color.blueViolet); nameLabel.setTextColor(Color.WHITE); hexLabel.setTextColor(Color.WHITE); rgbLabel.setTextColor(Color.WHITE); rgbaLabel.setTextColor(Color.WHITE); hexPrompt.setTextColor(Color.WHITE); rgbPrompt.setTextColor(Color.WHITE); rgbaPrompt.setTextColor(Color.WHITE); divider.setBackgroundResource(R.color.white); break; case "blue": nameLabel.setText("Blue"); hexLabel.setText("#0000FF"); rgbLabel.setText("0, 0, 255"); rgbaLabel.setText(convertToRgba(0, 0, 255)); nameLabel.setBackgroundResource(R.color.blue); hexLabel.setBackgroundResource(R.color.blue); rgbLabel.setBackgroundResource(R.color.blue); rgbaLabel.setBackgroundResource(R.color.blue); relativeLayout.setBackgroundResource(R.color.blue); hexPrompt.setBackgroundResource(R.color.blue); rgbPrompt.setBackgroundResource(R.color.blue); rgbaPrompt.setBackgroundResource(R.color.blue); nameLabel.setTextColor(Color.WHITE); hexLabel.setTextColor(Color.WHITE); rgbLabel.setTextColor(Color.WHITE); rgbaLabel.setTextColor(Color.WHITE); hexPrompt.setTextColor(Color.WHITE); rgbPrompt.setTextColor(Color.WHITE); rgbaPrompt.setTextColor(Color.WHITE); divider.setBackgroundResource(R.color.white); break; case "blueGreen": nameLabel.setText("Blue Green"); hexLabel.setText("#02AB84"); rgbLabel.setText("2, 171, 132"); rgbaLabel.setText(convertToRgba(2, 171, 132)); nameLabel.setBackgroundResource(R.color.blueGreen); hexLabel.setBackgroundResource(R.color.blueGreen); rgbLabel.setBackgroundResource(R.color.blueGreen); rgbaLabel.setBackgroundResource(R.color.blueGreen); relativeLayout.setBackgroundResource(R.color.blueGreen); hexPrompt.setBackgroundResource(R.color.blueGreen); rgbPrompt.setBackgroundResource(R.color.blueGreen); rgbaPrompt.setBackgroundResource(R.color.blueGreen); nameLabel.setTextColor(Color.WHITE); hexLabel.setTextColor(Color.WHITE); rgbLabel.setTextColor(Color.WHITE); rgbaLabel.setTextColor(Color.WHITE); hexPrompt.setTextColor(Color.WHITE); rgbPrompt.setTextColor(Color.WHITE); rgbaPrompt.setTextColor(Color.WHITE); divider.setBackgroundResource(R.color.white); break; case "black": nameLabel.setText("Black"); hexLabel.setText("#000000"); rgbLabel.setText("0, 0, 0"); rgbaLabel.setText(convertToRgba(0, 0, 0)); nameLabel.setBackgroundResource(R.color.black); hexLabel.setBackgroundResource(R.color.black); rgbLabel.setBackgroundResource(R.color.black); rgbaLabel.setBackgroundResource(R.color.black); relativeLayout.setBackgroundResource(R.color.black); hexPrompt.setBackgroundResource(R.color.black); rgbPrompt.setBackgroundResource(R.color.black); rgbaPrompt.setBackgroundResource(R.color.black); nameLabel.setTextColor(Color.WHITE); hexLabel.setTextColor(Color.WHITE); rgbLabel.setTextColor(Color.WHITE); rgbaLabel.setTextColor(Color.WHITE); hexPrompt.setTextColor(Color.WHITE); rgbPrompt.setTextColor(Color.WHITE); rgbaPrompt.setTextColor(Color.WHITE); divider.setBackgroundResource(R.color.white); break; case "grey": nameLabel.setText("Grey"); hexLabel.setText("#9C9E9B"); rgbLabel.setText("156, 158, 155"); rgbaLabel.setText(convertToRgba(156, 158, 155)); nameLabel.setBackgroundResource(R.color.grey); hexLabel.setBackgroundResource(R.color.grey); rgbLabel.setBackgroundResource(R.color.grey); rgbaLabel.setBackgroundResource(R.color.grey); relativeLayout.setBackgroundResource(R.color.grey); hexPrompt.setBackgroundResource(R.color.grey); rgbPrompt.setBackgroundResource(R.color.grey); rgbaPrompt.setBackgroundResource(R.color.grey); nameLabel.setTextColor(Color.WHITE); hexLabel.setTextColor(Color.WHITE); rgbLabel.setTextColor(Color.WHITE); rgbaLabel.setTextColor(Color.WHITE); hexPrompt.setTextColor(Color.WHITE); rgbPrompt.setTextColor(Color.WHITE); rgbaPrompt.setTextColor(Color.WHITE); divider.setBackgroundResource(R.color.white); break; case "white": nameLabel.setText("White"); hexLabel.setText("#FFFFFF"); rgbLabel.setText("255, 255, 255"); rgbaLabel.setText(convertToRgba(255, 255, 255)); nameLabel.setBackgroundResource(R.color.white); hexLabel.setBackgroundResource(R.color.white); rgbLabel.setBackgroundResource(R.color.white); rgbaLabel.setBackgroundResource(R.color.white); relativeLayout.setBackgroundResource(R.color.white); hexPrompt.setBackgroundResource(R.color.white); rgbPrompt.setBackgroundResource(R.color.white); rgbaPrompt.setBackgroundResource(R.color.white); nameLabel.setTextColor(Color.BLACK); hexLabel.setTextColor(Color.BLACK); rgbLabel.setTextColor(Color.BLACK); rgbaLabel.setTextColor(Color.BLACK); hexPrompt.setTextColor(getResources().getColor(R.color.dividerColor)); rgbPrompt.setTextColor(getResources().getColor(R.color.dividerColor)); rgbaPrompt.setTextColor(getResources().getColor(R.color.dividerColor)); divider.setBackgroundResource(R.color.dividerColor); break; } } protected String convertToRgba(int redVal, int greenVal, int blueVal) { float[] floatResult = new float[4]; floatResult[0] = redVal / 255f; floatResult[0] = Math.round(floatResult[0] * 100.0f) / 100.0f; floatResult[1] = greenVal / 255f; floatResult[1] = Math.round(floatResult[1] * 100.0f) / 100.0f; floatResult[2] = blueVal / 255f; floatResult[2] = Math.round(floatResult[2] * 100.0f) / 100.0f; floatResult[3] = 1.0f; String result = "("; for (int count = 0; count < floatResult.length; count++) { result += Float.toString(floatResult[count]) + ", "; } result = result.substring(0, (result.length() - 2)); result += ")"; return result; } protected void initialiseButtons() { greenButton.setBackgroundResource(R.color.green); yellowGreenButton.setBackgroundResource(R.color.yellowGreen); yellowButton.setBackgroundResource(R.color.yellow); orangeYellowButton.setBackgroundResource(R.color.orangeYellow); orangeButton.setBackgroundResource(R.color.orange); redOrangeButton.setBackgroundResource(R.color.redOrange); redButton.setBackgroundResource(R.color.red); violetRedButton.setBackgroundResource(R.color.violetRed); violetButton.setBackgroundResource(R.color.violet); blueVioletButton.setBackgroundResource(R.color.blueViolet); blueButton.setBackgroundResource(R.color.blue); blueGreenButton.setBackgroundResource(R.color.blueGreen); blackButton.setBackgroundResource(R.color.black); greyButton.setBackgroundResource(R.color.grey); whiteButton.setBackgroundResource(R.color.white); Log.i("TAG", "Successfully INIT Button"); } protected void updateInitial() { nameLabel.setText("White"); hexLabel.setText("#FFFFFF"); rgbLabel.setText("255, 255, 255"); rgbaLabel.setText("(1.0, 1.0, 1.0, 1.0)"); } } package io.ran; import io.ran.token.Token; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class CompoundKeyTest { @Test public void equals() { CompoundKey compoundKey = new CompoundKey(); compoundKey.add(Property.get(Token.of("id"), Clazz.of(String.class)).value("my id")); CompoundKey compoundKey2 = new CompoundKey(); compoundKey2.add(Property.get(Token.of("id"), Clazz.of(String.class)).value("my id")); assertEquals(compoundKey, compoundKey2); } @Test public void notEquals_differentValue() { CompoundKey compoundKey = new CompoundKey(); compoundKey.add(Property.get(Token.of("id"), Clazz.of(String.class)).value("my id2")); CompoundKey compoundKey2 = new CompoundKey(); compoundKey2.add(Property.get(Token.of("id"), Clazz.of(String.class)).value("my id")); assertNotEquals(compoundKey, compoundKey2); } @Test public void notEquals_differentProperty() { CompoundKey compoundKey = new CompoundKey(); compoundKey.add(Property.get(Token.of("id2"), Clazz.of(String.class)).value("my id")); CompoundKey compoundKey2 = new CompoundKey(); compoundKey2.add(Property.get(Token.of("id"), Clazz.of(String.class)).value("my id")); assertNotEquals(compoundKey, compoundKey2); } @Test public void mapContains() { CompoundKey compoundKey = new CompoundKey(); compoundKey.add(Property.get(Token.of("id"), Clazz.of(String.class)).value("my id")); CompoundKey compoundKey2 = new CompoundKey(); compoundKey2.add(Property.get(Token.of("id"), Clazz.of(String.class)).value("my id")); Map map = new HashMap<>(); map.put(compoundKey, true); assertTrue(map.containsKey(compoundKey2)); } @Test public void mapNotContains() { CompoundKey compoundKey = new CompoundKey(); compoundKey.add(Property.get(Token.of("id"), Clazz.of(String.class)).value("my id")); CompoundKey compoundKey2 = new CompoundKey(); compoundKey2.add(Property.get(Token.of("id"), Clazz.of(String.class)).value("my id2")); Map map = new HashMap<>(); map.put(compoundKey, true); assertFalse(map.containsKey(compoundKey2)); } }package com.example.application.dao.chapter; import com.example.application.model.Chapter; import java.util.List; public interface ChapterDAO { List getAllChapters(); void saveChapter(Chapter chapter); Chapter getChapter(int id); void deleteChapter(int id); } package br.com.zupacademy.guzzo.mercadolivre.controller; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import br.com.zupacademy.guzzo.mercadolivre.component.Emails; import br.com.zupacademy.guzzo.mercadolivre.config.security.UsuarioLogado; import br.com.zupacademy.guzzo.mercadolivre.controller.form.FinalizaCompraForm; import br.com.zupacademy.guzzo.mercadolivre.model.Compra; import br.com.zupacademy.guzzo.mercadolivre.model.Produto; @RestController public class ProcessaCompraParte1Controller { @Autowired private Emails emails; @PersistenceContext private EntityManager em; @PostMapping("produtos/{id}/finaliza-compra") @Transactional public ResponseEntity processaCompra(@PathVariable Long id, @RequestBody @Valid FinalizaCompraForm form, @AuthenticationPrincipal UsuarioLogado usuarioLogado) { Produto produto = em.find(Produto.class, id); if (produto == null) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Produto não encontrado com id " + id); } if ((produto.getQuantidade() - form.getQuantidade()) >= 0) { produto.abateEstoque(form.getQuantidade()); } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "A quantidade informada é superior que o produto possui! "); } Compra compra = form.converterParaCompra(produto, usuarioLogado.getUsuario()); String urlRedirect = compra.getTipoPagamento().getRedirect(compra.getUuid()); emails.novaVenda(compra); //em.merge(produto); em.persist(compra); return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).body(urlRedirect); } } package org.isisaddons.module.xdocreport.dom.example.models; import java.util.List; import java.util.Map; import com.google.common.collect.ImmutableMap; import org.isisaddons.module.xdocreport.dom.service.XDocReportModel; import lombok.Data; @Data public class ProjectDevelopersModel implements XDocReportModel { private final Project project; private final List developers; @Override public Map getContextData() { return ImmutableMap.of( "project", Data.object(project), "developers", Data.list(developers, Developer.class)); } } import java.util.*; public class Demo { public static void main (String args[]) { Scanner keyboard = new Scanner(System.in); Student studentA = new Student(); Student studentB = new Student(); System.out.println("What's the first Student's name?"); String name = keyboard.nextLine(); studentA.setStudentName(name); System.out.println("What's the second Student's name?"); name = keyboard.nextLine(); studentB.setStudentName(name); System.out.println("What's the first student's major?"); String major = keyboard.nextLine(); studentA.setStudentMajor(major); System.out.println("What's the second student's major?"); major = keyboard.nextLine(); studentB.setStudentMajor(major); String option = ""; do { System.out.println("Do you want to add Courses and Grades for a Student?"); System.out.println("Enter 'y' for yes and 'n' to quit"); option = keyboard.nextLine(); if (option.equalsIgnoreCase("y")) { System.out.println("Which student?"); System.out.print("For "); System.out.print(studentA.getStudentName()); System.out.println(" enter 1"); System.out.print("For "); System.out.print(studentB.getStudentName()); System.out.println(" enter 2"); int choice = keyboard.nextInt(); if (choice == 1) { String selection = ""; keyboard.nextLine(); while (!selection.equalsIgnoreCase("n")) { //check the course array for empty slots //return true for empty, false if not boolean check = studentA.checkCourseArray(); if (check == true) { System.out.println("Enter in the course."); String newCourse = keyboard.nextLine(); studentA.setNewCourse(newCourse); System.out.println("What grade did the student earn (0-4)?"); double newPoints = keyboard.nextDouble(); studentA.updateStudentGpa(newPoints); System.out.println("Record updated: " + studentA.toString()); } else { System.out.println(studentA.toString()); } System.out.println(); System.out.println("Press enter to add another course or 'n' to move on."); keyboard.nextLine(); selection = keyboard.nextLine(); } } else if (choice == 2) { String selection = ""; keyboard.nextLine(); while (!selection.equalsIgnoreCase("n")) { //check the course array for empty slots //return true for empty, false if not boolean check = studentB.checkCourseArray(); if (check == true) { System.out.println("Enter in the course."); String newCourse = keyboard.nextLine(); studentB.setNewCourse(newCourse); System.out.println("What grade did the student earn (0-4)?"); double newPoints = keyboard.nextDouble(); studentB.updateStudentGpa(newPoints); System.out.println("Record updated: " + studentB.toString()); } else { System.out.println(studentB.toString()); } System.out.println(); System.out.println("Press enter to add another course or 'n' to move on."); keyboard.nextLine(); selection = keyboard.nextLine(); } } } } while (!option.equalsIgnoreCase("n")); if (studentA.getStudentGpa() != 0.0){ System.out.println("The current records for "+ studentA.getStudentName() +" are: "); System.out.println(studentA.toString()); } if (studentB.getStudentGpa() != 0.0) { System.out.println("The current records for "+ studentB.getStudentName() +" are: "); System.out.println(studentB.toString()); } System.out.println("Thanks your using the program, Aloha"); } } package p; class A { class Z { void o() { { class F { { class B { void hj() { } } } } } } } }package thecave.matrixcontrol.gui.components; import thecave.matrixcontrol.device.DeviceImage; public interface ImageSource { int getImageCount(); DeviceImage getImageWithId(int imageIndex); } dumin199101/JavaCode02JavaWeb/travel/src/main/java/cn/itcast/travel/service/impl/RouteServiceImpl.java package cn.itcast.travel.service.impl; import cn.itcast.travel.dao.RouteDao; import cn.itcast.travel.dao.impl.RouteDaoImpl; import cn.itcast.travel.domain.PageBean; import cn.itcast.travel.domain.Route; import cn.itcast.travel.service.RouteService; import java.util.List; public class RouteServiceImpl implements RouteService { private RouteDao routeDao = new RouteDaoImpl(); @Override public PageBean pageQeury(int cid, int pageSize, int currentPage, String rname) { PageBean routePageBean = new PageBean<>(); routePageBean.setCurrentPage(currentPage); routePageBean.setPageSize(pageSize); //查找数量 int count = routeDao.findCount(cid,rname); routePageBean.setTotalCount(count); //查找当前页数据 int start = (currentPage - 1) * pageSize; List routeList = routeDao.findbyPage(cid, start, pageSize,rname); routePageBean.setList(routeList); //设置总页码 int totalPage = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1; routePageBean.setTotalPage(totalPage); return routePageBean; } } package com.github.tommyettinger.colorful; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; import com.github.tommyettinger.colorful.ycwcm.ColorfulBatch; import com.github.tommyettinger.colorful.ycwcm.ColorfulSprite; /** * Shader code to construct a {@link ShaderProgram} that can render the specialized colors produced by the rest of this * library. The shader code is meant for use in a {@link com.badlogic.gdx.graphics.g2d.SpriteBatch}; a convenience * method, {@link #makeBatch()}, is provided to generate and return a SpriteBatch that uses a correct ShaderProgram. * Many of the shaders here are experimental and meant as a basis for user code, rather than a complete solution. * If you aren't familiar with shaders in libGDX, see this * libGDX wiki article for more information. *
* None of the shaders here specify a {@code #version}, and some combinations of OS, driver, and GPU hardware may * require the version to be set to a specific value. You may need to put: * {@code ShaderProgram.prependVertexCode = "#version 110\n"; * ShaderProgram.prependFragmentCode = "#version 110\n";} in your launchers, with whatever version you can support, in * order to avoid some warnings or errors on some systems. *
* Many of these shaders would need at least some changing to work with kinds of * {@link com.badlogic.gdx.graphics.g2d.Batch} that aren't SpriteBatch (or at least very similar). You should compare * the names of {@code uniform} variables in the vertex and fragment shader if you use a different kind of Batch; if all * of them are the same and there are the same amount, then you should be able to use these shaders without issue. *
* Note that you don't need to specify a shader from here at all if you use a ColorfulBatch from this library! * There is a ColorfulBatch in each of the color space subpackages, such as {@code rgb}, {@code oklab}, and {@code ipt}. * All of those allow a multiplicative "tweak" to each color channel before an additive change is applied to that * channel; to contrast, all of the shaders here can only permit one or the other for a given channel. ColorfulBatch may * act oddly if it has to interact with SpriteBatch-specific classes like {@link com.badlogic.gdx.graphics.g2d.Sprite}, * so there are ColorfulSprite classes that also allow setting the "tweak" and additive change per-sprite. Still, it can * be a good idea to use the shaders here if you have an existing SpriteBatch, or want to use the various experimental * shaders as a test-bed. */ public class Shaders { /** * This is the default vertex shader from libGDX. It is used without change by most of the fragment shaders here. */ public static final String vertexShader = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" + "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" + "uniform mat4 u_projTrans;\n" + "varying vec4 v_color;\n" + "varying vec2 v_texCoords;\n" + "\n" + "void main()\n" + "{\n" + " v_color = " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" + " v_color.a = v_color.a * (255.0/254.0);\n" + " v_texCoords = " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" + " gl_Position = u_projTrans * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + "}\n"; /* attribute vec4 a_position; attribute vec4 a_color; attribute vec2 a_texCoord0; uniform mat4 u_projTrans; varying vec4 v_color; varying vec2 v_texCoords; void main() { v_color = a_color; v_color.a = v_color.a * (255.0/254.0); v_texCoords = a_texCoord0; gl_Position = u_projTrans * a_position; } */ /** * A simple shader that uses additive blending with "normal" RGBA colors (alpha is still multiplicative). * With the default SpriteBatch ShaderProgram, white is the neutral color, 50% gray darkens a color by about 50%, * and black darkens a color to black, but nothing can brighten a color. With this, 50% gray is the neutral color, * white adds 0.5 to the RGB channels (brightening it and also desaturating it), and black subtracts 0.5 from the * RGB channels (darkening and desaturating, but not to black unless the color is already somewhat dark). When * tinting with white, this looks like The Mona Lisa on the left, when * tinting with 50% gray, it makes no change, and when tinting with black, it almost reaches all black, but some * faint part of the image is still barely visible. *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. *
* Meant for use with {@link #vertexShader}. */ public static final String fragmentShaderRGBA = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " gl_FragColor = clamp(vec4(tgt.rgb * pow((v_color.rgb + 0.1) * 1.666, vec3(1.5)), v_color.a * tgt.a), 0.0, 1.0);\n" + "}"; /** * A simple shader that uses multiplicative blending with "normal" RGBA colors, and is simpler than * {@link #fragmentShaderRGBA} but can make changes in color smoother. With the default SpriteBatch ShaderProgram, * white is the neutral color, 50% gray darkens a color by about 50%, and black darkens a color to black, but * nothing can brighten a color. With this, 50% gray is the neutral color, white multiplies the RGB channels by * 2.0 (brightening it and slightly desaturating it), and black multiplies the RGB channels by 0 (reducing the color * always to black). When tinting with white, this looks like The Mona * Lisa on the left; when tinting with 50% gray, it makes no change, and when tinting with black, it produces an * all-black image. *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. *
* Meant for use with {@link #vertexShader}. *
* An earlier version of this attempted to use some useful code by CypherCove in gdx-tween, but the current version * doesn't share any code, and doesn't really do any gamma correction either. It does less... gamma... un-correction * than {@link #fragmentShaderRGBA}, though, so if the source images are gamma-corrected this should be fine. */ public static final String fragmentShaderGammaRGBA = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D(u_texture, v_texCoords);\n" + " gl_FragColor = clamp(vec4(tgt.rgb * v_color.rgb * 2.0, v_color.a * tgt.a), 0.0, 1.0);\n" + "}"; //// save the result as shader, and set it on your batch with // ShaderProgram shader = makeRGBAShader(); // batch.setShader(shader) /** * A simple helper method that builds the simplest shader here; this shader allows tinting with light colors to * lighten an image. You can assign the result to a SpriteBatch with its * {@link SpriteBatch#setShader(ShaderProgram)} method. *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. * @return a ShaderProgram that uses the RGBA shader {@link #fragmentShaderRGBA} */ public static ShaderProgram makeRGBAShader() { ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShaderRGBA); if(!shader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shader: " + shader.getLog()); return shader; } /** * A simple helper method that builds the simplest shader here; this shader allows tinting with light colors to * lighten an image, and also smooths changes well. You can assign the result to a SpriteBatch with its * {@link SpriteBatch#setShader(ShaderProgram)} method. *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. * @return a ShaderProgram that uses the RGBA shader {@link #fragmentShaderGammaRGBA} */ public static ShaderProgram makeGammaRGBAShader() { ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShaderGammaRGBA); if(!shader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shader: " + shader.getLog()); return shader; } /** * Where the magic happens; this converts a batch color from the YCwCm format (used by colorful's ycwcm package) to * RGBA. The vertex color will be split up into 4 channels just as a normal shader does, but the channels here are * luma, chromatic warmth, chromatic mildness, and alpha; alpha acts just like a typical RGBA shader, but the others * are additive instead of multiplicative, with 0.5 as a neutral value. This does not support the "tweak" features * that {@link ColorfulBatch} does, which include multiplicative counterparts to the additive operations this * supports on luma, chromatic warmth, and chromatic mildness, plus a contrast adjustment. If you want to adjust * contrast globally, you can use {@link #makeBatch(float)} to set the contrast for a new Batch with a new shader. *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. *
* Meant for use with {@link #vertexShader}. */ public static final String fragmentShader = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "const vec3 bright = vec3(0.375, 0.5, 0.125);\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + "////use the following line to match the color exactly\n" + " vec3 ycc = vec3(v_color.r - 0.5 + dot(tgt.rgb, bright), ((v_color.g - 0.5) * 2.0 + tgt.r - tgt.b), ((v_color.b - 0.5) * 2.0 + tgt.g - tgt.b));\n" + "////use the following line to increase contrast\n" + "// vec3 ycc = vec3(v_color.r * dot(sin(tgt.rgb * 1.5707963267948966) * sqrt(tgt.rgb), bright), ((v_color.g - 0.5) * 2.0 + tgt.r - tgt.b), ((v_color.b - 0.5) * 2.0 + tgt.g - tgt.b));\n" + "////use the following line to increase contrast more\n" + "// vec3 ycc = vec3(v_color.r * pow(dot(tgt.rgb, bright), 1.25), ((v_color.g - 0.5) * 2.0 + tgt.r - tgt.b), ((v_color.b - 0.5) * 2.0 + tgt.g - tgt.b));\n" + //uses a specific matrix (related to bright, above) multiplied with ycc to get back to rgb. " gl_FragColor = vec4( (clamp(mat3(1.0, 1.0, 1.0, 0.625, -0.375, -0.375, -0.5, 0.5, -0.5) * ycc, 0.0, 1.0)), v_color.a * tgt.a);\n" + "}"; /** * A variant on {@link #fragmentShader} that adjusts luma to make mid-range colors darker, while keeping light * colors light. This is not the same as {@link ColorfulBatch} even when the contrast for ColorfulBatch's tweak is * the same as what this uses (1.375 here, which is roughly 0.875f in a tweak value). ColorfulBatch does some work * in the vertex shader so it may be a little faster than this approach, and it seems to have less severe effects on * the overall brightness of an image that has adjusted contrast. *
* You can generate YCwCm colors using any of various methods in the {@code ycwcm} package, such as * {@link com.github.tommyettinger.colorful.ycwcm.ColorTools#ycwcm(float, float, float, float)}. *
* Meant for use with {@link #vertexShader}. */ public static final String fragmentShaderHigherContrast = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "const float contrast = 1.375 ; // You can make contrast a uniform if you want.\n" + "const vec3 bright = vec3(0.375, 0.5, 0.125) * (4.0 / 3.0);\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec3 ycc = vec3(v_color.r - 0.5 + pow(dot(tgt.rgb, bright), contrast) * 0.75, ((v_color.g - 0.5) * 2.0 + tgt.r - tgt.b), ((v_color.b - 0.5) * 2.0 + tgt.g - tgt.b));\n" + " gl_FragColor = vec4( (clamp(mat3(1.0, 1.0, 1.0, 0.625, -0.375, -0.375, -0.5, 0.5, -0.5) * ycc, 0.0, 1.0)), v_color.a * tgt.a);\n" + "}"; /** * An alternative shader that effectively reduces luma contrast, bringing all but the darkest colors to the * upper-mid luma range. This is not the same as {@link ColorfulBatch} even when the contrast for ColorfulBatch's * tweak is the same as what this uses (0.625 here, which is roughly 0.125f in a tweak value). ColorfulBatch does * some work in the vertex shader so it may be a little faster than this approach, and it seems to have less severe * effects on the overall brightness of an image that has adjusted contrast. *
* You can generate YCwCm colors using any of various methods in the {@code ycwcm} package, such as * {@link com.github.tommyettinger.colorful.ycwcm.ColorTools#ycwcm(float, float, float, float)}. *
* Meant for use with {@link #vertexShader}. */ public static final String fragmentShaderLowerContrast = fragmentShaderHigherContrast.replace(" 1.375 ", "0.625"); /** * Prepares and returns a new SpriteBatch that uses the default {@link #vertexShader} and {@link #fragmentShader} * from this class, making it able to render YCwCm colors from the ycwcm package. It won't be a * {@link ColorfulBatch} (those can adjust colors in more ways); you can simply use {@code new ColorfulBatch()} to * make one of those. Note that a SpriteBatch like this produces won't be able to render a {@link ColorfulSprite}, * but ColorfulBatch can. *
* You can generate YCwCm colors using any of various methods in the {@code ycwcm} package, such as * {@link com.github.tommyettinger.colorful.ycwcm.ColorTools#ycwcm(float, float, float, float)}. * @return a freshly allocated SpriteBatch that will also have a new ShaderProgram for rendering YCwCm */ public static SpriteBatch makeBatch() { ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShader); if(!shader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shader: " + shader.getLog()); return new SpriteBatch(1000, shader); } /** * Prepares and returns a new SpriteBatch that uses the default {@link #vertexShader} and {@link #fragmentShader} * from this class, making it able to render YCwCm colors from the ycwcm package. This also takes a * {@code contrast} parameter; if greater than 1.0 it will make light colors lighter and dark colors darker, while * if it is less than 1.0 it will make all but the darkest colors closer to the upper-middle-range of lightness. * If you want to adjust contrast per-sprite, use a {@link ColorfulBatch} (those can adjust colors in more ways); * you can simply use {@code new ColorfulBatch()} to make one of those. Note that a SpriteBatch like this produces * won't be able to render a {@link ColorfulSprite}, but ColorfulBatch can. ColorfulBatch also will calculate * contrast differently from the shader this uses, including doing some work in the vertex shader (which may be * faster). It also takes a contrast in its tweak value that is limited to a 0.0 to 1.0 range, rather than 0.1 to * 2.0 here (this can technically tolerate 0.01 to 10.0, but those extremes aren't recommended). *
* You can generate YCwCm colors using any of various methods in the {@code ycwcm} package, such as * {@link com.github.tommyettinger.colorful.ycwcm.ColorTools#ycwcm(float, float, float, float)}. * @param contrast how much contrast should be emphasized; higher than 1.0 is more contrasting, and this should usually be between 0.1 and 2.0 * @return a freshly allocated SpriteBatch that will also have a new ShaderProgram for rendering YCwCm */ public static SpriteBatch makeBatch(final float contrast) { ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShaderHigherContrast.replace(" 1.375 ", Float.toString(Math.min(Math.max(contrast, 0.01f), 10f)))); if(!shader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shader: " + shader.getLog()); return new SpriteBatch(1000, shader); } /** * Prepares and returns a new SpriteBatch that uses {@link #vertexShaderHSLC} and {@link #fragmentShaderHSLC} * from this class, making it interpret the SpriteBatch's color, as set by * {@link SpriteBatch#setColor(float, float, float, float)}, to be hue rotation, saturation change, lightness * change, and contrast change. All of these are neutral when their value is 0.5f. Hue rotates clockwise or * counterclockwise when it goes toward 0.0, and the other way when it goes toward 1.0; 0.0 and 1.0 both refer to * the 180 degree rotation, but I don't know which goes which way (it also depends on how you visualize hue). * Saturation becomes more grayscale as it goes towards 0.0, and more vivid as it goes towards 1.0. Lightness gets * darker towards 0.0, lighter towards 1.0 (any lightness above 0.5 will brighten the image, unlike the default * shader and batch color). Contrast affects changes in lightness; low contrast makes all lightness closer to the * mid-range, while high contrast makes even small changes in the mid-range of an image's color have stark lightness * changes in the result. Note, this does not support changing an image's alpha with the batch color. *
* You can generate HSLC colors using {@link FloatColors#rgb2hsl(float, float, float, float)}, using the last * parameter to store contrast. * @return a freshly allocated SpriteBatch that will also have a new ShaderProgram for rendering HSLC */ public static SpriteBatch makeBatchHSLC() { ShaderProgram shader = new ShaderProgram(vertexShaderHSLC, fragmentShaderHSLC); if(!shader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shader: " + shader.getLog()); return new SpriteBatch(1000, shader); } /** * Similar to {@link #fragmentShader}, but this uses the very perceptually-accurate IPT color space as described by * Ebner and Fairchild, instead of the custom YCwCm color space. IPT doesn't really need that much more computation * to be done by the shader, but tends to make gradual changes in color much smoother. If comparing to YCwCm, then * Y (luma) is like I (intensity) here, so when a Batch color has 0 for I (stored in the r channel), it makes the * image very dark, while if the Batch color has 1 for I, it makes the image very light. Cw and Cm can be graphed * like a color wheel, and in their case, the 4 corners of a square graph are red, yellow, green, and blue. IPT is * less geometrical, and the corners are roughly purple, orange, green, and cyan, while the centers of the edges of * the square are close to red, yellow, green, and blue. See this capture * of the IPT space if you want a better picture. The P (short for protan, a term from ophthalmology) channel * (stored in g) is the left-to-right axis there, with P==0 making colors green or blue (cooler), and P==1 making * colors orange, red, or purple (somewhat warmer). The T (short for tritan, also from ophthalmology) channel * (stored in b) is the down-to-up axis there, with T==0 making colors more blue or purple, and T==1 making colors * more green, yellow, brown, or orange. Where protan can be viewed as going from cool to warm as its value * increases, tritan can be viewed as going from artificial to natural, or perhaps fluid to solid. Alpha is treated * exactly as it is in the standard libGDX fragment shader, with the alpha in the batch color multiplied by the * alpha in the image pixel to get the result alpha. *
* You can generate IPT colors using any of various methods in the {@code ipt} package, such as * {@link com.github.tommyettinger.colorful.ipt.ColorTools#ipt(float, float, float, float)}. Note that IPT is * intended to share an API with the {@code ipt_hq} package, but IPT_HQ is usually preferred. *
* Meant for use with {@link #vertexShader}. */ public static String fragmentShaderIPT = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec4 adj = v_color;\n" + " adj.yz = adj.yz * 2.0 - 0.5;\n" + " vec3 ipt = (mat3(0.189786, 0.669665 , 0.286498, 0.576951, -0.73741 , 0.655205, 0.233221, 0.0681367, -0.941748)\n" + " * (tgt.rgb)) + adj.xyz - 0.5;\n" + " ipt.x = clamp(ipt.x, 0.0, 1.0);\n" + " ipt.yz = clamp(ipt.yz, -1.0, 1.0);\n" + " vec3 back = mat3(0.999779, 1.00015, 0.999769, 1.07094, -0.377744, 0.0629496, 0.324891, 0.220439, -0.809638) * ipt;\n" + " gl_FragColor = vec4(clamp(back, 0.0, 1.0), adj.a * tgt.a);\n" + "}"; /** * Just like {@link #fragmentShaderIPT}, but gamma-corrects the input and output RGB values (which improves * lightness uniformity) and uses an exponential step internally to change how colors are distributed within the * gamut. These steps are more computationally expensive than the bare-bones ones in {@link #fragmentShaderIPT}, but * they seem to improve some aspects of color transitions quite a bit. *
* You can generate IPT_HQ colors using any of various methods in the {@code ipt_hq} package, such as * {@link com.github.tommyettinger.colorful.ipt_hq.ColorTools#ipt(float, float, float, float)}. Note that IPT_HQ is * intended to share an API with the {@code ipt} package, but IPT_HQ is usually preferred. *
* Meant for use with {@link #vertexShader}. */ public static String fragmentShaderIPT_HQ = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "const vec3 forward = vec3(0.43);\n" + "const vec3 reverse = vec3(1.0 / 0.43);\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec3 ipt = mat3(0.40000, 4.45500, 0.80560, 0.40000, -4.8510, 0.35720, 0.20000, 0.39600, -1.1628) *" + " pow(mat3(0.313921, 0.151693, 0.017753, 0.639468, 0.748209, 0.109468, 0.0465970, 0.1000044, 0.8729690) \n" + " * (tgt.rgb * tgt.rgb), forward);\n" + " ipt.x = clamp(ipt.x + v_color.x - 0.55, 0.0, 1.0);\n" + " ipt.yz = clamp(ipt.yz + v_color.yz * 2.0 - 1.0, -1.0, 1.0);\n" + " ipt = mat3(1.0, 1.0, 1.0, 0.097569, -0.11388, 0.032615, 0.205226, 0.133217, -0.67689) * ipt;\n" + " gl_FragColor = vec4(sqrt(clamp(" + " mat3(5.432622, -1.10517, 0.028104, -4.67910, 2.311198, -0.19466, 0.246257, -0.20588, 1.166325) *\n" + " (sign(ipt) * pow(abs(ipt), reverse))," + " 0.0, 1.0)), v_color.a * tgt.a);\n" + "}"; /** * Just like {@link #fragmentShaderIPT_HQ}, but uses the Oklab color space instead of the very similar IPT_HQ one. * This also gamma-corrects the inputs and outputs, though it uses subtly different math internally. Oklab colors * tend to have more variation on their L channel, which represents lightness, than their A or B channels, which * represent green-to-red and blue-to-yellow chromatic axes; indeed, A and B tend to be no more than about 1/6 away * from their middle point at 1/2, which is used for grayscale. This is normal for Oklab, and allows colors to be * compared for approximate difference using Euclidean distance. Importantly, Oklab preserves the meaning of its L * channel (lightness) very well when comparing two arbitrary colors, while also doing well when comparing chroma * (see {@link com.github.tommyettinger.colorful.oklab.ColorTools#chroma(float)}. *
* You can generate Oklab colors using any of various methods in the {@code oklab} package, such as * {@link com.github.tommyettinger.colorful.oklab.ColorTools#oklab(float, float, float, float)}. *
* Meant for use with {@link #vertexShader}. */ public static String fragmentShaderOklab = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "const vec3 forward = vec3(1.0 / 3.0);\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec3 lab = mat3(+0.2104542553, +1.9779984951, +0.0259040371, +0.7936177850, -2.4285922050, +0.7827717662, -0.0040720468, +0.4505937099, -0.8086757660) *" + " pow(mat3(0.4121656120, 0.2118591070, 0.0883097947, 0.5362752080, 0.6807189584, 0.2818474174, 0.0514575653, 0.1074065790, 0.6302613616) \n" + " * (tgt.rgb * tgt.rgb), forward);\n" + " lab.x = clamp(lab.x + v_color.r - 0.63, 0.0, 1.0);\n" + " lab.yz = clamp(lab.yz + v_color.gb * 2.0 - 1.0, -1.0, 1.0);\n" + " lab = mat3(1.0, 1.0, 1.0, +0.3963377774, -0.1055613458, -0.0894841775, +0.2158037573, -0.0638541728, -1.2914855480) * lab;\n" + " gl_FragColor = vec4(sqrt(clamp(" + " mat3(+4.0767245293, -1.2681437731, -0.0041119885, -3.3072168827, +2.6093323231, -0.7034763098, +0.2307590544, -0.3411344290, +1.7068625689) *\n" + " (lab * lab * lab)," + " 0.0, 1.0)), v_color.a * tgt.a);\n" + "}"; /** * A vertex shader that does the bulk of processing HSI-format batch colors and converting them to a format * {@link #fragmentShaderHSI} can use. Since HSI is only a cylindrical/spherical adaptation of IPT, with identical * I components and the combination of H and S in polar coordinates mapping to P and T in Cartesian coordinates, * the fragment shader this is used with can be any that expects an IPT color (currently only * {@link #fragmentShaderIPT} does this, and it's the same as {@link #fragmentShaderHSI}). This vertex shader does * a lot more than most vertex shaders here, but since it is executed relatively rarely (unless you're drawing many * 1-pixel textures), there shouldn't be a heavy performance penalty. *
* There is no special code to generate HSI colors; you can use * {@link com.github.tommyettinger.colorful.ipt.ColorTools#ipt(float, float, float, float)}, or any ColorTools * method that generates a packed float color directly from the channel values, to specify hue, saturation, * intensity, and alpha in that order. You can also just specify the batch color directly with * {@link SpriteBatch#setColor(float, float, float, float)}, taking the channels in the same order as above. *
* EXPERIMENTAL. Meant more for reading and editing than serious usage. */ public static final String vertexShaderHSI = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" + "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" + "uniform mat4 u_projTrans;\n" + "varying vec4 v_color;\n" + "varying vec2 v_texCoords;\n" + "const vec3 yellow = vec3( 0.16155326,0.020876605,-0.26078433 );\n" + "const vec3 magenta = vec3(-0.16136102,0.122068435,-0.070396 );\n" + "const vec3 cyan = vec3( 0.16420607,0.3481738, 0.104959644);\n" + "void main()\n" + "{\n" + " v_color = " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" + " v_color.a = " + ShaderProgram.COLOR_ATTRIBUTE + ".a * (255.0/254.0);\n" + " vec3 hsi = v_color.rgb;\n" + " v_color.x = (hsi.z - 0.5) * 0.9999;\n" + " hsi.x *= 6.28318;\n" + " hsi.y *= 0.5;\n" + " v_color.y = cos(hsi.x) * hsi.y;\n" + " v_color.z = sin(hsi.x) * hsi.y;\n" + " float crMid = dot(cyan.yz, v_color.yz);\n" + " float mgMid = dot(magenta.yz, v_color.yz);\n" + " float ybMid = dot(yellow.yz, v_color.yz);\n" + " float crScale = (v_color.x - 0.5 + step(crMid, 0.0)) * cyan.x / (0.00001 - crMid);\n" + " float mgScale = (v_color.x + 0.5 - step(mgMid, 0.0)) * magenta.x / (0.00001 - mgMid);\n" + " float ybScale = (v_color.x - 0.5 + step(ybMid, 0.0)) * yellow.x / (0.00001 - ybMid);\n" + " float scale = 4.0 * min(crScale, min(mgScale, ybScale));\n" + " v_color.yz *= scale * length(v_color.yz) / cos(3.14159 * v_color.x);\n" + " v_color.xyz += 0.5;\n" + " v_texCoords = " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" + " gl_Position = u_projTrans * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + "}\n"; /** * This is an alias for {@link #fragmentShaderIPT}. If used with {@link #vertexShaderHSI}, you can specify a batch * color using an HSL-like system. *
* There is no special code to generate HSI colors; you can use * {@link com.github.tommyettinger.colorful.ipt.ColorTools#ipt(float, float, float, float)}, or any ColorTools * method that generates a packed float color directly from the channel values, to specify hue, saturation, * intensity, and alpha in that order. You can also just specify the batch color directly with * {@link SpriteBatch#setColor(float, float, float, float)}, taking the channels in the same order as above. *
* Meant for use with {@link #vertexShaderHSI}. */ public static String fragmentShaderHSI = fragmentShaderIPT; /** * Not a full shader, this is a snippet used by most of the other HSL-based shaders to implement the complex * rgb2hsl() and hsl2rgb() methods. There are also comments in the code snippet that you can use if you want to * change the distribution of colors across the color wheel. *
* Credit to , https://gamedev.stackexchange.com/a/59808 . *
* EXPERIMENTAL. Meant more for reading and editing than serious usage. */ public static final String partialCodeHSL = "const float eps = 1.0e-10;\n" + "////Call this to go from the official HSL hue distribution (where blue is opposite yellow) to a\n" + "////different distribution that matches primary colors in painting (where purple is opposite yellow).\n" + "//float official2primaries(float hue) {\n" + "// return hue * ( 2.137\n" + "// + hue * ( 0.542\n" + "// + hue * (-15.141\n" + "// + hue * ( 30.120\n" + "// + hue * (-22.541\n" + "// + hue * 5.883)))));\n" + "//}\n" + "////Call this to go to the official HSL hue distribution (where blue is opposite yellow) from a\n" + "////different distribution that matches primary colors in painting (where purple is opposite yellow).\n" + "//float primaries2official(float hue) {\n" + "// return hue * ( 0.677\n" + "// + hue * ( -0.123\n" + "// + hue * (-11.302\n" + "// + hue * ( 46.767\n" + "// + hue * (-58.493\n" + "// + hue * 23.474)))));\n" + "//}\n" + "vec4 rgb2hsl(vec4 c)\n" + "{\n" + " const vec4 J = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n" + " vec4 p = mix(vec4(c.bg, J.wz), vec4(c.gb, J.xy), step(c.b, c.g));\n" + " vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n" + " float d = q.x - min(q.w, q.y);\n" + " float l = q.x * (1.0 - 0.5 * d / (q.x + eps));\n" + " return vec4(abs(q.z + (q.w - q.y) / (6.0 * d + eps)), (q.x - l) / (min(l, 1.0 - l) + eps), l, c.a);\n" + "}\n" + "\n" + "vec4 hsl2rgb(vec4 c)\n" + "{\n" + " const vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n" + " vec3 p = abs(fract(c.x + K.xyz) * 6.0 - K.www);\n" + " float v = (c.z + c.y * min(c.z, 1.0 - c.z));\n" + " return vec4(v * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), 2.0 * (1.0 - c.z / (v + eps))), c.w);\n" + "}"; /** * Adjusted-hue version of {@link #partialCodeHSL}, supplying HSL to-and-from RGB conversions with a smaller range * of hue used for cyan and a larger range for orange. Not currently used. This is pretty much only meant so people * reading the source code and trying different variations on HSL can see some of the attempts I made. *
* Credit to , https://gamedev.stackexchange.com/a/59808 . *
* EXPERIMENTAL. Meant more for reading and editing than serious usage. */ public static final String partialCodeHSLStretched = "const float eps = 1.0e-10;\n" + //// maybe not blue enough? // //Call this to go from the official HSL hue distribution (where blue is opposite yellow) to a // //different distribution that matches primary colors in painting (where purple is opposite yellow). // "float official2primaries(float hue) {\n" + // " return hue * ( 1.630\n" + // " + hue * ( 5.937\n" + // " + hue * (-38.485\n" + // " + hue * ( 76.101\n" + // " + hue * (-63.977\n" + // " + hue * 19.794)))));\n" + // "}\n" + // //Call this to go to the official HSL hue distribution (where blue is opposite yellow) from a // //different distribution that matches primary colors in painting (where purple is opposite yellow). // "float primaries2official(float hue) {\n" + // " return hue * ( 1.463\n" + // " + hue * ( -9.834\n" + // " + hue * ( 31.153\n" + // " + hue * (-35.066\n" + // " + hue * 13.284))));\n" + // "}\n" + //// still weirdly high orange // "float official2primaries(float hue) {\n" + // " return hue * ( 2.634\n" + // " + hue * ( -4.703\n" + // " + hue * ( 3.659\n" + // " + hue * ( 0.829\n" + // " + hue * -1.419))));\n" + // "}\n" + // "float primaries2official(float hue) {\n" + // " return hue * ( 1.163\n" + // " + hue * ( -7.102\n" + // " + hue * ( 22.709\n" + // " + hue * (-25.502\n" + // " + hue * 9.732))));\n" + // "}\n" + // "const float ROOT = 16.0;\n" + // "const float SQUARE = ROOT * ROOT;\n" + "float official2primaries(float hue) {\n" + // " return (sqrt(hue * 0.9375 + 0.0625) - 0.25) * 1.333;\n" + // " return asin(sqrt(hue * SQUARE) * (1.0 / ROOT)) * (2.0 * 3.14159274);\n" + // " return asin((sqrt(hue * 0.9375 + 0.0625) - 0.25) * 2.666 - 1.0) * 0.318309886 + 0.5;\n" + // " return sqrt(sin((hue - 0.5) * 3.14159274) * 0.5 + 0.5);\n" + // " return pow(hue, 0.5625);\n" + // " return sqrt(hue);\n" + " return (sqrt(hue + 0.050625) - 0.225) * 1.25;\n" + "}\n" + "float primaries2official(float hue) {\n" + // " hue = sin((hue) * (0.5 * 3.14159274));\n" + // " hue = (hue) * 0.75 + 0.25;\n" + // " hue = sin((hue - 0.5) * 3.14159274);\n" + // " hue = (hue + 1.0) * 0.375 + 0.25;\n" + // " return (hue * hue - 0.0625) * (1.0 / 0.9375);\n" + // " return asin(hue * hue * 2.0 - 1.0) * 0.318309886 + 0.5;\n" + // " return pow(hue, 1.77777);\n" + " return pow(hue * 0.8 + 0.225, 2.0) - 0.050625;\n" + // " return hue * hue;\n" + // " hue = sin((hue) * (0.5 * 3.14159274));\n" + // " hue = hue * ROOT;\n" + // " return (hue * hue) * (1.0 / SQUARE);\n" + "}\n" + //// way too much orange? // //Call this to go from the official HSL hue distribution (where blue is opposite yellow) to a // //different distribution that matches primary colors in painting (where purple is opposite yellow). // "float official2primaries(float hue) {\n" + // " return hue * ( 2.137\n" + // " + hue * ( 0.542\n" + // " + hue * (-15.141\n" + // " + hue * ( 30.120\n" + // " + hue * (-22.541\n" + // " + hue * 5.883)))));\n" + // "}\n" + // //Call this to go to the official HSL hue distribution (where blue is opposite yellow) from a // //different distribution that matches primary colors in painting (where purple is opposite yellow). // "float primaries2official(float hue) {\n" + // " return hue * ( 0.677\n" + // " + hue * ( -0.123\n" + // " + hue * (-11.302\n" + // " + hue * ( 46.767\n" + // " + hue * (-58.493\n" + // " + hue * 23.474)))));\n" + // "}\n" + "vec4 rgb2hsl(vec4 c)\n" + "{\n" + " const vec4 J = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n" + " vec4 p = mix(vec4(c.bg, J.wz), vec4(c.gb, J.xy), step(c.b, c.g));\n" + " vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n" + "\n" + " float d = q.x - min(q.w, q.y);\n" + " float l = q.x * (1.0 - 0.5 * d / (q.x + eps));\n" + " return vec4(official2primaries(abs(q.z + (q.w - q.y) / (6.0 * d + eps))), (q.x - l) / (min(l, 1.0 - l) + eps), l, c.a);\n" + "}\n" + "\n" + "vec4 hsl2rgb(vec4 c)\n" + "{\n" + " const vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n" + " vec3 p = abs(fract(primaries2official(c.x) + K.xyz) * 6.0 - K.www);\n" + " float v = (c.z + c.y * min(c.z, 1.0 - c.z));\n" + " return vec4(v * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), 2.0 * (1.0 - c.z / (v + eps))), c.w);\n" + "}"; /** * This GLSL snippet takes an RGB vec3 and a float that represents a hue rotation in radians, and returns the * rotated RGB vec3. It is not a full shader, and is used by inserting it into shader code to provide the applyHue() * method to that code. *
* Credit for this challenging method goes to Andrey-Postelzhuk, * Unity Forums. */ public static final String partialHueRodrigues = "vec3 applyHue(vec3 rgb, float hue)\n" + "{\n" + " vec3 k = vec3(0.57735);\n" + " float c = cos(hue);\n" + " //Rodrigues' rotation formula\n" + " return rgb * c + cross(k, rgb) * sin(hue) + k * dot(k, rgb) * (1.0 - c);\n" + "}\n"; /** * Treats the color as hue, saturation, lightness, and... uh... well, this is pretty much only useful when the batch * color's {@code a} is 1 . You probably want {@link #fragmentShaderHSLC} or {@link #fragmentShaderHSLA}. *
* EXPERIMENTAL. Meant more for reading and editing than serious usage. */ public static final String fragmentShaderHSL = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + partialCodeHSL + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec4 hsl = rgb2hsl(tgt);\n" + " hsl.x = fract((fract(v_color.x + 0.5 - hsl.x) - 0.5) * v_color.w + hsl.x);\n" + " hsl.yz = mix(hsl.yz, v_color.yz, v_color.w);\n" + " gl_FragColor = hsl2rgb(hsl);\n" + "}"; /** * I can't even remember what this does, to be honest. It's probably not what you want. Instead, you probably want * {@link #fragmentShaderHSLC} or {@link #fragmentShaderHSLA}. *
* EXPERIMENTAL. Meant more for reading and editing than serious usage. */ public static final String fragmentShaderRotateHSL = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + partialCodeHSL + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec4 hsl = rgb2hsl(tgt);\n" + " hsl.x = fract(v_color.x + hsl.x + 0.5);\n" + " hsl.yz = clamp(hsl.yz * v_color.yz * 2.0, 0.0, 1.0);\n" + " gl_FragColor = hsl2rgb(hsl);\n" + "}"; /** * This is similar to the default vertex shader from libGDX, but also sets a varying value for contrast. It is * needed if you use {@link #fragmentShaderHSLC}. */ public static final String vertexShaderHSLC = "attribute vec4 a_position;\n" + "attribute vec4 a_color;\n" + "attribute vec2 a_texCoord0;\n" + "uniform mat4 u_projTrans;\n" + "varying vec4 v_color;\n" + "varying vec2 v_texCoords;\n" + "varying float v_lightFix;\n" + "\n" + "void main()\n" + "{\n" + " v_color = a_color;\n" + " v_texCoords = a_texCoord0;\n" + " v_color.a = pow(v_color.a * (255.0/254.0) + 0.5, 1.709);\n" + " v_lightFix = 1.0 + pow(v_color.a, 1.41421356);\n" + " gl_Position = u_projTrans * a_position;\n" + "}\n"; /** * Allows changing Hue/Saturation/Lightness/Contrast, with hue as a rotation. If hue continuously goes from 0 to 1, * then 0 to 1, 0 to 1, and so on, then this will smoothly rotate the hue of the image. *
* You can generate HSLC colors using methods like {@link FloatColors#rgb2hsl(float, float, float, float)}. *
* Credit for HLSL version goes to Andrey-Postelzhuk, * Unity Forums. * The YCC adaptation, and different approach to contrast (this has close to neutral contrast when a is 0.5, * while the original had a fair bit higher contrast than expected), is from this codebase. *
* Meant only for use with {@link #vertexShaderHSLC}, which sets {@code varying float v_lightFix} so contrast can * use it. */ public static final String fragmentShaderHSLC = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying float v_lightFix;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + partialHueRodrigues + "void main()\n" + "{\n" + " float hue = 6.2831853 * (v_color.x - 0.5);\n" + " float saturation = v_color.y * 2.0;\n" + " float brightness = v_color.z - 0.5;\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " tgt.rgb = applyHue(tgt.rgb, hue);\n" + " tgt.rgb = vec3(\n" + " (0.5 * pow(dot(tgt.rgb, vec3(0.375, 0.5, 0.125)), v_color.w) * v_lightFix + brightness),\n" + // lightness " ((tgt.r - tgt.b) * saturation),\n" + // warmth " ((tgt.g - tgt.b) * saturation));\n" + // mildness " gl_FragColor = clamp(vec4(\n" + " dot(tgt.rgb, vec3(1.0, 0.625, -0.5)),\n" + // back to red " dot(tgt.rgb, vec3(1.0, -0.375, 0.5)),\n" + // back to green " dot(tgt.rgb, vec3(1.0, -0.375, -0.5)),\n" + // back to blue " tgt.a), 0.0, 1.0);\n" + // keep alpha, then clamp "}"; /** * Allows changing Hue/Saturation/Lightness/Alpha, with hue as a rotation. *
* You can generate HSLA colors using methods like {@link FloatColors#rgb2hsl(float, float, float, float)}. *
* Credit for HLSL version goes to Andrey-Postelzhuk, * Unity Forums. * The YCC adaptation, and change to use alpha, is from this codebase. *
* Meant to be used with {@link #vertexShader}, unlike what {@link #fragmentShaderHSLC} expects. */ public static final String fragmentShaderHSLA = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + partialHueRodrigues + "void main()\n" + "{\n" + " float hue = 6.2831853 * (v_color.x - 0.5);\n" + " float saturation = v_color.y * 2.0;\n" + " float brightness = v_color.z - 0.5;\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " tgt.rgb = applyHue(tgt.rgb, hue);\n" + " tgt.rgb = vec3(\n" + " (dot(tgt.rgb, vec3(0.375, 0.5, 0.125)) + brightness),\n" + // lightness " ((tgt.r - tgt.b) * saturation),\n" + // warmth " ((tgt.g - tgt.b) * saturation));\n" + // mildness " gl_FragColor = clamp(vec4(\n" + " dot(tgt.rgb, vec3(1.0, 0.625, -0.5)),\n" + // back to red " dot(tgt.rgb, vec3(1.0, -0.375, 0.5)),\n" + // back to green " dot(tgt.rgb, vec3(1.0, -0.375, -0.5)),\n" + // back to blue " tgt.a * v_color.w), 0.0, 1.0);\n" + // keep alpha, then clamp "}"; /** * Generally a lower-quality hue rotation than {@link #fragmentShaderHSLC}; this is here as a work in progress. *
* You can generate HSLC colors using methods like {@link FloatColors#rgb2hsl(float, float, float, float)}. *
* Meant to be used with {@link #vertexShaderHSLC}, which sets {@code varying float v_lightFix} so * contrast can use it. *
* EXPERIMENTAL. Meant more for reading and editing than serious usage. */ public static final String fragmentShaderHSLC2 = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying float v_lightFix;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + partialCodeHSL + "void main()\n" + "{\n" + " float hue = (v_color.x - 0.5);\n" + " float saturation = v_color.y * 2.0;\n" + " float brightness = v_color.z - 0.5;\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " tgt = rgb2hsl(tgt);\n" + " tgt.r = fract(tgt.r + hue);\n" + " tgt = hsl2rgb(tgt);\n" + " tgt.rgb = vec3(\n" + " (0.5 * pow(dot(tgt.rgb, vec3(0.375, 0.5, 0.125)), v_color.w) * v_lightFix + brightness),\n" + // lightness " ((tgt.r - tgt.b) * saturation),\n" + // warmth " ((tgt.g - tgt.b) * saturation));\n" + // mildness " gl_FragColor = clamp(vec4(\n" + " dot(tgt.rgb, vec3(1.0, 0.625, -0.5)),\n" + // back to red " dot(tgt.rgb, vec3(1.0, -0.375, 0.5)),\n" + // back to green " dot(tgt.rgb, vec3(1.0, -0.375, -0.5)),\n" + // back to blue " tgt.a), 0.0, 1.0);\n" + // keep alpha, then clamp "}"; /** * Cycles lightness in a psychedelic way as hue and lightness change; not a general-purpose usage. *
* You can generate HSLC colors using methods like {@link FloatColors#rgb2hsl(float, float, float, float)}. *
* Meant to be used with {@link #vertexShaderHSLC}, which sets {@code varying float v_lightFix} so * contrast can use it. *
* EXPERIMENTAL. Meant more for reading and editing than serious usage. */ public static final String fragmentShaderHSLC3 = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying float v_lightFix;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "vec3 applyHue(vec3 rgb, float hue)\n" + partialHueRodrigues + "void main()\n" + "{\n" + " float hue = 6.2831853 * (v_color.x - 0.5);\n" + " float saturation = v_color.y * 2.0;\n" + " float brightness = v_color.z - 0.5;\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " tgt.rgb = applyHue(tgt.rgb, hue);\n" + " tgt.rgb = vec3(\n" + " (0.5 * pow(dot(tgt.rgb, vec3(0.375, 0.5, 0.125)), v_color.w) * v_lightFix),\n" + // lightness " ((tgt.r - tgt.b) * saturation),\n" + // warmth " ((tgt.g - tgt.b) * saturation));\n" + // mildness " tgt.r = sin((tgt.r + brightness) * 6.2831853) * 0.5 + 0.5;\n" + " gl_FragColor = clamp(vec4(\n" + " dot(tgt.rgb, vec3(1.0, 0.625, -0.5)),\n" + // back to red " dot(tgt.rgb, vec3(1.0, -0.375, 0.5)),\n" + // back to green " dot(tgt.rgb, vec3(1.0, -0.375, -0.5)),\n" + // back to blue " tgt.a), 0.0, 1.0);\n" + // keep alpha, then clamp "}"; /** * Cycles hue, but not lightness; otherwise this is like {@link #fragmentShaderHSLC3} without contrast, and keeping * alpha intact. Internally, this uses Sam Hocevar's RGB/HSL conversion instead of Andrey-Postelzhuk's HSLC code. *
* You can generate HSLA colors using methods like {@link FloatColors#rgb2hsl(float, float, float, float)}. *
* Expects the vertex shader to be {@link #vertexShader}, not the HSLC variant. *
* EXPERIMENTAL. Meant more for reading and editing than serious usage. */ public static final String fragmentShaderHSLPsychedelic = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + partialCodeHSL + "void main()\n" + "{\n" + " float hue = v_color.x - 0.5;\n" + " float saturation = v_color.y * 2.0;\n" + " float brightness = v_color.z - 0.5;\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " tgt = rgb2hsl(tgt);\n" + " tgt.x = fract(tgt.x + hue);\n" + " tgt.y = clamp(tgt.y * saturation, 0.0, 1.0);\n" + " tgt.z = clamp(brightness + tgt.z, 0.0, 1.0);\n" + " gl_FragColor = hsl2rgb(tgt);\n" + "}"; /** * One of the more useful HSL shaders here, this takes a batch color as hue, saturation, lightness, and power, * with hue as a target hue and power used to determine how much of the target color should be used. There is no * neutral value for hue, saturation, or lightness, but if power is 0, then the source color will be used * exactly. On the other hand, if power is 1.0, then all pixels will be the target color. Hue is specified from * 0.0 to 1.0, with 0.0 as red, about 0.3 as green, about 0.6 as blue, etc. Saturation is specified from 0.0 to 1.0, * with 0.0 as grayscale and 1.0 as a fully-saturated target color. Lightness is specified from 0.0 to 1.0, with 0.0 * as black, the 0.3 to 0.7 range as most colors, and 1.0 white; saturation is clamped to a smaller value as * lightness moves away from 0.5 (toward black or white). *
* You can generate HSL(P) colors using methods like {@link FloatColors#rgb2hsl(float, float, float, float)}. */ public static final String fragmentShaderHSLP = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + partialCodeHSL + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec4 hsl = rgb2hsl(tgt);\n" + " hsl.xy = vec2(cos(hsl.x * 6.2831853), sin(hsl.x * 6.2831853)) * hsl.y;\n" + " vec3 tint = vec3(cos(v_color.x * 6.2831853) * v_color.y, sin(v_color.x * 6.2831853) * v_color.y, v_color.z);\n" + " hsl.xyz = mix(hsl.xyz, tint, v_color.w);\n" + " hsl.xy = vec2(fract(atan(hsl.y, hsl.x) / 6.2831853), length(hsl.xy));\n" + " gl_FragColor = hsl2rgb(hsl);\n" + "}"; /** * This is supposed to look for RGBA colors that are similar to {@code search}, and if it finds * one, to replace it with {@code replace} (also an RGBA color). It isn't great at the searching part. *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. *
* EXPERIMENTAL. Meant more for reading and editing than serious usage. */ public static final String fragmentShaderReplacement = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "uniform vec4 u_search;\n" + "uniform vec4 u_replace;\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D(u_texture, v_texCoords);\n" + " float curve = smoothstep(0.0, 1.0, 1.25 - distance(tgt.rgb, u_search.rgb) * 2.0);\n" + " gl_FragColor = vec4(mix(tgt.rgb, u_replace.rgb, curve), tgt.a) * v_color;\n" + "}"; /** * A drop-in replacement for the default fragment shader that eliminates lightness differences in the output colors. * Specifically, it does the normal SpriteBatch shader's step with the multiplicative batch color, converts to IPT, * sets intensity to 0.5, shrinks the P and T components so the color is less saturated, and then converts back to * an RGBA color. Even though this uses IPT internally, it expects the batch color to be normal RGBA. *
* Editing this shader is strongly encouraged to fit your needs! *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. *
* Meant for use with {@link #vertexShader}. * @see #fragmentShaderConfigurableContrast a per-sprite-configurable version of this */ public static String fragmentShaderFlatLightness = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "#define TARGET_LIGHTNESS 0.5 \n" + "#define SATURATION_CHANGE 1.0 \n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec3 ipt = (mat3(0.189786, 0.669665 , 0.286498, 0.576951, -0.73741 , 0.655205, 0.233221, 0.0681367, -0.941748)\n" + " * (tgt.rgb * v_color.rgb));\n" + " ipt.x = TARGET_LIGHTNESS;\n" + // change to desired lightness or pass in a lightness as a uniform "// ipt.x = (ipt.x - 0.5) * 0.25 + TARGET_LIGHTNESS;\n" + // an alternative way that preserves a tiny bit of original lightness " ipt.yz *= SATURATION_CHANGE;\n" + // multiplies saturation by SATURATION_CHANGE, which may be more or less than 1.0 " vec3 back = clamp(mat3(0.999779, 1.00015, 0.999769, 1.07094, -0.377744, 0.0629496, 0.324891, 0.220439, -0.809638) * ipt, 0.0, 1.0);\n" + " gl_FragColor = vec4(back, v_color.a * tgt.a);\n" + "}"; /** * A specialized shader that can reduce lightness differences in the output colors, saturate/desaturate them, and * can be configured to use some of the existing lightness in the image to add to a main flat lightness. * Specifically, it takes the fragment color (typically a pixel in a texture), converts to IPT, does a calculation * involving the intensity of the fragment color where the batch color's blue channel affects how much that * intensity is used, adds the red channel of the batch color, multiplies the P and T components by the green * channel times 2.0 to saturate or desaturate, and then converts back to an RGBA color. The neutral value for this * is the RGBA color 0.5, 0.5, 1.0, 1.0 . A typical usage to achieve a fog effect would be to raise lightness (r), * slightly reduce saturation (g), sharply flatten the original texture's lightness (b), and leave alpha alone (a): * 0.7, 0.4, 0.2, 1.0 . *
* This doesn't use a standard type of color; you should use something like * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)} to set the channels in * the specific way this uses them. *
* Meant for use with {@link #vertexShader}. * @see #fragmentShaderFlatLightness if you only need one contrast setting and still want to set color tints */ public static String fragmentShaderConfigurableContrast = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec3 ipt = (mat3(0.189786, 0.669665 , 0.286498, 0.576951, -0.73741 , 0.655205, 0.233221, 0.0681367, -0.941748)\n" + " * tgt.rgb);\n" + " ipt.x = (ipt.x - 0.5) * v_color.b + v_color.r;\n" + // preserves some lightness based on b, sets main lightness with r " ipt.yz *= v_color.g * 2.0;\n" + // the green channel affects saturation; if it's 0.5 it won't change saturation. " vec3 back = clamp(mat3(0.999779, 1.00015, 0.999769, 1.07094, -0.377744, 0.0629496, 0.324891, 0.220439, -0.809638) * ipt, 0.0, 1.0);\n" + " gl_FragColor = vec4(back, v_color.a * tgt.a);\n" + "}"; /** * A day/night cycle shader that can be used without any other parts of this library. This only needs setting the * uniform {@code u_timeOfDay} to any float; the rate at which you change this float affects how fast the day/night * cycle occurs. This is meant to be used with {@link #fragmentShaderDayNight}. Together, they make the color * adjustment go from bluish and dark at night, to purplish at dawn, to orange/yellow and bright at mid-day, toward * red at dusk, and then back to bluish at night. This uses an RGBA batch color. *
* Editing this shader is strongly encouraged to fit your needs! The time-based variables st, ct, and dd can all be * adjusted to increase or decrease the strength of the effect, and their effects can also be adjusted upon v_color * and v_tweak. *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. */ public static String vertexShaderDayNight = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" + "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" + "uniform mat4 u_projTrans;\n" + "uniform float u_timeOfDay;\n" + "varying vec4 v_color;\n" + "varying vec4 v_tweak;\n" + "varying vec2 v_texCoords;\n" + "varying float v_lightFix;\n" + "const vec3 forward = vec3(1.0 / 3.0);\n" + "\n" + "void main()\n" + "{\n" + " float st = sin(1.5707963 * sin(0.2617994 * u_timeOfDay)); // Whenever st is very high or low... \n" + " float ct = sin(1.5707963 * cos(0.2617994 * u_timeOfDay)); // ...ct is close to 0, and vice versa. \n" + " float dd = ct * ct; // Positive, small; used for dawn and dusk. \n" + " v_color = " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" + " v_color.w = v_color.w * (255.0/254.0);\n" + " vec3 oklab = mat3(+0.2104542553, +1.9779984951, +0.0259040371, +0.7936177850, -2.4285922050, +0.7827717662, -0.0040720468, +0.4505937099, -0.8086757660) *" + " pow(mat3(0.4121656120, 0.2118591070, 0.0883097947, 0.5362752080, 0.6807189584, 0.2818474174, 0.0514575653, 0.1074065790, 0.6302613616) \n" + " * (v_color.rgb * v_color.rgb), forward);\n" + " // The next four lines make use of the time-based variables st, ct, and dd. Edit to fit. \n" + " v_color.x = clamp(oklab.x + (0.0625 * st), 0.0, 1.0);\n" + " v_color.yz = clamp(oklab.yz + vec2(0.0625 * dd + 0.03125 * st, 0.1 * st), -1.0, 1.0) * ((dd + 0.25) * 0.5);\n" + " v_tweak = vec4(0.2 * st + 0.5);\n" + " v_tweak.w = pow((1.0 - 0.125 * st), 1.709);\n" + " v_lightFix = 1.0 + pow(v_tweak.w, 1.41421356);\n" + " v_texCoords = " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" + " gl_Position = u_projTrans * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + "}\n"; /** * The fragment shader counterpart to {@link #vertexShaderDayNight}; must be used with that vertex shader. See its * docs for more info, particularly about the one uniform this needs set. This uses an RGBA batch color. *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. *
* Meant only for use with {@link #vertexShaderDayNight}. */ public static String fragmentShaderDayNight = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "varying LOWP vec4 v_tweak;\n" + "varying float v_lightFix;\n" + "uniform sampler2D u_texture;\n" + "const vec3 forward = vec3(1.0 / 3.0);\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec3 lab = mat3(+0.2104542553, +1.9779984951, +0.0259040371, +0.7936177850, -2.4285922050, +0.7827717662, -0.0040720468, +0.4505937099, -0.8086757660) *" + " pow(mat3(0.4121656120, 0.2118591070, 0.0883097947, 0.5362752080, 0.6807189584, 0.2818474174, 0.0514575653, 0.1074065790, 0.6302613616) \n" + " * (tgt.rgb * tgt.rgb), forward);\n" + " lab.x = clamp(pow(lab.x, v_tweak.w) * v_lightFix * v_tweak.x + v_color.x - 1.0, 0.0, 1.0);\n" + " lab.yz = clamp((lab.yz * v_tweak.yz + v_color.yz) * 1.5, -1.0, 1.0);\n" + " lab = mat3(1.0, 1.0, 1.0, +0.3963377774, -0.1055613458, -0.0894841775, +0.2158037573, -0.0638541728, -1.2914855480) * lab;\n" + " gl_FragColor = vec4(sqrt(clamp(" + " mat3(+4.0767245293, -1.2681437731, -0.0041119885, -3.3072168827, +2.6093323231, -0.7034763098, +0.2307590544, -0.3411344290, +1.7068625689) *\n" + " (lab * lab * lab)," + " 0.0, 1.0)), v_color.a * tgt.a);\n" + "}"; /** * Takes a batch color in CIE LAB format (but ranging from 0 to 1 instead of its normal larger range). * Adapted from This ShaderToy by nmz. */ public static String fragmentShaderCielab = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "const vec3 forward = vec3(1.0 / 3.0);\n" + "const vec3 sRGBFrom = vec3(2.4);\n" + "const vec3 sRGBThresholdFrom = vec3(0.04045);\n" + "const vec3 sRGBTo = vec3(1.0 / 2.4);\n" + "const vec3 sRGBThresholdTo = vec3(0.0031308);\n" + "const vec3 epsilon = vec3(0.00885645);\n" + "vec3 linear(vec3 t){ return mix(pow((t + 0.055) * (1.0 / 1.055), sRGBFrom), t * (1.0/12.92), step(t, sRGBThresholdFrom)); }\n" + "vec3 sRGB(vec3 t){ return mix(1.055 * pow(t, sRGBTo) - 0.055, 12.92*t, step(t, sRGBThresholdTo)); }\n" + "float xyzF(float t){ return mix(pow(t,1./3.), 7.787037 * t + 0.139731, step(t, 0.00885645)); }\n" + "vec3 xyzF(vec3 t){ return mix(pow(t, forward), 7.787037 * t + 0.139731, step(t, epsilon)); }\n" + "float xyzR(float t){ return mix(t*t*t , 0.1284185 * (t - 0.139731), step(t, 0.20689655)); }\n" + "vec3 rgb2lab(vec3 c)\n" + "{\n" + " c *= mat3(0.4124, 0.3576, 0.1805,\n" + " 0.2126, 0.7152, 0.0722,\n" + " 0.0193, 0.1192, 0.9505);\n" + " c = xyzF(c);\n" + " vec3 lab = vec3(max(0.,1.16*c.y - 0.16), (c.x - c.y) * 5.0, (c.y - c.z) * 2.0); \n" + " return lab;\n" + // " return vec3(lab.x, length(vec2(lab.y,lab.z)), atan(lab.z, lab.y));\n" + "}\n" + "vec3 lab2rgb(vec3 c)\n" + "{\n" + // " c = vec3(c.x, cos(c.z) * c.y, sin(c.z) * c.y);\n" + " float lg = 1./1.16*(c.x + 0.16);\n" + " vec3 xyz = vec3(xyzR(lg + c.y * 0.2),\n" + " xyzR(lg),\n" + " xyzR(lg - c.z * 0.5));\n" + " vec3 rgb = xyz*mat3( 3.2406, -1.5372,-0.4986,\n" + " -0.9689, 1.8758, 0.0415,\n" + " 0.0557, -0.2040, 1.0570);\n" + " return rgb;\n" + "}\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec3 lab = rgb2lab(linear(tgt.rgb));\n" + " lab.x = lab.x + v_color.r - 0.5372549;\n" + " lab.yz = lab.yz + (v_color.gb - 0.5) * 2.0;\n" + " gl_FragColor = vec4(sRGB(clamp(lab2rgb(lab), 0.0, 1.0)), v_color.a * tgt.a);\n" + "}"; /** * Makes the colors in the given textures almost-grayscale, then moves their chromatic channels much closer to the * batch color, without changing the lightness. The result is almost all the same hue as the batch color, and can be * gray if the batch color is any grayscale color. This uses an RGB batch color for simpler usage in most code that * doesn't already use colorful-gdx. There is some contribution from the original texture, so even if the batch * color is gray, then the result will probably have some very muted colors. I hope this shader is... bearable. *
* You can generate RGB colors using any of various methods in the {@code rgb} package, such as * {@link com.github.tommyettinger.colorful.rgb.ColorTools#rgb(float, float, float, float)}. *
* Meant for use with {@link #vertexShader}. */ public static String fragmentShaderColorize = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "const vec3 forward = vec3(1.0 / 3.0);\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec3 base = mat3(+0.2104542553, +1.9779984951, +0.0259040371, +0.7936177850, -2.4285922050, +0.7827717662, -0.0040720468, +0.4505937099, -0.8086757660) *" + " pow(mat3(0.4121656120, 0.2118591070, 0.0883097947, 0.5362752080, 0.6807189584, 0.2818474174, 0.0514575653, 0.1074065790, 0.6302613616) \n" + " * (tgt.rgb * tgt.rgb), forward);\n" + " vec3 tint = mat3(+0.2104542553, +1.9779984951, +0.0259040371, +0.7936177850, -2.4285922050, +0.7827717662, -0.0040720468, +0.4505937099, -0.8086757660) *" + " pow(mat3(0.4121656120, 0.2118591070, 0.0883097947, 0.5362752080, 0.6807189584, 0.2818474174, 0.0514575653, 0.1074065790, 0.6302613616) \n" + " * (v_color.rgb * v_color.rgb), forward);\n" + " tint.x = clamp(base.x, 0.0, 1.0);\n" + " float blen = length(base.yz);\n" + " blen *= blen;\n" + " tint.yz = clamp(tint.yz * (0.7 + blen) + base.yz * (0.3 - blen), -1.0, 1.0);\n" + // change 0.7 and 0.3 to, say, 0.85 and 0.15 to reduce the original image's contribution " tint = mat3(1.0, 1.0, 1.0, +0.3963377774, -0.1055613458, -0.0894841775, +0.2158037573, -0.0638541728, -1.2914855480) * tint;\n" + " gl_FragColor = vec4(sqrt(clamp(" + " mat3(+4.0767245293, -1.2681437731, -0.0041119885, -3.3072168827, +2.6093323231, -0.7034763098, +0.2307590544, -0.3411344290, +1.7068625689) *\n" + " (tint * tint * tint)," + " 0.0, 1.0)), v_color.a * tgt.a);\n" + "}"; /** * Makes the colors in the given textures almost-grayscale, then moves their chromatic channels much closer to the * batch color's chromatic channels, without changing the lightness. The result is almost all the same hue as the * batch color, and can be gray if the batch color is any grayscale color. The lightness of the batch color is used * to determine how strong the effect should be; you may want to use an out-of-gamut color for very strong tint * effects, because those need to be light and the lightest gamut is just one point. This uses an Oklab batch color. * There is some contribution from the original texture, varied based on the batch lightness, so even if the batch * color is gray, then the result will probably have some very muted colors. *
* You can generate Oklab colors using any of various methods in the {@code oklab} package, such as * {@link com.github.tommyettinger.colorful.oklab.ColorTools#oklab(float, float, float, float)}. *
* Meant for use with {@link #vertexShader}. */ public static String fragmentShaderColorizeOklab = "#ifdef GL_ES\n" + "#define LOWP lowp\n" + "precision mediump float;\n" + "#else\n" + "#define LOWP \n" + "#endif\n" + "varying vec2 v_texCoords;\n" + "varying LOWP vec4 v_color;\n" + "uniform sampler2D u_texture;\n" + "const vec3 forward = vec3(1.0 / 3.0);\n" + "void main()\n" + "{\n" + " vec4 tgt = texture2D( u_texture, v_texCoords );\n" + " vec3 base = mat3(+0.2104542553, +1.9779984951, +0.0259040371, +0.7936177850, -2.4285922050, +0.7827717662, -0.0040720468, +0.4505937099, -0.8086757660) *" + " pow(mat3(0.4121656120, 0.2118591070, 0.0883097947, 0.5362752080, 0.6807189584, 0.2818474174, 0.0514575653, 0.1074065790, 0.6302613616) \n" + " * (tgt.rgb * tgt.rgb), forward);\n" + " vec2 tint = v_color.gb - 0.5;\n" + " base.x = clamp(base.x, 0.0, 1.0);\n" + " float blen = length(base.yz);\n" + " blen *= blen;\n" + " base.gb = clamp(tint * (v_color.r + blen) + base.yz * (1.0 - v_color.r - blen), -1.0, 1.0);\n" + " base = mat3(1.0, 1.0, 1.0, +0.3963377774, -0.1055613458, -0.0894841775, +0.2158037573, -0.0638541728, -1.2914855480) * base;\n" + " gl_FragColor = vec4(sqrt(clamp(" + " mat3(+4.0767245293, -1.2681437731, -0.0041119885, -3.3072168827, +2.6093323231, -0.7034763098, +0.2307590544, -0.3411344290, +1.7068625689) *\n" + " (base * base * base)," + " 0.0, 1.0)), v_color.a * tgt.a);\n" + "}"; } 1-10 package ulcambridge.foundations.viewer; import java.util.LinkedHashMap; import java.util.Map; import ulcambridge.foundations.viewer.model.Item; /** * This is a very simple cache that stores the last CAPACITY items * requested and allows quick access to them. * * @author jennie * */ public class ItemCache extends LinkedHashMap { private static final long serialVersionUID = 1447337912579613915L; private int CAPACITY; public ItemCache(int capacity) { super(capacity + 1, 1.1f, true); // load factor is 1.1 so should not ever rehash. this.CAPACITY = capacity; } @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > CAPACITY; } } hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderSearchModifierDstu3Test.java package ca.uhn.fhir.jpa.provider.dstu3; import ca.uhn.fhir.jpa.api.model.DaoMethodOutcome; import ca.uhn.fhir.jpa.searchparam.MatchUrlService; import ca.uhn.fhir.jpa.searchparam.ResourceSearch; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.rest.api.server.IBundleProvider; import org.hl7.fhir.dstu3.model.BodySite; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; import org.hl7.fhir.dstu3.model.Encounter; import org.hl7.fhir.dstu3.model.Observation; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.dstu3.model.Procedure; import org.hl7.fhir.dstu3.model.Reference; import org.hl7.fhir.dstu3.model.SearchParameter; import org.hl7.fhir.instance.model.api.IIdType; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Collections; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class ResourceProviderSearchModifierDstu3Test extends BaseResourceProviderDstu3Test{ @Autowired MatchUrlService myMatchUrlService; @Test public void testReplicateBugWithNotDuringChain() { Encounter enc = new Encounter(); enc.setType(Collections.singletonList(new CodeableConcept().addCoding(new Coding("system", "value", "display")))); IIdType encId = myEncounterDao.create(enc).getId(); Observation obs = new Observation(); obs.setContext(new Reference(encId)); myObservationDao.create(obs).getId(); { //Works when not chained: String encounterSearchString = "Encounter?type:not=system|value"; ResourceSearch resourceSearch = myMatchUrlService.getResourceSearch(encounterSearchString); SearchParameterMap searchParameterMap = resourceSearch.getSearchParameterMap(); IBundleProvider search = myEncounterDao.search(searchParameterMap); assertThat(search.size(), is(equalTo(0))); } { //Works without the NOT qualifier. String resultSearchString = "Observation?context.type=system|value"; ResourceSearch resourceSearch = myMatchUrlService.getResourceSearch(resultSearchString); SearchParameterMap searchParameterMap = resourceSearch.getSearchParameterMap(); IBundleProvider search = myObservationDao.search(searchParameterMap); assertThat(search.size(), is(equalTo(1))); } { //Works in a chain String noResultSearchString = "Observation?context.type:not=system|value"; ResourceSearch resourceSearch = myMatchUrlService.getResourceSearch(noResultSearchString); SearchParameterMap searchParameterMap = resourceSearch.getSearchParameterMap(); IBundleProvider search = myObservationDao.search(searchParameterMap); assertThat(search.size(), is(equalTo(0))); } { //Works in a chain with only value String noResultSearchString = "Observation?context.type:not=value"; ResourceSearch resourceSearch = myMatchUrlService.getResourceSearch(noResultSearchString); SearchParameterMap searchParameterMap = resourceSearch.getSearchParameterMap(); IBundleProvider search = myObservationDao.search(searchParameterMap); assertThat(search.size(), is(equalTo(0))); } } } drive-cloud-modules/drive-cloud-admin/drive-cloud-admin-service/src/main/java/com/drive/admin/mapper/OperatorAreaMapper.java0 package com.drive.admin.mapper; import com.drive.admin.pojo.entity.OperatorAreaEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * 运营商代理区域 Mapper 接口 * * @author xiaoguo */ public interface OperatorAreaMapper extends BaseMapper { } 0 package com.dapo.common.jpa.repository; import com.dapo.common.jpa.model.District; import com.dapo.common.jpa.model.Municipality; import org.springframework.data.repository.PagingAndSortingRepository; /** * Created by dimomass on 19.12.18. */ public interface MunicipalityRepository extends PagingAndSortingRepository{ } package roma.romaway.commons.android.h5download; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import com.romaway.android.phone.config.Configs; import com.romaway.common.android.base.data.SharedPreferenceUtils; import com.romaway.commons.android.fileutil.FileSystem; /** * * @Description:获取H5模块信息 * @author lichuan * @date 2015年8月13日 上午11:02:51 * @version */ public class H5Info { /*public static H5Info singletion = new H5Info(); private H5Info() { } public static H5Info getInstance() { return singletion; }*/ /** * * @date 2015年8月13日 上午11:41:28 * @version * @Description: 取得正在使用中的H5模块 * @author lichuan * @param @return * @return String */ public static String getCurrVersion(Context context){ String version = ""; //如果是引用内置h5地址,就取内置h5的版本号 if(Configs.jiaoyiURL.contains("file:///android_asset")) { version = getAssetsCurrVersion(context); } else { //取下发更新的h5版本号 version = SharedPreferenceUtils.getPreference(SharedPreferenceUtils.DATA_CONFIG,"JIAO_YI_UPDATE_VERSION", ""); } return version; } /** * * @date 2015年8月13日 下午1:11:25 * @version * @Description:内置H5模块的版本号 * @author lichuan * @param @return * @return String */ public static String getAssetsCurrVersion(Context context){ String version = ""; String json = FileSystem.getFromAssets(context, "kds519/config.txt"); if(json != null) { try { JSONObject object = new JSONObject(json); version = object.optString("version"); } catch (JSONException e) { e.printStackTrace(); } } return version; } } package com.ranveeraggarwal.letrack.models; import java.io.Serializable; public class Person implements Serializable { private long id; private String name; private int frequency; private int leaves; private int startDate; private String description; public Person() { } public Person(String name, int frequency, String description, int startDate) { this.setName(name); this.setFrequency(frequency); this.setDescription(description); this.setLeaves(0); this.setStartDate(startDate); } public Person(long id, String name, int frequency, String description, int leaves, int startDate) { this.setId(id); this.setName(name); this.setFrequency(frequency); this.setDescription(description); this.setLeaves(leaves); this.setStartDate(startDate); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getFrequency() { return frequency; } public void setFrequency(int frequency) { this.frequency = frequency; } public int getLeaves() { return leaves; } public void setLeaves(int leaves) { this.leaves = leaves; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getStartDate() { return startDate; } public void setStartDate(int startDate) { this.startDate = startDate; } public long getId() { return id; } public void setId(long id) { this.id = id; } } 0 package com.phoenix.eteacher.reco; import com.phoenix.eteacher.controller.CandidateBarController; import com.phoenix.eteacher.controller.ToolbarController; import com.phoenix.eteacher.view.CustomEditText; import com.visionobjects.textwidget.TextWidget; import com.visionobjects.textwidget.TextWidgetApi; import android.text.Editable; import android.util.Log; public class EditionBehavior implements TextWidgetApi.OnTextChangedListener, TextWidgetApi.OnSelectionChangedListener, ToolbarController.OnSpaceButtonClickedListener, ToolbarController.OnDeleteButtonClickedListener, CandidateBarController.OnCandidateButtonClickedListener, CustomEditText.OnCursorIndexChangedListener { private static final String TAG = "CursiveBehavior"; private CustomEditText mEditText; private CandidateBarController mCandidateBarController; private TextWidget mWidget; public EditionBehavior(TextWidget widget, CustomEditText editText, CandidateBarController candidatebarController) { mWidget = widget; mEditText = editText; mCandidateBarController = candidatebarController; } // ---------------------------------------------------------------------- // Toolbar controller interface public void onSpaceButtonClicked() { Log.d(TAG, "Space button clicked"); final int start = mEditText.getSelectionStart(); final int end = mEditText.getSelectionEnd(); mWidget.replaceCharacters(start, end, " "); mEditText.setCursorIndex(start + 1); } public void onDeleteButtonClicked() { Log.d(TAG, "Delete button clicked"); final int start = mEditText.getSelectionStart(); final int end = mEditText.getSelectionEnd(); if (start != end) { mWidget.replaceCharacters(start, end, null); } else if (start != 0) { mWidget.replaceCharacters(start - 1, start, null); mEditText.setCursorIndex(start - 1); } } // ---------------------------------------------------------------------- // Candidate bar controller interface public void onCandidateButtonClicked(final int start, final int end, final String label) { Log.d(TAG, "Candidate label \"" + label + "\" clicked"); mWidget.replaceCharacters(start, end, label); } // ---------------------------------------------------------------------- // Custom EditText interface public void onCursorIndexChanged(final int index) { Log.d(TAG, "Cursor index changed to " + index + " from input field"); if (!mWidget.isCursorHandleDragging()) { if (mWidget.isInsertionMode()) { // switch to correction mode if the cursor is moved to a // position different from the current insert index if (index != mWidget.getInsertIndex()) { mWidget.setCorrectionMode(); } } else { // switch to insertion mode if the cursor is moved to the // end of the text final Editable editable = mEditText.getText(); if((editable != null ) && (index == editable.length())) { mWidget.setInsertionMode(index); } } } // update cursor index // this may trigger an onSelectionChanged() event mWidget.setCursorIndex(index); // scroll to cursor if widget is in correction mode if (!mWidget.isInsertionMode()) { mWidget.scrollToCursor(); } } // ---------------------------------------------------------------------- // Text management public void onTextChanged(final String text, final boolean intermediate) { Log.d(TAG, "Text changed to \"" + text.replace('\n', '\u00B6') + "\" " + (intermediate ? "(intermediate)" : "(stable)")); // get the text currently stored in the target field String previousText = ""; final Editable editable = mEditText.getText(); if(editable != null) previousText = editable.toString(); // temporarily disable selection changed listener // because setText() automatically places the cursor at the beginning // of the text mEditText.setOnCursorIndexChangedListener(null); mEditText.setTextKeepState(text); mEditText.setOnCursorIndexChangedListener(this); if (mWidget.isInsertionMode()) { // widget is in insertion mode // put cursor at current widget insert index mEditText.setCursorIndex(mWidget.getInsertIndex()); } else { // widget is in correction mode // auto-switch to insertion mode if user appended text or text is empty if (text.length() == 0 || text.length() > previousText.length() && text.startsWith(previousText)) { mWidget.setInsertionMode(text.length()); } } } // ---------------------------------------------------------------------- // Text selection public void onSelectionChanged(final int start, final int end, final String[] labels, final int selectedIndex) { Log.d(TAG, "Selection changed range " + start + "-" + end); if (labels != null) { for (int i=0; iYtaoStudio/kvEngine package com.alibabacloud.polar_race.engine.common.impl; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class ValueLog { /*映射的fileChannel对象*/ private FileChannel fileChannel; private RandomAccessFile randomAccessFile; // private ByteBuffer directWriteBuffer; // private File file; public ValueLog(String storePath, int filename) { /*打开文件*/ try { File file = new File(storePath, "v" + filename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { System.out.println("Create file" + "valueLog" + filename + "failed"); e.printStackTrace(); } } this.randomAccessFile = new RandomAccessFile(file, "rw"); this.fileChannel = this.randomAccessFile.getChannel(); } catch (FileNotFoundException e) { System.out.println("create file channel " + "valueLog" + " Failed. "); } // this.directWriteBuffer = ByteBuffer.allocateDirect(4096); } public long getFileLength() { try { return this.randomAccessFile.length(); } catch (IOException e) { e.printStackTrace(); } return -1; } public void putMessageDirect(byte[] value) { // this.directWriteBuffer.clear(); // this.directWriteBuffer.put(value); // this.directWriteBuffer.flip(); // try { // this.fileChannel.write(this.directWriteBuffer); // } catch (IOException e){ // e.printStackTrace(); // } } public void putMessageDirect(ByteBuffer buffer) { try { this.fileChannel.write(buffer); } catch (IOException e) { e.printStackTrace(); } } public void putMessageDirect(ByteBuffer buffer, long offset) { try { this.fileChannel.write(buffer, offset); } catch (IOException e) { e.printStackTrace(); } } public long getWrotePosition() { try { return this.fileChannel.position(); } catch (IOException e) { e.printStackTrace(); } return -1; } void setWrotePosition(long wrotePosition) { try { this.fileChannel.position(wrotePosition); } catch (IOException e) { e.printStackTrace(); } } public byte[] getMessageDirect(long offset, ByteBuffer byteBuffer, byte[] bytes) { byteBuffer.clear(); try { fileChannel.read(byteBuffer, offset); } catch (IOException e) { e.printStackTrace(); } byteBuffer.flip(); byteBuffer.get(bytes); return bytes; } public void close() { // directWriteBuffer = null; try { this.fileChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } /* * Copyright 2017-2020, Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.testsuite.oauth; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.strimzi.kafka.oauth.client.ClientConfig; import io.strimzi.kafka.oauth.common.ConfigProperties; import io.strimzi.kafka.oauth.common.HttpUtil; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.errors.TopicAuthorizationException; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.jboss.arquillian.junit.Arquillian; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.net.URI; import java.time.Duration; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import java.util.concurrent.ExecutionException; import static io.strimzi.kafka.oauth.common.OAuthAuthenticator.loginWithClientSecret; import static io.strimzi.kafka.oauth.common.OAuthAuthenticator.urlencode; @RunWith(Arquillian.class) public class KeycloakClientCredentialsWithJwtValidationAuthzTest { private static final String HOST = "keycloak"; private static final String REALM = "kafka-authz"; private static final String TOKEN_ENDPOINT_URI = "http://" + HOST + ":8080/auth/realms/" + REALM + "/protocol/openid-connect/token"; private static final String TEAM_A_CLIENT = "team-a-client"; private static final String TEAM_B_CLIENT = "team-b-client"; private static final String BOB = "bob"; private static final String TOPIC_A = "a_messages"; private static final String TOPIC_B = "b_messages"; private static final String TOPIC_X = "x_messages"; private HashMap tokens; private Producer teamAProducer; private Consumer teamAConsumer; private Producer teamBProducer; private Consumer teamBConsumer; @Test public void doTest() throws Exception { System.out.println("==== KeycloakClientCredentialsWithJwtValidationAuthzTest - Tests Authorization ===="); Properties defaults = new Properties(); defaults.setProperty(ClientConfig.OAUTH_TOKEN_ENDPOINT_URI, TOKEN_ENDPOINT_URI); defaults.setProperty(ClientConfig.OAUTH_USERNAME_CLAIM, "preferred_username"); ConfigProperties.resolveAndExportToSystemProperties(defaults); Properties p = System.getProperties(); for (Object key: p.keySet()) { System.out.println("" + key + "=" + p.get(key)); } fixBadlyImportedAuthzSettings(); tokens = authenticateAllActors(); testTeamAClientPart1(); testTeamBClientPart1(); createTopicAsClusterManager(); testTeamAClientPart2(); testTeamBClientPart2(); testClusterManager(); } Producer getProducer(final String name) { return recycleProducer(name, true); } Producer newProducer(final String name) { return recycleProducer(name, false); } Producer recycleProducer(final String name, boolean recycle) { switch (name) { case TEAM_A_CLIENT: if (teamAProducer != null) { if (recycle) { return teamAProducer; } else { teamAProducer.close(); } } break; case TEAM_B_CLIENT: if (teamBProducer != null) { if (recycle) { return teamBProducer; } else { teamBProducer.close(); } } break; default: throw new IllegalArgumentException("Unsupported producer: " + name); } Properties producerProps = buildProducerConfig(tokens.get(name)); Producer producer = new KafkaProducer<>(producerProps); if (TEAM_A_CLIENT.equals(name)) { teamAProducer = producer; } else { teamBProducer = producer; } return producer; } Consumer newConsumer(final String name, String topic) { switch (name) { case TEAM_A_CLIENT: if (teamAConsumer != null) { teamAConsumer.close(); } break; case TEAM_B_CLIENT: if (teamBConsumer != null) { teamBConsumer.close(); } break; default: throw new IllegalArgumentException("Unsupported consumer: " + name); } Properties consumerProps = buildConsumerConfig(tokens.get(name)); consumerProps.setProperty(ConsumerConfig.GROUP_ID_CONFIG, groupFor(topic)); Consumer consumer = new KafkaConsumer<>(consumerProps); if (TEAM_A_CLIENT.equals(name)) { teamAConsumer = consumer; } else { teamBConsumer = consumer; } return consumer; } void createTopicAsClusterManager() throws Exception { Properties bobAdminProps = buildAdminClientConfig(tokens.get(BOB)); AdminClient admin = AdminClient.create(bobAdminProps); // // Create x_* topic // admin.createTopics(Arrays.asList(new NewTopic[]{ new NewTopic(TOPIC_X, 1, (short) 1) })).all().get(); } private void testClusterManager() throws Exception { Properties bobAdminProps = buildProducerConfig(tokens.get(BOB)); Producer producer = new KafkaProducer<>(bobAdminProps); Properties consumerProps = buildConsumerConfig(tokens.get(BOB)); Consumer consumer = new KafkaConsumer<>(consumerProps); // // bob should succeed producing to x_* topic // produce(producer, TOPIC_X); // // bob should succeed producing to a_* topic // produce(producer, TOPIC_A); // // bob should succeed producing to b_* topic // produce(producer, TOPIC_B); // // bob should succeed producing to non-existing topic // produce(producer, "non-existing-topic"); // // bob should succeed consuming from x_* topic // consume(consumer, TOPIC_X); // // bob should succeed consuming from a_* topic // consume(consumer, TOPIC_A); // // bob should succeed consuming from b_* topic // consume(consumer, TOPIC_B); // // bob should succeed consuming from "non-existing-topic" - which now exists // consume(consumer, "non-existing-topic"); } private void testTeamAClientPart1() throws Exception { Producer teamAProducer = getProducer(TEAM_A_CLIENT); // // team-a-client should fail to produce to b_* topic // produceFail(teamAProducer, TOPIC_B); // Re-init producer because message to topicB is stuck in the queue, and any subsequent message to another queue // won't be handled until first message makes it through. teamAProducer = newProducer(TEAM_A_CLIENT); // // team-a-client should succeed producing to a_* topic // produce(teamAProducer, TOPIC_A); // // team-a-client should also fail producing to non-existing x_* topic (fails to create it) // produceFail(teamAProducer, TOPIC_X); Consumer teamAConsumer = newConsumer(TEAM_A_CLIENT, TOPIC_B); // // team-a-client should fail consuming from b_* topic // consumeFail(teamAConsumer, TOPIC_B); // Close and re-init consumer teamAConsumer = newConsumer(TEAM_A_CLIENT, TOPIC_A); // // team-a-client should succeed consuming from a_* topic // consume(teamAConsumer, TOPIC_A); // // team-a-client should fail consuming from x_* topic - it doesn't exist // consumeFail(teamAConsumer, TOPIC_X); } private void testTeamBClientPart1() throws Exception { Producer teamBProducer = getProducer(TEAM_B_CLIENT); // // team-b-client should fail to produce to a_* topic // produceFail(teamBProducer, TOPIC_A); // Re-init producer because message to topicA is stuck in the queue, and any subsequent message to another queue // won't be handled until first message makes it through. teamBProducer = newProducer(TEAM_B_CLIENT); // // team-b-client should succeed producing to b_* topic // produce(teamBProducer, TOPIC_B); // // team-b-client should fail to produce to x_* topic // produceFail(teamBProducer, TOPIC_X); Consumer teamBConsumer = newConsumer(TEAM_B_CLIENT, TOPIC_A); // // team-b-client should fail consuming from a_* topic // consumeFail(teamBConsumer, TOPIC_A); // Close and re-init consumer teamBConsumer = newConsumer(TEAM_B_CLIENT, TOPIC_B); // // team-b-client should succeed consuming from b_* topic // consume(teamBConsumer, TOPIC_B); } private void testTeamAClientPart2() throws Exception { // // team-a-client should succeed producing to existing x_* topic // Producer teamAProducer = newProducer(TEAM_A_CLIENT); produce(teamAProducer, TOPIC_X); // // team-a-client should fail reading from x_* topic // Consumer teamAConsumer = newConsumer(TEAM_A_CLIENT, TOPIC_A); consumeFail(teamAConsumer, TOPIC_X); } private void testTeamBClientPart2() throws Exception { // // team-b-client should succeed consuming from x_* topic // Consumer teamBConsumer = newConsumer(TEAM_B_CLIENT, TOPIC_B); consume(teamBConsumer, TOPIC_X); // // team-b-client should fail producing to x_* topic // Producer teamBProducer = newProducer(TEAM_B_CLIENT); produceFail(teamBProducer, TOPIC_X); } /** * Use Keycloak Admin API to update Authorization Services 'decisionStrategy' on 'kafka' client to AFFIRMATIVE * * @throws IOException */ static void fixBadlyImportedAuthzSettings() throws IOException { URI masterTokenEndpoint = URI.create("http://" + HOST + ":8080/auth/realms/master/protocol/openid-connect/token"); String token = loginWithUsernamePassword(masterTokenEndpoint, "", "admin", "admin-"); String authorization = "Bearer " + token; // This is quite a round-about way but here it goes // We first need to identify the 'id' of the 'kafka' client by fetching the clients JsonNode clients = HttpUtil.get(URI.create("http://" + HOST + ":8080/auth/admin/realms/kafka-authz/clients"), authorization, JsonNode.class); String id = null; // iterate over clients Iterator it = clients.iterator(); while (it.hasNext()) { JsonNode client = it.next(); String clientId = client.get("clientId").asText(); if ("kafka".equals(clientId)) { id = client.get("id").asText(); break; } } if (id == null) { throw new IllegalStateException("It seems that 'kafka' client isn't configured"); } URI authzUri = URI.create("http://" + HOST + ":8080/auth/admin/realms/kafka-authz/clients/" + id + "/authz/resource-server"); // Now we fetch from this client's resource-server the current configuration ObjectNode authzConf = (ObjectNode) HttpUtil.get(authzUri, authorization, JsonNode.class); // And we update the configuration and send it back authzConf.put("decisionStrategy", "AFFIRMATIVE"); HttpUtil.put(authzUri, authorization, "application/json", authzConf.toString()); } static String groupFor(String topic) { return topic + "-group"; } static HashMap authenticateAllActors() throws IOException { HashMap tokens = new HashMap<>(); tokens.put(TEAM_A_CLIENT, loginWithClientSecret(URI.create(TOKEN_ENDPOINT_URI), null, null, TEAM_A_CLIENT, TEAM_A_CLIENT + "-secret", true, null, null).token()); tokens.put(TEAM_B_CLIENT, loginWithClientSecret(URI.create(TOKEN_ENDPOINT_URI), null, null, TEAM_B_CLIENT, TEAM_B_CLIENT + "-secret", true, null, null).token()); tokens.put(BOB, loginWithUsernamePassword(URI.create(TOKEN_ENDPOINT_URI), BOB, BOB + "-password", "")); return tokens; } static void consume(Consumer consumer, String topic) { TopicPartition partition = new TopicPartition(topic, 0); consumer.assign(Arrays.asList(partition)); while (consumer.partitionsFor(topic, Duration.ofSeconds(1)).size() == 0) { System.out.println("No assignment yet for consumer"); } consumer.seekToBeginning(Arrays.asList(partition)); ConsumerRecords records = consumer.poll(Duration.ofSeconds(10)); Assert.assertTrue("Got message", records.count() >= 1); } static void consumeFail(Consumer consumer, String topic) { TopicPartition partition = new TopicPartition(topic, 0); consumer.assign(Arrays.asList(partition)); try { while (consumer.partitionsFor(topic, Duration.ofSeconds(1)).size() == 0) { System.out.println("No assignment yet for consumer"); } consumer.seekToBeginning(Arrays.asList(partition)); consumer.poll(Duration.ofSeconds(1)); Assert.fail("Should fail with TopicAuthorizationException"); } catch (TopicAuthorizationException e) { } } static void produce(Producer producer, String topic) throws Exception { producer.send(new ProducerRecord<>(topic, "The Message")).get(); } static void produceFail(Producer producer, String topic) throws Exception { try { produce(producer, topic); Assert.fail("Should not be able to send message"); } catch (ExecutionException e) { // should get authorization exception Assert.assertTrue("Should fail with TopicAuthorizationException", e.getCause() instanceof TopicAuthorizationException); } } static Properties buildProducerConfig(String accessToken) { Properties p = new Properties(); p.setProperty("security.protocol", "SASL_PLAINTEXT"); p.setProperty("sasl.mechanism", "OAUTHBEARER"); p.setProperty("sasl.jaas.config", "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required " + " oauth.access.token=\"" + accessToken + "\";"); p.setProperty("sasl.login.callback.handler.class", "io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler"); p.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092"); p.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); p.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); p.setProperty(ProducerConfig.ACKS_CONFIG, "all"); return p; } static Properties buildAdminClientConfig(String accessToken) { return buildProducerConfig(accessToken); } static Properties buildConsumerConfig(String accessToken) { Properties p = new Properties(); p.setProperty("security.protocol", "SASL_PLAINTEXT"); p.setProperty("sasl.mechanism", "OAUTHBEARER"); p.setProperty("sasl.jaas.config", "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required " + " oauth.access.token=\"" + accessToken + "\";"); p.setProperty("sasl.login.callback.handler.class", "io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler"); p.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092"); p.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); p.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); p.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "consumer-group"); p.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "10"); p.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true"); return p; } static String loginWithUsernamePassword(URI tokenEndpointUri, String username, String password, String clientId) throws IOException { StringBuilder body = new StringBuilder("grant_type=password&username=" + urlencode(username) + "&password=" + urlencode(password) + "&client_id=" + urlencode(clientId)); JsonNode result = HttpUtil.post(tokenEndpointUri, null, null, null, "application/x-www-form-urlencoded", body.toString(), JsonNode.class); JsonNode token = result.get("access_token"); if (token == null) { throw new IllegalStateException("Invalid response from authorization server: no access_token"); } return token.asText(); } void cleanup() throws Exception { Properties bobAdminProps = buildAdminClientConfig(tokens.get(BOB)); AdminClient admin = AdminClient.create(bobAdminProps); admin.deleteTopics(Arrays.asList(TOPIC_A, TOPIC_B, TOPIC_X, "non-existing-topic")); admin.deleteConsumerGroups(Arrays.asList(groupFor(TOPIC_A), groupFor(TOPIC_B), groupFor(TOPIC_X), groupFor("non-existing-topic"))); } } catoyos/gens-st_0 package main_logic; import java.io.File; import java.util.List; import pattern_search.Pattern; import pattern_search.Result; import main_logic.io.InputOutput; import model.Arch; import model.City; import model.City.Direction; import model.Individual; import model.World; import model.Zone; import model.interfaces.IAIEngine; import model.utils.StringUtils; import data_storage.Storage; public class StoryUniverse { private static final String UNIVERSE_FILE = "universe.dat"; final String uniID; private World world; public StoryUniverse(IAIEngine aieng) { this(generateId(), aieng, "files"); } public StoryUniverse(IAIEngine aieng, String rootfolder) { this(generateId(), aieng, rootfolder); } public StoryUniverse(String uniID, IAIEngine aieng) { this(uniID, aieng, "files"); } public StoryUniverse(String uniID, IAIEngine aie, String rootfolder) { this.uniID = uniID; this.world = null; Arch.setAIEngine(aie); Storage.getInitiatedStorage(uniID, rootfolder); } private static String generateId(){ return StringUtils.generateId((int)(Math.random() * StringUtils.ID_N_25_3), 3); } public static StoryUniverse generateFromString(String fileContent, IAIEngine aieng, String rootfolder) { String[] lines = fileContent.split("\n"); StoryUniverse uni = null; try { String nuid = lines[0]; String cuid = null; uni = new StoryUniverse(nuid, aieng, rootfolder); if(lines.length > 2){ cuid = lines[2]; if (Arch.worldExists(cuid)) { uni.world = Arch.getWorldById(cuid); } } if(lines.length > 3){ String[] nids = lines[3].split(","); long[] lnids = {-1, -1, -1, -1}; for (int i = 0; i < lnids.length && i < nids.length; i++) { try { lnids[i] = Long.parseLong(nids[i]); } catch (NumberFormatException e) { lnids[i] = -1; e.printStackTrace(); } } Arch.setNewIDns(lnids); } } catch (Exception e) { e.printStackTrace(); } return uni; } public static File getUniverseFile(String id) { return new File(InputOutput.getDefaultFilePath(InputOutput.getDefaultFolderPath(id), UNIVERSE_FILE)); } public static File getUniverseFile(String id, String folder) { return new File(InputOutput.getDefaultFilePath(InputOutput.getDefaultFolderPath(folder, id), UNIVERSE_FILE)); } // public void printResults(Pattern pattern) { // long t0,t1; // System.out.println(world.getWorldID()); // List zones = world.getZones(); // for (Zone zone : zones) { // System.out.println(zone.getZoneID()); // List cities = zone.getCities(); // for (City city : cities) { // System.out.println(city.getCityID()); // t0 = System.currentTimeMillis(); // List> res = pattern.eval(city.getCitizenInd()); // t1 = System.currentTimeMillis(); // System.out.print("("+(t1-t0)+"ms.)"); // System.out.println("("+res.size()+"/"+city.getNCitizens()+" = "+100*(res.size()/(float)city.getNCitizens())+"%)"); // for (Result result : res) { // System.out.println(indiToString(result.getRes())); // } // } // } // } public void printResults(Pattern pattern) { long t0,t1; t0 = System.currentTimeMillis(); Result res = pattern.eval(world); t1 = System.currentTimeMillis(); System.out.print("("+(t1-t0)+"ms.)"); if (res.isPositive()) { System.out.println(worldToString(res.getRes())); } else { System.out.println("nope"); } } public static void worldToString(World w, StringBuilder sb){ sb.append("ID: ").append(w.getWorldID()); sb.append(", Parent universe: ").append(w.getParentUni()); sb.append(", Moment: ").append(w.getMoment()); sb.append(", Zones: ").append(w.getNZones()); if (w.getNZones()>0) { sb.append("\nZONES:"); List zones = w.getZones(); for (Zone zone : zones) { sb.append("\n"); zoneToString(zone, sb); } } } public static void zoneToString(Zone z, StringBuilder sb){ sb.append("\tID: ").append(z.getZoneID()); sb.append(", Parent world: ").append(z.getParentWorldID()); sb.append(", Last updated: ").append(z.getLastUpdated()); sb.append(", Cities: ").append(z.getNCities()); sb.append(", Citizens: ").append(z.getNCitizens()); if (z.getNCities() > 0) { sb.append("\n\tCITIES:"); List cities = z.getCities(); for (City city : cities) { sb.append("\n"); cityToString(city, sb); } } } public static void cityToString(City c, StringBuilder sb){ sb.append("\t\tID: ").append(c.getCityID()); sb.append(", Parent zone: ").append(c.getParentZoneID()); sb.append(", Adjacent cities: ["); sb.append(" NORTH=").append(c.getAdjacentCityID(Direction.NORTH)); sb.append(" EAST=").append(c.getAdjacentCityID(Direction.EAST)); sb.append(" SOUTH=").append(c.getAdjacentCityID(Direction.SOUTH)); sb.append(" WEST=").append(c.getAdjacentCityID(Direction.WEST)); sb.append(" ]"); sb.append(", Citizens: ").append(c.getNCitizens()); if (c.getNCitizens() > 0) { sb.append("\n\t\tCITIZENS:"); List citizens = c.getCitizenInd(); for (Individual indi : citizens) { sb.append("\n"); indiToString(indi, sb); } } } public static void indiToString(Individual i, StringBuilder sb){ sb.append("\t\t\tID: ").append(i.getIndividualID()); short[] car = i.getCharactValues(); String[] carstr = {"str", "con", "spe", "int", "wis", "cha", "bea", "fer", "hor", "com" }; for (int j = 0; j < carstr.length; j++) { sb.append(",").append(carstr[j]).append(":").append(car[j]); } } public static String worldToString(World w){ StringBuilder sb = new StringBuilder(); worldToString(w, sb); return sb.toString(); } public static String zoneToString(Zone z){ StringBuilder sb = new StringBuilder(); zoneToString(z, sb); return sb.toString(); } public static String cityToString(City c){ StringBuilder sb = new StringBuilder(); cityToString(c, sb); return sb.toString(); } public static String indiToString(Individual i){ StringBuilder sb = new StringBuilder(); indiToString(i, sb); return sb.toString(); } public World getWorld() { return world; } public void setWorld(World world) { this.world = world; } public String getUniID() { return uniID; } @Override public String toString() { return "StoryUniverse [uniID=" + uniID + ", world=" + world + "]"; } } package com.ljl.study.test; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * @author alin * @version 2017年6月10日 * 类说明 */ public class SendUrl { /** * 不行啊,测试不通 */ public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:8080/task2/a/u/stu"); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setConnectTimeout(10*1000); // 单位是毫秒 urlConn.setRequestMethod("GET"); InputStream inStrm = urlConn.getInputStream(); // <=== 注意,实际发送请求的代码段就在这里,这句代码比 urlConn.connect() 好用,connect 压根不会发送请求出去,所以这句话一定要写 inStrm.close(); urlConn.disconnect(); } } binhbt/cattle-manager package com.leo.cattle.presentation.view.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.leo.cattle.presentation.R; import com.leo.cattle.presentation.model.CattleModel; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by leo on 4/1/2016. */ public class CattleAdapter extends RecyclerView.Adapter { public interface OnItemClickListener { void onUserItemClicked(CattleModel userModel); } private List usersCollection; private final LayoutInflater layoutInflater; private OnItemClickListener onItemClickListener; @Inject public CattleAdapter(Context context) { this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.usersCollection = Collections.emptyList(); } @Override public int getItemCount() { return (this.usersCollection != null) ? this.usersCollection.size() : 0; } @Override public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View view = this.layoutInflater.inflate(R.layout.item_cattle, parent, false); return new UserViewHolder(view); } @Override public void onBindViewHolder(UserViewHolder holder, final int position) { final CattleModel cattleModel = this.usersCollection.get(position); holder.textViewTitle.setText(cattleModel.getName()); holder.des.setText(cattleModel.getDesCription()); holder.weight.setText((float)(cattleModel.getWeight()/10) +"kg - "+cattleModel.getMonthOld()+"month"); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (CattleAdapter.this.onItemClickListener != null) { CattleAdapter.this.onItemClickListener.onUserItemClicked(cattleModel); } } }); } @Override public long getItemId(int position) { return position; } public void setUsersCollection(Collection usersCollection) { this.validateUsersCollection(usersCollection); this.usersCollection = (List) usersCollection; this.notifyDataSetChanged(); } public void setOnItemClickListener (OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } private void validateUsersCollection(Collection usersCollection) { if (usersCollection == null) { throw new IllegalArgumentException("The list cannot be null"); } } static class UserViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.avatar) ImageView avatar; @Bind(R.id.title) TextView textViewTitle; @Bind(R.id.des) TextView des; @Bind(R.id.weight) TextView weight; public UserViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } } 0 package br.com.sisvendatarde.domain; import javax.persistence.Column; import javax.persistence.Entity; @Entity public class Funcionario extends GenericDomain { @Column(length = 50, nullable = false) private String nome; @Column(length = 14, nullable = false) private String cpf; @Column(length = 20, nullable = false) private String senha; @Column(length = 30, nullable = false) private String funcao; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public String getFuncao() { return funcao; } public void setFuncao(String funcao) { this.funcao = funcao; } } /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.presto.flex; import static io.airlift.json.JsonCodec.jsonCodec; import static org.testng.Assert.assertEquals; import org.apache.presto.flex.FlexTableHandle; import org.testng.annotations.Test; import io.airlift.json.JsonCodec; import io.airlift.testing.EquivalenceTester; public class TestFlexTableHandle { private final FlexTableHandle tableHandle = new FlexTableHandle("connectorId", "schemaName", "tableName"); @Test public void testJsonRoundTrip() { JsonCodec codec = jsonCodec(FlexTableHandle.class); String json = codec.toJson(tableHandle); FlexTableHandle copy = codec.fromJson(json); assertEquals(copy, tableHandle); } @Test public void testEquivalence() { EquivalenceTester.equivalenceTester() .addEquivalentGroup(new FlexTableHandle("connector", "schema", "table"), new FlexTableHandle("connector", "schema", "table")) .addEquivalentGroup(new FlexTableHandle("connectorX", "schema", "table"), new FlexTableHandle("connectorX", "schema", "table")) .addEquivalentGroup(new FlexTableHandle("connector", "schemaX", "table"), new FlexTableHandle("connector", "schemaX", "table")) .addEquivalentGroup(new FlexTableHandle("connector", "schema", "tableX"), new FlexTableHandle("connector", "schema", "tableX")) .check(); } } package org.societies.platform.sns.connecor.linkedin; import java.io.BufferedWriter; import java.io.FileWriter; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; public class ConnectorTester { private static void writeToFile(String filename, String data){ try{ // Create file FileWriter fstream = new FileWriter(filename); BufferedWriter out = new BufferedWriter(fstream); out.write(data); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } /** * to get the token there is right now a cloud API in * http://wd.teamlife.it/fbconnector.php that allows to get the access token */ public static void main(String[] args) { String access_token = ""; LinkedinConnector connector = new LinkedinConnector(access_token, "Societies User"); try { //JSONObject json = new JSONObject(connector.getUserActivities()); //System.out.println("Friends:"+ friends.toString(1)); // make the json payload using json-simple // JSONObject jsonMap = new JSONObject(); // jsonMap.put("comment", "Posting from the API using JSON"); // // JSONObject contentObject = new JSONObject(); // contentObject.put("title", "A title for your share"); // contentObject.put("submitted-url","http://www.linkedin.com"); // contentObject.put("submitted-image-url", "http://lnkd.in/Vjc5ec"); // // jsonMap.put("content", contentObject); // // JSONObject visibilityObject = new JSONObject(); // visibilityObject.put("code", "anyone"); // // jsonMap.put("visibility", visibilityObject); // // // System.out.println(jsonMap.toString(2)); // connector.post(jsonMap.toString(2)); System.out.println("Friends:\n"+connector.getUserFriends()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* * Copyright 2016 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.service.plugins.processor.elasticagent; import com.thoughtworks.go.config.AgentConfig; import com.thoughtworks.go.domain.AgentConfigStatus; import com.thoughtworks.go.domain.AgentInstance; import com.thoughtworks.go.domain.AgentRuntimeStatus; import com.thoughtworks.go.plugin.access.elastic.models.AgentMetadata; import com.thoughtworks.go.plugin.access.elastic.ElasticAgentExtension; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.request.DefaultGoApiRequest; import com.thoughtworks.go.plugin.api.response.GoApiResponse; import com.thoughtworks.go.plugin.infra.PluginRequestProcessorRegistry; import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor; import com.thoughtworks.go.server.domain.ElasticAgentMetadata; import com.thoughtworks.go.server.service.AgentConfigService; import com.thoughtworks.go.server.service.AgentService; import org.junit.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.util.LinkedMultiValueMap; import java.util.Arrays; import static com.thoughtworks.go.plugin.access.elastic.ElasticAgentPluginConstants.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ElasticAgentRequestProcessorTest { private AgentService agentService = mock(AgentService.class); private AgentConfigService agentConfigService = mock(AgentConfigService.class); private ElasticAgentExtension extension = new ElasticAgentExtension(null); private ElasticAgentRequestProcessor processor = new ElasticAgentRequestProcessor(new PluginRequestProcessorRegistry(), agentService, agentConfigService, extension); private GoPluginDescriptor pluginDescriptor = new GoPluginDescriptor("docker", null, null, null, null, false); private GoPluginIdentifier pluginIdentifier = new GoPluginIdentifier(EXTENSION_NAME, SUPPORTED_VERSIONS); @Test public void shouldProcessListAgentRequest() throws Exception { LinkedMultiValueMap allAgents = new LinkedMultiValueMap<>(); ElasticAgentMetadata agent = new ElasticAgentMetadata("foo", "bar", "docker", AgentRuntimeStatus.Building, AgentConfigStatus.Disabled); allAgents.put("docker", Arrays.asList(agent)); when(agentService.allElasticAgents()).thenReturn(allAgents); GoApiResponse response = processor.process(pluginDescriptor, new DefaultGoApiRequest(REQUEST_SERVER_LIST_AGENTS, "1.0", pluginIdentifier)); JSONAssert.assertEquals("[{\"agent_id\":\"bar\",\"agent_state\":\"Building\",\"build_state\":\"Building\",\"config_state\":\"Disabled\"}]", response.responseBody(), true); } @Test public void shouldProcessDisableAgentRequest() throws Exception { AgentMetadata agent = new AgentMetadata("foo", null, null, null); DefaultGoApiRequest goPluginApiRequest = new DefaultGoApiRequest(PROCESS_DISABLE_AGENTS, "1.0", pluginIdentifier); goPluginApiRequest.setRequestBody(extension.getElasticAgentMessageConverter(goPluginApiRequest.apiVersion()).listAgentsResponseBody(Arrays.asList(agent))); AgentInstance agentInstance = AgentInstance.createFromConfig(new AgentConfig("uuid"), null); when(agentService.findElasticAgent("foo", "docker")).thenReturn(agentInstance); processor.process(pluginDescriptor, goPluginApiRequest); verify(agentConfigService).disableAgents(processor.usernameFor(pluginDescriptor), agentInstance); } @Test public void shouldProcessDeleteAgentRequest() throws Exception { AgentMetadata agent = new AgentMetadata("foo", null, null, null); DefaultGoApiRequest goPluginApiRequest = new DefaultGoApiRequest(PROCESS_DELETE_AGENTS, "1.0", pluginIdentifier); goPluginApiRequest.setRequestBody(extension.getElasticAgentMessageConverter(goPluginApiRequest.apiVersion()).listAgentsResponseBody(Arrays.asList(agent))); AgentInstance agentInstance = AgentInstance.createFromConfig(new AgentConfig("uuid"), null); when(agentService.findElasticAgent("foo", "docker")).thenReturn(agentInstance); processor.process(pluginDescriptor, goPluginApiRequest); verify(agentConfigService).deleteAgents(processor.usernameFor(pluginDescriptor), agentInstance); } } /** * Copyright (c) 1995 - 2019 Cycorp, Inc. All rights reserved. */ package com.cyc.cycjava.cycl; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.ConsesLow.list; import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.makeKeyword; import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.makeSymbol; import static com.cyc.tool.subl.util.SubLFiles.declareFunction; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLList; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObject; import com.cyc.tool.subl.jrtl.nativeCode.type.symbol.SubLSymbol; import com.cyc.tool.subl.util.SubLFile; import com.cyc.tool.subl.util.SubLFiles.LispMethod; import com.cyc.tool.subl.util.SubLTranslatedFile; /** * Copyright (c) 1995 - 2019 Cycorp, Inc. All rights reserved. * module: SUBLOOP-MARKABLE * source file: /cyc/top/cycl/subloop-markable.lisp * created: 2019/07/03 17:37:08 */ public final class subloop_markable extends SubLTranslatedFile implements V12 { public static final SubLFile me = new subloop_markable(); public static final String myName = "com.cyc.cycjava.cycl.subloop_markable"; // Internal Constants @LispMethod(comment = "Internal Constants") private static final SubLSymbol SUBLOOP_MARKABLE = makeSymbol("SUBLOOP-MARKABLE"); static private final SubLList $list1 = list(list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("CLEAR-ALL-MARKS"), NIL, makeKeyword("PUBLIC")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("ADD-MARK"), list(makeSymbol("MARK")), makeKeyword("PUBLIC")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("REMOVE-MARK"), list(makeSymbol("MARK")), makeKeyword("PUBLIC")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("HAS-MARK-P"), list(makeSymbol("MARK")), makeKeyword("PUBLIC"))); private static final SubLSymbol SUBLOOP_MARKABLE_TEMPLATE = makeSymbol("SUBLOOP-MARKABLE-TEMPLATE"); static private final SubLList $list3 = list(makeSymbol("SUBLOOP-MARKABLE")); static private final SubLList $list4 = list(makeKeyword("EXTENDS"), list(makeSymbol("SUBLOOP-MARKABLE"))); static private final SubLList $list5 = list(list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("GET-MARKS-INTERNAL"), NIL, makeKeyword("PROTECTED")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("SET-MARKS-INTERNAL"), list(makeSymbol("NEW-MARKS")), makeKeyword("PROTECTED")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("INITIALIZE-QUA-SUBLOOP-MARKABLE-TEMPLATE"), NIL, makeKeyword("PUBLIC"))); static private final SubLList $list7 = list(makeKeyword("PUBLIC")); static private final SubLList $list8 = list(list(makeSymbol("SET-MARKS-INTERNAL"), makeSymbol("SELF"), NIL), list(RET, NIL)); static private final SubLList $list10 = list(makeSymbol("MARK")); static private final SubLList $list11 = list(list(makeSymbol("CLET"), list(list(makeSymbol("LIST-OF-MARKS"), list(makeSymbol("GET-MARKS-INTERNAL"), makeSymbol("SELF")))), list(makeSymbol("PUNLESS"), list(makeSymbol("MEMBER"), makeSymbol("MARK"), makeSymbol("LIST-OF-MARKS")), list(makeSymbol("CPUSH"), makeSymbol("MARK"), makeSymbol("LIST-OF-MARKS")), list(makeSymbol("SET-MARKS-INTERNAL"), makeSymbol("SELF"), makeSymbol("LIST-OF-MARKS")))), list(RET, makeSymbol("MARK"))); static private final SubLList $list13 = list(list(makeSymbol("SET-MARKS-INTERNAL"), makeSymbol("SELF"), list(makeSymbol("DELETE"), makeSymbol("MARK"), list(makeSymbol("GET-MARKS-INTERNAL"), makeSymbol("SELF")))), list(RET, makeSymbol("MARK"))); static private final SubLList $list_alt1 = list(list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("CLEAR-ALL-MARKS"), NIL, makeKeyword("PUBLIC")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("ADD-MARK"), list(makeSymbol("MARK")), makeKeyword("PUBLIC")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("REMOVE-MARK"), list(makeSymbol("MARK")), makeKeyword("PUBLIC")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("HAS-MARK-P"), list(makeSymbol("MARK")), makeKeyword("PUBLIC"))); static private final SubLList $list15 = list(list(RET, list(makeSymbol("FIF"), list(makeSymbol("MEMBER"), makeSymbol("MARK"), list(makeSymbol("GET-MARKS-INTERNAL"), makeSymbol("SELF"))), T, NIL))); private static final SubLSymbol INITIALIZE_QUA_SUBLOOP_MARKABLE_TEMPLATE = makeSymbol("INITIALIZE-QUA-SUBLOOP-MARKABLE-TEMPLATE"); static private final SubLList $list17 = list(list(makeSymbol("SET-MARKS-INTERNAL"), makeSymbol("SELF"), NIL), list(RET, makeSymbol("SELF"))); static private final SubLList $list_alt3 = list(makeSymbol("SUBLOOP-MARKABLE")); static private final SubLList $list_alt4 = list(makeKeyword("EXTENDS"), list(makeSymbol("SUBLOOP-MARKABLE"))); // Definitions public static final SubLObject subloop_markable_p_alt(SubLObject v_subloop_markable) { return interfaces.subloop_instanceof_interface(v_subloop_markable, SUBLOOP_MARKABLE); } // Definitions public static SubLObject subloop_markable_p(final SubLObject v_subloop_markable) { return interfaces.subloop_instanceof_interface(v_subloop_markable, SUBLOOP_MARKABLE); } static private final SubLList $list_alt5 = list(list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("GET-MARKS-INTERNAL"), NIL, makeKeyword("PROTECTED")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("SET-MARKS-INTERNAL"), list(makeSymbol("NEW-MARKS")), makeKeyword("PROTECTED")), list(makeSymbol("DEF-INSTANCE-METHOD"), makeSymbol("INITIALIZE-QUA-SUBLOOP-MARKABLE-TEMPLATE"), NIL, makeKeyword("PUBLIC"))); public static final SubLObject subloop_markable_template_p_alt(SubLObject subloop_markable_template) { return interfaces.subloop_instanceof_interface(subloop_markable_template, SUBLOOP_MARKABLE_TEMPLATE); } public static SubLObject subloop_markable_template_p(final SubLObject subloop_markable_template) { return interfaces.subloop_instanceof_interface(subloop_markable_template, SUBLOOP_MARKABLE_TEMPLATE); } public static SubLObject declare_subloop_markable_file() { declareFunction("subloop_markable_p", "SUBLOOP-MARKABLE-P", 1, 0, false); declareFunction("subloop_markable_template_p", "SUBLOOP-MARKABLE-TEMPLATE-P", 1, 0, false); return NIL; } static private final SubLList $list_alt7 = list(makeKeyword("PUBLIC")); static private final SubLList $list_alt8 = list(list(makeSymbol("SET-MARKS-INTERNAL"), makeSymbol("SELF"), NIL), list(RET, NIL)); public static SubLObject init_subloop_markable_file() { return NIL; } static private final SubLList $list_alt10 = list(makeSymbol("MARK")); public static SubLObject setup_subloop_markable_file() { interfaces.new_interface(SUBLOOP_MARKABLE, NIL, NIL, $list1); interfaces.new_interface(SUBLOOP_MARKABLE_TEMPLATE, $list3, $list4, $list5); interfaces.interfaces_add_interface_instance_method(CLEAR_ALL_MARKS, SUBLOOP_MARKABLE_TEMPLATE, $list7, NIL, $list8); interfaces.interfaces_add_interface_instance_method(ADD_MARK, SUBLOOP_MARKABLE_TEMPLATE, $list7, $list10, $list11); interfaces.interfaces_add_interface_instance_method(REMOVE_MARK, SUBLOOP_MARKABLE_TEMPLATE, $list7, $list10, $list13); interfaces.interfaces_add_interface_instance_method(HAS_MARK_P, SUBLOOP_MARKABLE_TEMPLATE, $list7, $list10, $list15); interfaces.interfaces_add_interface_instance_method(INITIALIZE_QUA_SUBLOOP_MARKABLE_TEMPLATE, SUBLOOP_MARKABLE_TEMPLATE, $list7, NIL, $list17); return NIL; } static private final SubLList $list_alt11 = list(list(makeSymbol("CLET"), list(list(makeSymbol("LIST-OF-MARKS"), list(makeSymbol("GET-MARKS-INTERNAL"), makeSymbol("SELF")))), list(makeSymbol("PUNLESS"), list(makeSymbol("MEMBER"), makeSymbol("MARK"), makeSymbol("LIST-OF-MARKS")), list(makeSymbol("CPUSH"), makeSymbol("MARK"), makeSymbol("LIST-OF-MARKS")), list(makeSymbol("SET-MARKS-INTERNAL"), makeSymbol("SELF"), makeSymbol("LIST-OF-MARKS")))), list(RET, makeSymbol("MARK"))); static private final SubLList $list_alt13 = list(list(makeSymbol("SET-MARKS-INTERNAL"), makeSymbol("SELF"), list(makeSymbol("DELETE"), makeSymbol("MARK"), list(makeSymbol("GET-MARKS-INTERNAL"), makeSymbol("SELF")))), list(RET, makeSymbol("MARK"))); static private final SubLList $list_alt15 = list(list(RET, list(makeSymbol("FIF"), list(makeSymbol("MEMBER"), makeSymbol("MARK"), list(makeSymbol("GET-MARKS-INTERNAL"), makeSymbol("SELF"))), T, NIL))); @Override public void declareFunctions() { declare_subloop_markable_file(); } @Override public void initializeVariables() { init_subloop_markable_file(); } @Override public void runTopLevelForms() { setup_subloop_markable_file(); } static private final SubLList $list_alt17 = list(list(makeSymbol("SET-MARKS-INTERNAL"), makeSymbol("SELF"), NIL), list(RET, makeSymbol("SELF"))); } /** * Total time: 88 ms */ import android.util.Log; import owt.p2p.P2PClient; import owt.p2p.RemoteStream; public class Expectations implements P2PClient.P2PClientObserver{ private static final String TAG = Expectations.class.getSimpleName(); @Override public void onServerDisconnected() { Log.v(TAG, "onServerDisconnected."); } @Override public void onStreamAdded(RemoteStream remoteStream) { Log.v(TAG, "onStreamAdded."); } @Override public void onDataReceived(String peerId, String message) { Log.v(TAG, "onDataReceived."); } } /* * Logical Structural Diff (LSDiff) * Copyright (C) <2015> > * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /* * Created on Jun 18, 2004 */ package tyRuBa.engine.factbase; import tyRuBa.engine.Validator; /** * A ValidatorManager persists the Validators that indicate whether facts for a * bucket are valid or not. In a FactBase the validators are referenced by their * handles, so mappings are implemented in the ValidatorManager that allow * retrieval of a validator by giving its handle. * @category FactBase * @author riecken */ public interface ValidatorManager { /** * Adds a validator to this manager. * @param v the Validator * @param identifier an identifier for this validator */ public void add(Validator v, String identifier); /** * Updates the specified validator. * @param validatorHandle the validator's handle */ public void update(long validatorHandle, Boolean outdated, Boolean hasFacts); /** * Removes the validator identified by the specified handle. * @param validatorHandle the validator's handle */ public void remove(long validatorHandle); /** * Removes a validator. * @param identifier identifier for the validator to remove. */ public void remove(String identifier); /** * Retrieves a validator by its handle. * @param validatorHandle validator to retrieve. */ public Validator get(long validatorHandle); /** * Retrieves a validator by its identifier. * @param identifier Identifier of validator to retrieve. */ public Validator get(String identifier); /** * Retrieves the identifer for a given validator. * @param validatorHandle handle for the validator whose identifier you * want. */ public String getIdentifier(long validatorHandle); /** * Prints out all the validators. */ public void printOutValidators(); /** * Persists the validators. */ public void backup(); /** * Returns the last time a validator was invalidated. */ public long getLastInvalidatedTime(); }/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.tests.cli; import com.facebook.presto.cli.Presto; import com.google.common.collect.ImmutableList; import com.google.inject.Inject; import com.google.inject.name.Named; import io.prestodb.tempto.ProductTest; import java.io.File; import java.io.IOException; import java.util.List; import static com.google.common.io.Resources.getResource; import static com.google.common.io.Resources.readLines; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; public class PrestoCliLauncher extends ProductTest { protected static final long TIMEOUT = 300 * 1000; // 30 secs per test protected static final String EXIT_COMMAND = "exit"; protected final List nationTableInteractiveLines; protected final List nationTableBatchLines; private static final String CLASSPATH = System.getProperty("java.class.path"); private static final String JAVA_BIN = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; @Inject @Named("databases.presto.host") protected String serverHost; @Inject @Named("databases.presto.server_address") protected String serverAddress; protected PrestoCliProcess presto; protected PrestoCliLauncher() throws IOException { nationTableInteractiveLines = readLines(getResource("com/facebook/presto/tests/cli/interactive_query.results"), UTF_8); nationTableBatchLines = readLines(getResource("com/facebook/presto/tests/cli/batch_query.results"), UTF_8); } protected void stopPresto() throws InterruptedException { if (presto != null) { presto.getProcessInput().println(EXIT_COMMAND); presto.waitForWithTimeoutAndKill(); } } protected void launchPrestoCli(String... arguments) throws IOException { launchPrestoCli(asList(arguments)); } protected void launchPrestoCli(List arguments) throws IOException { presto = new PrestoCliProcess(getProcessBuilder(arguments).start()); } protected ProcessBuilder getProcessBuilder(List arguments) { return new ProcessBuilder(ImmutableList.builder() .add(JAVA_BIN, "-cp", CLASSPATH, Presto.class.getCanonicalName()) .addAll(arguments) .build()); } } package com.me.coin.framework.ioc; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.me.coin.framework.aop.AopCache; import com.me.coin.framework.aop.ProxyChain; import com.me.coin.framework.aop.ProxyManager; import com.me.coin.framework.dao.impl.CoinDao; import com.me.coin.framework.ioc.annotation.IocBean; import com.me.coin.framework.tx.TransactionProxy; import com.me.coin.framework.tx.annotation.Service; import com.me.coin.framework.util.Strings; /** * 存放所有bean的容器 * @author dwl * */ public class CoinIocCache { //存放所有的bean private Map, CoinBean> cache = new HashMap, CoinBean>(); public CoinIocCache() { CoinBean dao = new CoinBean("coinDao", new CoinDao()); dao.setInject(true); cache.put(CoinDao.class,dao); } /** * controller类 * @param clazz */ public void addActionBean(Class clazz){ try { String name = Strings.lowerFirst(clazz.getSimpleName()); cache.put(clazz, new CoinBean(name, clazz.newInstance())); } catch (Exception e) { e.printStackTrace(); } } /** * service类通过动态代理生成 * @param clazz */ public void addServiceBean(Class clazz){ Object bean = TransactionProxy.getProxy(clazz); Service service = clazz.getAnnotation(Service.class); String name = service.value(); if(Strings.isEmpty(name)) name = Strings.lowerFirst(clazz.getSimpleName()); cache.put(clazz, new CoinBean(name, bean)); } /** * 普通bean类 * @param clazz */ public void addIocBean(Class clazz){ try { IocBean iocBean = clazz.getAnnotation(IocBean.class); String name = iocBean.value(); if(Strings.isEmpty(name)) name = Strings.lowerFirst(clazz.getSimpleName()); cache.put(clazz, new CoinBean(name, clazz.newInstance())); } catch (Exception e) { e.printStackTrace(); } } /** * aop切面后的bean * @param clazz */ public void addAopBean(Class clazz){ String name = ""; if(clazz.isAnnotationPresent(IocBean.class)) name = clazz.getAnnotation(IocBean.class).value(); if(clazz.isAnnotationPresent(Service.class)) name = clazz.getAnnotation(Service.class).value(); ProxyChain chain = AopCache.getChain(clazz); Object bean = ProxyManager.getProxy(clazz, chain); if(Strings.isEmpty(name)) name = Strings.lowerFirst(clazz.getSimpleName()); cache.put(clazz, new CoinBean(name, bean)); } public boolean hasCoinBean(Class clazz){ return cache.containsKey(clazz); } public CoinBean getCoinBean(Class clazz){ return cache.get(clazz); } /** * 根据接口获取所有实现类 * @param clazz * @return */ public List> getInterfaceImpl(Class clazz){ List> classes = new ArrayList<>(); cache.forEach((k,v)->{ if(clazz.isAssignableFrom(k)) classes.add(k); }); return classes; } } 0 package com.jude.rollviewpagerdome.widget; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.Gravity; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.jude.rollviewpagerdome.R; public class LoadingDialog extends Dialog { private ImageView mImageView; public LoadingDialog(Context context) { super(context, R.style.base_dialog); } public LoadingDialog(Context context, int themeResId) { super(context, R.style.base_dialog); } protected LoadingDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, R.style.base_dialog); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.custom_progress_dialog); mImageView = (ImageView) findViewById(R.id.custom_progress_dialog_img); mImageView.setImageResource(R.mipmap.spinner); } @Override public void show() { super.show(); Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(getContext(), R.anim .progress_animator); mImageView.startAnimation(hyperspaceJumpAnimation); } @Override public void hide() { super.hide(); if (mImageView != null) { mImageView.clearAnimation(); } } @Override protected void onStart() { super.onStart(); WindowManager.LayoutParams layoutParams = getWindow().getAttributes(); layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT; layoutParams.gravity = Gravity.CENTER; getWindow().setAttributes(layoutParams); } } RCIX/BaseMod package basemod; import basemod.helpers.ConvertHelper; import basemod.interfaces.PostEnergyRechargeSubscriber; import basemod.interfaces.PostInitializeSubscriber; import basemod.interfaces.PostRenderSubscriber; import basemod.interfaces.PostUpdateSubscriber; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.actions.GameActionManager; import com.megacrit.cardcrawl.actions.common.*; import com.megacrit.cardcrawl.blights.AbstractBlight; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.events.AbstractImageEvent; import com.megacrit.cardcrawl.helpers.*; import com.megacrit.cardcrawl.map.MapEdge; import com.megacrit.cardcrawl.map.MapRoomNode; import com.megacrit.cardcrawl.potions.AbstractPotion; import com.megacrit.cardcrawl.relics.AbstractRelic; import com.megacrit.cardcrawl.rooms.MonsterRoom; import com.megacrit.cardcrawl.ui.panels.EnergyPanel; import com.megacrit.cardcrawl.unlock.UnlockTracker; import com.megacrit.cardcrawl.vfx.cardManip.ShowCardAndObtainEffect; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class DevConsole implements PostEnergyRechargeSubscriber, PostInitializeSubscriber, PostRenderSubscriber, PostUpdateSubscriber { public static final Logger logger = LogManager.getLogger(DevConsole.class.getName()); public static final float CONSOLE_X = 200.0f; public static final float CONSOLE_Y = 200.0f; public static final float CONSOLE_W = 800.0f; public static final float CONSOLE_H = 40.0f; public static final float CONSOLE_PAD_X = 15.0f; public static final int CONSOLE_TEXT_SIZE = 30; private static final int MAX_LINES = 8; // This regular expression matches any number of consecutive whitespaces (but at least 1) public static final String PATTERN = "[\\s]+"; public static final String PROMPT = "$> "; public static BitmapFont consoleFont = null; private static InputProcessor consoleInputProcessor; private static InputProcessor otherInputProcessor = null; public static Texture consoleBackground = null; private static boolean infiniteEnergy = false; public static boolean forceUnlocks = false; public static int unlockLevel = -1; public static boolean enabled = false; public static boolean visible = false; public static int toggleKey = Keys.GRAVE; public static String currentText = ""; public static int priorKey = Keys.UP; public static int nextKey = Keys.DOWN; public static ArrayList priorCommands; public static ArrayList log; public static ArrayList prompted; public static int commandPos; public DevConsole() { BaseMod.subscribe(this); priorCommands = new ArrayList<>(); commandPos = -1; log = new ArrayList<>(); prompted = new ArrayList<>(); AutoComplete.init(); } // If you add, remove or change a command make sure to also do the same in the AutoComplete class public static void execute() { // To get the tokens, we first trim the current Text (removing whitespaces from the start and end) // then we split it using a pattern that matches one or more consecutive whitespaces // The resulting array tokens only has Strings with no whitespaces String[] tokens = currentText.trim().split(PATTERN); if (priorCommands.size() == 0 || !priorCommands.get(0).equals(currentText)) { priorCommands.add(0, currentText); } log.add(0, currentText); prompted.add(0, true); commandPos = -1; currentText = ""; if (tokens.length < 1) { return; } for (int i = 0; i < tokens.length; i++) { tokens[i] = tokens[i].trim(); } switch (tokens[0].toLowerCase()) { case "relic": { cmdRelic(tokens); break; } case "hand": { cmdHand(tokens); break; } case "info": { Settings.isInfo = !Settings.isInfo; break; } case "kill": { cmdKill(tokens); break; } case "gold": { cmdGold(tokens); break; } case "energy": { cmdEnergy(tokens); break; } case "deck": { cmdDeck(tokens); break; } case "draw": { cmdDraw(tokens); break; } case "fight": { cmdFight(tokens); break; } case "event": { cmdEvent(tokens); break; } case "potion": { cmdPotion(tokens); break; } case "unlock": { cmdUnlock(tokens); break; } case "power": { cmdPower(tokens); break; } case "clear": { cmdClear(tokens); break; } case "help": { cmdHelp(); break; } case "hp": { cmdHP(tokens); break; } case "maxhp": { cmdMaxHP(tokens); break; } case "debug": { cmdDebugMode(tokens); break; } case "blight": cmdBlight(tokens); break; default: { log("invalid command"); break; } } } private static void cmdDebugMode(String[] tokens) { if(tokens.length == 2 && (tokens[1].equals("true") || tokens[1].equals("false"))) { try { Settings.isDebug = Boolean.parseBoolean(tokens[1]); log("Setting debug mode to: " + Settings.isDebug); } catch(Exception e) { couldNotParse(); log("options are:"); log("* true"); log("* false"); } }else { couldNotParse(); log("options are:"); log("* true"); log("* false"); } } private static void cmdClear(String[] tokens) { if (tokens.length < 2) { clearLog(); clearCmds(); } else if (tokens[1].equals("log")) { clearLog(); } else if (tokens[1].equals("cmd")) { clearCmds(); } else { cmdClearHelp(); } } // clear log private static void clearLog() { while (log.size() > 0) { log.remove(0); } while (prompted.size() > 0) { prompted.remove(0); } } // clear command list private static void clearCmds() { while (priorCommands.size() > 0) { priorCommands.remove(0); } } private static void cmdClearHelp() { couldNotParse(); log("options are:"); log("* log"); log("* cmd"); } // print help info private static void cmdHelp() { log("options are: relic hand info kill gold energy deck..."); log("draw fight event potion unlock power clear help hp maxhp"); } private static void cmdPower(String[] tokens) { if (tokens.length < 2) { cmdPowerHelp(); return; } String powerID = ""; int amount = 1; for (int i = 1; i < tokens.length - 1; i++) { powerID = powerID.concat(tokens[i]).concat(" "); } try { amount = Integer.parseInt(tokens[tokens.length - 1]); } catch (Exception e) { powerID = powerID.concat(tokens[tokens.length - 1]); } powerID = powerID.trim(); // If the ID was written using underscores, find the original ID if (BaseMod.underScorePowerIDs.containsKey(powerID)) { powerID = BaseMod.underScorePowerIDs.get(powerID); } Class power; try { power = BaseMod.getPowerClass(powerID); } catch (Exception e) { logger.info("failed to load power " + powerID); log("could not load power"); cmdPowerHelp(); return; } try { new ConsoleTargetedPower(power, amount); } catch (Exception e) { log("could not make power"); cmdPowerHelp(); } } private static void cmdPowerHelp() { couldNotParse(); log("options are:"); log("* [id] [amt]"); } private static String getRelicName(String[] relicNameArray) { String relic = String.join(" ", relicNameArray); if (BaseMod.underScoreRelicIDs.containsKey(relic)) { relic = BaseMod.underScoreRelicIDs.get(relic); } return relic; } private static void cmdRelic(String[] tokens) { if (AbstractDungeon.player != null) { if (tokens.length < 2) { cmdRelicHelp(); return; } if ((tokens[1].toLowerCase().equals("remove") || tokens[1].toLowerCase().equals("r")) && tokens.length > 2) { String[] relicNameArray = Arrays.copyOfRange(tokens, 2, tokens.length); String relicName = getRelicName(relicNameArray); AbstractDungeon.player.loseRelic(relicName); } else if ((tokens[1].toLowerCase().equals("add") || tokens[1].toLowerCase().equals("a")) && tokens.length > 2) { String[] relicNameArray = Arrays.copyOfRange(tokens, 2, tokens.length); String relicName = getRelicName(relicNameArray); AbstractDungeon.getCurrRoom().spawnRelicAndObtain(Settings.WIDTH / 2, Settings.HEIGHT / 2, RelicLibrary.getRelic(relicName).makeCopy()); } else if (tokens[1].toLowerCase().equals("desc") && tokens.length > 2) { String[] relicNameArray = Arrays.copyOfRange(tokens, 2, tokens.length); String relicName = getRelicName(relicNameArray); log(RelicLibrary.getRelic(relicName).description); } else if (tokens[1].toLowerCase().equals("flavor") && tokens.length > 2) { String[] relicNameArray = Arrays.copyOfRange(tokens, 2, tokens.length); String relicName = getRelicName(relicNameArray); log(RelicLibrary.getRelic(relicName).flavorText); } else if (tokens[1].toLowerCase().equals("pool") && tokens.length > 2) { String[] relicNameArray = Arrays.copyOfRange(tokens, 2, tokens.length); String relicName = getRelicName(relicNameArray); log(RelicLibrary.getRelic(relicName).tier.toString()); } else if (tokens[1].toLowerCase().equals("list")) { if (tokens.length < 3) { cmdRelicListHelp(); return; } switch (tokens[2]) { case "starter": { Collections.sort(RelicLibrary.starterList); logger.info(RelicLibrary.starterList); log(RelicLibrary.starterList); break; } case "common": { Collections.sort(RelicLibrary.commonList); logger.info(RelicLibrary.commonList); log(RelicLibrary.commonList); break; } case "uncommon": { Collections.sort(RelicLibrary.uncommonList); logger.info(RelicLibrary.uncommonList); log(RelicLibrary.uncommonList); break; } case "rare": { Collections.sort(RelicLibrary.rareList); logger.info(RelicLibrary.rareList); log(RelicLibrary.rareList); } case "boss": { Collections.sort(RelicLibrary.bossList); logger.info(RelicLibrary.bossList); log(RelicLibrary.bossList); break; } case "special": { Collections.sort(RelicLibrary.specialList); logger.info(RelicLibrary.specialList); log(RelicLibrary.specialList); break; } case "shop": { Collections.sort(RelicLibrary.shopList); logger.info(RelicLibrary.shopList); log(RelicLibrary.shopList); break; } default: { cmdRelicListHelp(); } } } else { cmdRelicHelp(); } } } private static void cmdRelicHelp() { couldNotParse(); log("options are:"); log("* remove [id]"); log("* add [id]"); log("* desc [id]"); log("* flavor [id]"); log("* pool [id]"); log("* list [type]"); } private static void cmdRelicListHelp() { log("options are: starter common uncommon rare boss special shop"); } private static void cmdBlight(String[] tokens) { if (AbstractDungeon.player != null) { if (tokens.length < 2) { cmdBlightHelp(); return; } if ((tokens[1].toLowerCase().equals("remove") || tokens[1].toLowerCase().equals("r")) && tokens.length > 2) { String[] blightNameArray = Arrays.copyOfRange(tokens, 2, tokens.length); String blightName = String.join(" ", blightNameArray); AbstractDungeon.player.blights.removeIf(b -> b.blightID.equals(blightName)); // Reorganize Blights for (int i=0; i 2) { String[] blightNameArray = Arrays.copyOfRange(tokens, 2, tokens.length); String blightName = String.join(" ", blightNameArray); AbstractBlight blight = AbstractDungeon.player.getBlight(blightName); if (blight != null) { blight.incrementUp(); blight.stack(); } else { AbstractDungeon.getCurrRoom().spawnBlightAndObtain(Settings.WIDTH / 2.0f, Settings.HEIGHT / 2.0f, BlightHelper.getBlight(blightName)); } } else { cmdBlightHelp(); } } } private static void cmdBlightHelp() { couldNotParse(); log("options are:"); log("* add [id]"); log("* remove [id]"); } private static void cmdHand(String[] tokens) { if (AbstractDungeon.player != null) { if (tokens.length < 3) { cmdHandHelp(); return; } int countIndex = tokens.length - 1; while (ConvertHelper.tryParseInt(tokens[countIndex], 0) != 0) { countIndex--; } String[] cardNameArray = Arrays.copyOfRange(tokens, 2, countIndex + 1); String cardName = String.join(" ", cardNameArray); // If the ID was written using underscores, find the original ID if (BaseMod.underScoreCardIDs.containsKey(cardName)) { cardName = BaseMod.underScoreCardIDs.get(cardName); } if (tokens[1].toLowerCase().equals("add") || tokens[1].toLowerCase().equals("a")) { AbstractCard c = CardLibrary.getCard(cardName); if (c != null) { // card count int count = 1; if (tokens.length > countIndex + 1 && ConvertHelper.tryParseInt(tokens[countIndex + 1], 0) != 0) { count = ConvertHelper.tryParseInt(tokens[countIndex + 1], 0); } int upgradeCount = 0; if (tokens.length > countIndex + 2) { upgradeCount = ConvertHelper.tryParseInt(tokens[countIndex + 2], 0); } log("adding " + count + (count == 1 ? " copy of " : " copies of ") + cardName + " with " + upgradeCount + " upgrade(s)"); for (int i = 0; i < count; i++) { AbstractCard copy = c.makeCopy(); for (int j = 0; j < upgradeCount; j++) { copy.upgrade(); } AbstractDungeon.actionManager.addToBottom(new MakeTempCardInHandAction(copy, true)); } } else { log("could not find card " + cardName); } } else if (tokens[1].toLowerCase().equals("remove") || tokens[1].toLowerCase().equals("r")) { // remove all cards if (tokens[2].equals("all")) { for (AbstractCard c : new ArrayList<>(AbstractDungeon.player.hand.group)) { AbstractDungeon.player.hand.moveToExhaustPile(c); } return; // remove single card } else { boolean removed = false; AbstractCard toRemove = null; for (AbstractCard c : AbstractDungeon.player.hand.group) { if (removed) { break; } if (c.cardID.equals(cardName)) { toRemove = c; removed = true; } } if (removed) { AbstractDungeon.player.hand.moveToExhaustPile(toRemove); } } } else if (tokens[1].toLowerCase().equals("discard") || tokens[1].toLowerCase().equals("d")) { if (tokens[2].equals("all")) { // discard all cards for (AbstractCard c : new ArrayList<>(AbstractDungeon.player.hand.group)) { AbstractDungeon.player.hand.moveToDiscardPile(c); c.triggerOnManualDiscard(); GameActionManager.incrementDiscard(false); } } else { // discard single card for (AbstractCard c : AbstractDungeon.player.hand.group) { if (c.cardID.equals(cardName)) { AbstractDungeon.player.hand.moveToDiscardPile(c); c.triggerOnManualDiscard(); GameActionManager.incrementDiscard(false); return; } } } } else if ((tokens[1].equalsIgnoreCase("set") || tokens[1].equalsIgnoreCase("s")) && (tokens[2].equalsIgnoreCase("damage") || tokens[2].equalsIgnoreCase("block") || tokens[2].equalsIgnoreCase("magic") || tokens[2].equalsIgnoreCase("cost") || tokens[2].equalsIgnoreCase("d") || tokens[2].equalsIgnoreCase("b") || tokens[2].equalsIgnoreCase("m") || tokens[2].equalsIgnoreCase("c")) && tokens.length == 5) { try{ cardNameArray = Arrays.copyOfRange(tokens, 3, countIndex + 1); cardName = String.join(" ", cardNameArray); boolean all = tokens[3].equals("all"); int v = Integer.parseInt(tokens[4]); for (AbstractCard c : new ArrayList<>(AbstractDungeon.player.hand.group)) { if (all || c.cardID.equals(cardName)) { if (tokens[2].equalsIgnoreCase("damage") || tokens[2].equalsIgnoreCase("d")) { if (c.baseDamage != v) c.upgradedDamage = true; c.baseDamage = v; } if (tokens[2].equalsIgnoreCase("block") || tokens[2].equalsIgnoreCase("b")) { if (c.baseBlock != v) c.upgradedBlock = true; c.baseBlock = v; } if (tokens[2].equalsIgnoreCase("magic") || tokens[2].equalsIgnoreCase("m")) { if (c.baseMagicNumber != v) c.upgradedMagicNumber = true; c.magicNumber = c.baseMagicNumber = v; } if (tokens[2].equalsIgnoreCase("cost") || tokens[2].equalsIgnoreCase("c")) { if (c.cost != v) c.upgradedCost = true; c.cost = v; } c.displayUpgrades(); c.applyPowers(); if (!all) break; } } } catch (NumberFormatException e) { cmdHandHelp(); } } else { cmdHandHelp(); } } else { log("cannot add cards when player doesn't exist"); } } private static void cmdHandHelp() { couldNotParse(); log("options are:"); log("* add [id] {count} {upgrade amt}"); log("* remove [id]"); log("* remove all"); log("* discard [id]"); log("* discard all"); log("* set damage [id] [amount]"); log("* set block [id] [amount]"); log("* set magic [id] [amount]"); log("* set cost [id] [amount]"); } private static void cmdKill(String[] tokens) { if (AbstractDungeon.getCurrRoom().monsters != null) { if (tokens.length != 2) { cmdKillHelp(); return; } if (tokens[1].toLowerCase().equals("all")) { int monsterCount = AbstractDungeon.getCurrRoom().monsters.monsters.size(); int[] multiDamage = new int[monsterCount]; for (int i = 0; i < monsterCount; ++i) { multiDamage[i] = 999; } AbstractDungeon.actionManager.addToTop(new DamageAllEnemiesAction(AbstractDungeon.player, multiDamage, DamageInfo.DamageType.HP_LOSS, AbstractGameAction.AttackEffect.NONE)); } else if (tokens[1].toLowerCase().equals("self")) { AbstractDungeon.actionManager .addToTop(new LoseHPAction(AbstractDungeon.player, AbstractDungeon.player, 999)); } else { cmdKillHelp(); } } } private static void cmdKillHelp() { couldNotParse(); log("options are:"); log("* all"); log("* self"); } private static void cmdHP(String[] tokens) { if (tokens.length < 2) { cmdHPHelp(); return; } if ((tokens[1].toLowerCase().equals("add") || tokens[1].toLowerCase().equals("a")) && tokens.length > 2) { int i; try { i = Integer.parseInt(tokens[2]); AbstractDungeon.actionManager .addToTop(new HealAction(AbstractDungeon.player, AbstractDungeon.player, i)); } catch (Exception e) { cmdHPHelp(); } } else if ((tokens[1].toLowerCase().equals("lose") || tokens[1].toLowerCase().equals("l")) && tokens.length > 2) { int i; try { i = Integer.parseInt(tokens[2]); AbstractDungeon.actionManager.addToTop(new LoseHPAction(AbstractDungeon.player, AbstractDungeon.player, i, AbstractGameAction.AttackEffect.NONE)); } catch (Exception e) { cmdHPHelp(); } } else { cmdHPHelp(); } } private static void cmdHPHelp() { couldNotParse(); log("options are:"); log("* add [amt]"); log("* lose [amt]"); } private static void cmdMaxHP(String[] tokens) { if (tokens.length < 2) { cmdMaxHPHelp(); return; } if ((tokens[1].toLowerCase().equals("add") || tokens[1].toLowerCase().equals("a")) && tokens.length > 2) { int i; try { i = Integer.parseInt(tokens[2]); AbstractDungeon.player.increaseMaxHp(i, true); } catch (Exception e) { cmdMaxHPHelp(); } } else if ((tokens[1].toLowerCase().equals("lose") || tokens[1].toLowerCase().equals("l")) && tokens.length > 2) { int i; try { i = Integer.parseInt(tokens[2]); AbstractDungeon.player.decreaseMaxHealth(i); } catch (Exception e) { cmdMaxHPHelp(); } } else { cmdMaxHPHelp(); } } private static void cmdMaxHPHelp() { couldNotParse(); log("options are:"); log("* add [amt]"); log("* lose [amt]"); } private static void cmdGold(String[] tokens) { if (AbstractDungeon.player != null) { if (tokens.length != 3) { cmdGoldHelp(); return; } int amount = ConvertHelper.tryParseInt(tokens[2], 0); if (tokens[1].toLowerCase().equals("add") || tokens[1].toLowerCase().equals("a")) { AbstractDungeon.player.displayGold += amount; AbstractDungeon.player.gainGold(amount); } else if (tokens[1].toLowerCase().equals("lose") || tokens[1].toLowerCase().equals("l")) { AbstractDungeon.player.displayGold = Math.max(AbstractDungeon.player.displayGold - amount, 0); AbstractDungeon.player.loseGold(amount); } else { cmdGoldHelp(); } } } private static void cmdGoldHelp() { couldNotParse(); log("options are:"); log("* add [amt]"); log("* lose [amt]"); } private static void cmdEnergy(String[] tokens) { if (AbstractDungeon.player != null) { if (tokens.length < 2) { cmdEnergyHelp(); return; } if (tokens[1].toLowerCase().equals("add") && tokens.length > 2) { AbstractDungeon.player.gainEnergy(ConvertHelper.tryParseInt(tokens[2], 0)); } else if (tokens[1].toLowerCase().equals("lose") && tokens.length > 2) { AbstractDungeon.player.loseEnergy(ConvertHelper.tryParseInt(tokens[2], 0)); } else if (tokens[1].toLowerCase().equals("inf")) { infiniteEnergy = !infiniteEnergy; if (infiniteEnergy) { AbstractDungeon.player.gainEnergy(9999); } } else { cmdEnergyHelp(); } } } private static void cmdEnergyHelp() { couldNotParse(); log("options are:"); log("* add [amt]"); log("* lose [amt]"); log("* inf"); } private static void couldNotParse() { log("could not parse previous command"); } private static void cmdUnlock(String[] tokens) { if (tokens.length < 2) { return; } if (tokens[1].toLowerCase().equals("always")) { forceUnlocks = !forceUnlocks; } else if (tokens[1].toLowerCase().equals("level") && tokens.length > 2) { unlockLevel = ConvertHelper.tryParseInt(tokens[2]); } } private static void cmdDeck(String[] tokens) { if (AbstractDungeon.player != null) { if (tokens.length < 3) { cmdDeckHelp(); return; } int countIndex = tokens.length - 1; while (ConvertHelper.tryParseInt(tokens[countIndex], 0) != 0) { countIndex--; } String[] cardNameArray = Arrays.copyOfRange(tokens, 2, countIndex + 1); String cardName = String.join(" ", cardNameArray); // If the ID was written using underscores, find the original ID if (BaseMod.underScoreCardIDs.containsKey(cardName)) { cardName = BaseMod.underScoreCardIDs.get(cardName); } if (tokens[1].toLowerCase().equals("add") || tokens[1].toLowerCase().equals("a")) { AbstractCard c = CardLibrary.getCard(cardName); if (c != null) { // card count int count = 1; if (tokens.length > countIndex + 1 && ConvertHelper.tryParseInt(tokens[countIndex + 1], 0) != 0) { count = ConvertHelper.tryParseInt(tokens[countIndex + 1], 0); } int upgradeCount = 0; if (tokens.length > countIndex + 2) { upgradeCount = ConvertHelper.tryParseInt(tokens[countIndex + 2], 0); } log("adding " + count + (count == 1 ? " copy of " : " copies of ") + cardName + " with " + upgradeCount + " upgrade(s)"); for (int i = 0; i < count; i++) { AbstractCard copy = c.makeCopy(); for (int j = 0; j < upgradeCount; j++) { copy.upgrade(); } UnlockTracker.markCardAsSeen(copy.cardID); AbstractDungeon.effectList.add(new ShowCardAndObtainEffect(copy, Settings.WIDTH / 2.0f, Settings.HEIGHT / 2.0f)); } } else { log("could not find card " + cardName); } } else if (tokens[1].toLowerCase().equals("remove") || tokens[1].toLowerCase().equals("r")) { // remove all cards if (tokens[2].equals("all")) { for (String str : AbstractDungeon.player.masterDeck.getCardNames()) { AbstractDungeon.player.masterDeck.removeCard(str); } // remove single card } else { AbstractDungeon.player.masterDeck.removeCard(cardName); } } else { cmdDeckHelp(); } } else { log("cannot add cards when player doesn't exist"); } } private static void cmdDeckHelp() { couldNotParse(); log("options are:"); log("* add [id] {count} {upgrade amt}"); log("* remove [id]"); log("* remove all"); } private static void cmdDraw(String[] tokens) { if (AbstractDungeon.getCurrRoom().monsters != null) { if (tokens.length != 2) { cmdDrawHelp(); return; } AbstractDungeon.actionManager .addToTop(new DrawCardAction(AbstractDungeon.player, ConvertHelper.tryParseInt(tokens[1], 0))); } else { log("cannot draw when not in combat"); } } private static void cmdDrawHelp() { couldNotParse(); log("options are:"); log("* draw [amt]"); } private static void cmdFight(String[] tokens) { if (tokens.length < 2) { return; } MapRoomNode cur = AbstractDungeon.currMapNode; if (cur == null) { log("cannot fight when there is no map"); return; } String[] encounterArray = Arrays.copyOfRange(tokens, 1, tokens.length); String encounterName = String.join(" ", encounterArray); // If the ID was written using underscores, find the original ID if (BaseMod.underScoreEncounterIDs.containsKey(encounterName)) { encounterName = BaseMod.underScoreEncounterIDs.get(encounterName); } if (AbstractDungeon.getCurrRoom() instanceof MonsterRoom) { // Note: AbstractDungeon.nextRoomTransition() will remove the encounter of the current room from the monster list // so if we want the new encounter to be in the front afterwards for our new MonsterRoom, we should insert the encounter at position 1, not 0 AbstractDungeon.monsterList.add(1, encounterName); } else { AbstractDungeon.monsterList.add(0, encounterName); } MapRoomNode node = new MapRoomNode(cur.x, cur.y); node.room = new MonsterRoom(); ArrayList curEdges = cur.getEdges(); for (MapEdge edge : curEdges) { node.addEdge(edge); } AbstractDungeon.nextRoom = node; AbstractDungeon.nextRoomTransitionStart(); } private static void cmdEvent(String[] tokens) { if (tokens.length < 2) { return; } if (AbstractDungeon.currMapNode == null) { log("cannot execute event when there is no map"); return; } if (AbstractDungeon.player == null) { log("cannot execute event when player doesn't exist"); return; } String[] eventArray = Arrays.copyOfRange(tokens, 1, tokens.length); String eventName = String.join(" ", eventArray); // If the ID was written using underscores, find the original ID if (BaseMod.underScoreEventIDs.containsKey(eventName)) { eventName = BaseMod.underScoreEventIDs.get(eventName); } if (EventHelper.getEvent(eventName) == null) { couldNotParse(); log(eventName + " is not an event ID"); return; } AbstractDungeon.eventList.add(0, eventName); MapRoomNode cur = AbstractDungeon.currMapNode; MapRoomNode node = new MapRoomNode(cur.x, cur.y); node.room = new CustomEventRoom(); ArrayList curEdges = cur.getEdges(); for (MapEdge edge : curEdges) { node.addEdge(edge); } AbstractDungeon.previousScreen = null; AbstractDungeon.dynamicBanner.hide(); AbstractDungeon.dungeonMapScreen.closeInstantly(); AbstractDungeon.closeCurrentScreen(); AbstractDungeon.topPanel.unhoverHitboxes(); AbstractDungeon.fadeIn(); AbstractDungeon.effectList.clear(); AbstractDungeon.topLevelEffects.clear(); AbstractDungeon.topLevelEffectsQueue.clear(); AbstractDungeon.effectsQueue.clear(); AbstractDungeon.dungeonMapScreen.dismissable = true; AbstractDungeon.nextRoom = node; AbstractDungeon.setCurrMapNode(node); AbstractDungeon.getCurrRoom().onPlayerEntry(); AbstractDungeon.scene.nextRoom(node.room); AbstractDungeon.rs = node.room.event instanceof AbstractImageEvent ? AbstractDungeon.RenderScene.EVENT : AbstractDungeon.RenderScene.NORMAL; } private static void cmdPotion(String[] tokens) { if (PotionHelper.potions == null || PotionHelper.potions.isEmpty()) { log("cannot use potion command when potions are not initialized"); log("start a run and try again"); return; } if (tokens.length < 2) { cmdPotionHelp(); return; } int i; try { i = Integer.parseInt(tokens[1]); } catch (Exception e) { // check if we want to list potions if (tokens[1].equals("list")) { Collections.sort(PotionHelper.potions); log(PotionHelper.potions); } else { cmdPotionHelp(); } return; } if (AbstractDungeon.player == null) { log("cannot obtain potion when player doesn't exist"); return; } String potionID = ""; for (int k = 2; k < tokens.length; k++) { potionID = potionID.concat(tokens[k]); if (k != tokens.length - 1) { potionID = potionID.concat(" "); } } // If the ID was written using underscores, find the original ID if (BaseMod.underScorePotionIDs.containsKey(potionID)) { potionID = BaseMod.underScorePotionIDs.get(potionID); } AbstractPotion p = null; if (PotionHelper.potions.contains(potionID)) { p = PotionHelper.getPotion(potionID); } if (PotionHelper.potions.contains(potionID + " Potion")) { p = PotionHelper.getPotion(potionID + " Potion"); } if (p == null) { log("invalid potion id"); log("use potion list to see valid ids"); return; } if (i >= AbstractDungeon.player.potionSlots || i < 0) { log("cannot obtain potion in invalid slot " + i); log("use values between 0 and " + (AbstractDungeon.player.potionSlots - 1)); return; } AbstractDungeon.player.obtainPotion(i, p); } public static void cmdPotionHelp() { couldNotParse(); log("options are:"); log("* list"); log("* [slot] [id]"); } @Override public void receivePostEnergyRecharge() { if (infiniteEnergy) { EnergyPanel.setEnergy(9999); } } @Override public void receivePostInitialize() { consoleInputProcessor = new ConsoleInputProcessor(); // Console font FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("font/Kreon-Regular.ttf")); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = (int) (CONSOLE_TEXT_SIZE * Settings.scale); consoleFont = generator.generateFont(parameter); generator.dispose(); consoleBackground = ImageMaster.loadImage("img/ConsoleBackground.png"); AutoComplete.postInit(); } public static void log(String text) { log.add(0, text); prompted.add(0, false); } public static void log(@SuppressWarnings("rawtypes") ArrayList list) { for (Object o : list) { log(o.toString()); } } @Override public void receivePostRender(SpriteBatch sb) { if (visible && consoleFont != null) { int sizeToDraw = log.size() + 1; if (sizeToDraw > MAX_LINES) { sizeToDraw = MAX_LINES; } sb.draw(consoleBackground, CONSOLE_X * Settings.scale, CONSOLE_Y * Settings.scale, (CONSOLE_W * Settings.scale), (CONSOLE_H * Settings.scale + (CONSOLE_TEXT_SIZE * Settings.scale * (sizeToDraw - 1)))); if (AutoComplete.enabled) { AutoComplete.render(sb); } float x = (CONSOLE_X * Settings.scale + (CONSOLE_PAD_X * Settings.scale)); float y = (CONSOLE_Y * Settings.scale + (float) Math.floor(CONSOLE_TEXT_SIZE * Settings.scale)); consoleFont.draw(sb, PROMPT + currentText, x, y); for (int i = 0; i < sizeToDraw - 1; i++) { y += (float) Math.floor(CONSOLE_TEXT_SIZE * Settings.scale); consoleFont.draw(sb, (prompted.get(i) ? PROMPT : "") + log.get(i), x, y); } } } @Override public void receivePostUpdate() { if (Gdx.input.isKeyJustPressed(toggleKey)) { AutoComplete.reset(); if (visible) { currentText = ""; commandPos = -1; } else { otherInputProcessor = Gdx.input.getInputProcessor(); if (AutoComplete.enabled) { AutoComplete.suggest(false); } } // only allow opening console when enabled but allow closing the console anytime if (visible || enabled) { Gdx.input.setInputProcessor(visible ? otherInputProcessor : consoleInputProcessor); visible = !visible; } } // If AutoComplete is enabled and the key to select a suggestion is pressed // select the next or previous suggestion if (AutoComplete.enabled && Gdx.input.isKeyPressed(AutoComplete.selectKey)) { if (Gdx.input.isKeyJustPressed(priorKey) ) { if (visible) { AutoComplete.selectUp(); } } if (Gdx.input.isKeyJustPressed(nextKey)) { if (visible) { AutoComplete.selectDown(); } } } else { // get previous commands if (Gdx.input.isKeyJustPressed(priorKey)) { if (visible) { if (commandPos + 1 < priorCommands.size()) { commandPos++; currentText = priorCommands.get(commandPos); AutoComplete.resetAndSuggest(); } } } if (Gdx.input.isKeyJustPressed(nextKey)) { if (visible) { if (commandPos - 1 < 0) { currentText = ""; commandPos = -1; } else { commandPos--; currentText = priorCommands.get(commandPos); } AutoComplete.resetAndSuggest(); } } } // If the fill in key is pressed automaticallly fill in what the user wants if (AutoComplete.enabled && (Gdx.input.isKeyJustPressed(AutoComplete.fillKey1) || Gdx.input.isKeyJustPressed(AutoComplete.fillKey2))) { AutoComplete.fillInSuggestion(); } // if the key to delete the last token is pressed, delete the rightmost token if (Gdx.input.isKeyJustPressed(AutoComplete.deleteTokenKey)) { AutoComplete.removeOneTokenUsingSpaceAndIdDelimiter(); if (AutoComplete.enabled) { AutoComplete.suggest(false); } } } } eymeneruyar/Java-MySQL-Storage-Management-Project1-10 package Servlets; import Entities.Product; import Entities.ReportCOA; import Entities.View_CheckOutActions; import Utils.DBUtil; import com.google.gson.Gson; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet(name = "checkOutActionsServlet",value = "/COAReport") public class CheckOutActionsServlet extends HttpServlet { Gson gson = new Gson(); DBUtil util = new DBUtil(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String obj = req.getParameter("obj"); ReportCOA reportCOA = gson.fromJson(obj, ReportCOA.class); System.out.println(reportCOA.toString()); String stJson = ""; //Kasa value = -1 --- Giriş value = 1 --- Çıkış value = 2 if(reportCOA.getCbIn_status() == 2 && reportCOA.getCu_id() == -1){ //Kasa Çıkış stJson = gson.toJson(util.allPaymentOutFilterDate(reportCOA.getCOA_startDate(),reportCOA.getCOA_endDate())); System.out.println("Kasa Çıkış"); }else if(reportCOA.getCbIn_status() == 1 && reportCOA.getCu_id() != -1){ //Müşteri Giriş stJson = gson.toJson(util.viewCOATable(reportCOA.getCu_id(),reportCOA.getCOA_startDate(),reportCOA.getCOA_endDate())); System.out.println("Müşteri Giriş"); }else{//Kasa Giriş stJson = gson.toJson(util.viewCOABoxInTable(reportCOA.getCOA_startDate(),reportCOA.getCOA_endDate())); System.out.println("Kasa Giriş"); } //ls.forEach(it-> System.out.println("deneme: " + it.toString())); resp.setContentType("application/json"); resp.getWriter().write(stJson); } } android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/medialibrary/GetAssets.java1000+ package abi43_0_0.expo.modules.medialibrary; import android.content.Context; import android.content.ContentResolver; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import abi43_0_0.expo.modules.core.Promise; import static abi43_0_0.expo.modules.medialibrary.MediaLibraryConstants.ASSET_PROJECTION; import static abi43_0_0.expo.modules.medialibrary.MediaLibraryConstants.ERROR_NO_PERMISSIONS; import static abi43_0_0.expo.modules.medialibrary.MediaLibraryConstants.ERROR_UNABLE_TO_LOAD; import static abi43_0_0.expo.modules.medialibrary.MediaLibraryConstants.ERROR_UNABLE_TO_LOAD_PERMISSION; import static abi43_0_0.expo.modules.medialibrary.MediaLibraryConstants.EXTERNAL_CONTENT; import static abi43_0_0.expo.modules.medialibrary.MediaLibraryUtils.putAssetsInfo; class GetAssets extends AsyncTask { private final Context mContext; private final Promise mPromise; private final Map mAssetOptions; public GetAssets(Context context, Map assetOptions, Promise promise) { mContext = context; mAssetOptions = assetOptions; mPromise = promise; } @Override protected Void doInBackground(Void... params) { final Bundle response = new Bundle(); GetQueryInfo getQueryInfo = new GetQueryInfo(mAssetOptions).invoke(); final String selection = getQueryInfo.getSelection(); final String order = getQueryInfo.getOrder(); final int limit = getQueryInfo.getLimit(); final int offset = getQueryInfo.getOffset(); ContentResolver contentResolver = mContext.getContentResolver(); try (Cursor assets = contentResolver.query( EXTERNAL_CONTENT, ASSET_PROJECTION, selection, null, order)) { if (assets == null) { mPromise.reject(ERROR_UNABLE_TO_LOAD, "Could not get assets. Query returns null."); } else { ArrayList assetsInfo = new ArrayList<>(); putAssetsInfo(contentResolver, assets, assetsInfo, limit, offset, false); response.putParcelableArrayList("assets", assetsInfo); response.putBoolean("hasNextPage", !assets.isAfterLast()); response.putString("endCursor", Integer.toString(assets.getPosition())); response.putInt("totalCount", assets.getCount()); mPromise.resolve(response); } } catch (SecurityException e) { mPromise.reject(ERROR_UNABLE_TO_LOAD_PERMISSION, "Could not get asset: need READ_EXTERNAL_STORAGE permission.", e); } catch (IOException e) { mPromise.reject(ERROR_UNABLE_TO_LOAD, "Could not read file", e); } catch (UnsupportedOperationException e) { e.printStackTrace(); mPromise.reject(ERROR_NO_PERMISSIONS, e.getMessage()); } return null; } } gridgo-utils/src/main/java/io/gridgo/utils/exception/ObjectReflectiveException.java package io.gridgo.utils.exception; public class ObjectReflectiveException extends RuntimeException { private static final long serialVersionUID = -2569346711203369483L; public ObjectReflectiveException(Throwable cause) { super(cause); } public ObjectReflectiveException(String msg, Throwable cause) { super(msg, cause); } } /* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.services.task.commands; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import org.jbpm.services.task.utils.ClassUtil; import org.kie.api.runtime.Context; import org.kie.internal.task.api.TaskDeadlinesService; import org.kie.internal.task.api.TaskDeadlinesService.DeadlineType; import org.kie.internal.task.api.TaskPersistenceContext; import org.kie.internal.task.api.model.DeadlineSummary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @XmlRootElement(name="init-deadlines-command") @XmlAccessorType(XmlAccessType.NONE) public class InitDeadlinesCommand extends TaskCommand { private static final long serialVersionUID = -8095766991770311489L; private static final Logger logger = LoggerFactory.getLogger(InitDeadlinesCommand.class); private final String deploymentId; private final Class> resultClass; public InitDeadlinesCommand() { this(null); } public InitDeadlinesCommand(String deploymentId) { this.deploymentId = deploymentId; resultClass = ClassUtil.> castClass(List.class); } @Override public Void execute(Context context) { TaskContext ctx = (TaskContext) context; TaskPersistenceContext persistenceContext = ctx.getPersistenceContext(); TaskDeadlinesService deadlineService = ctx.getTaskDeadlinesService(); try { processDeadlines("UnescalatedStartDeadlines", DeadlineType.START, persistenceContext, deadlineService); processDeadlines("UnescalatedEndDeadlines", DeadlineType.END, persistenceContext, deadlineService); } catch (Exception e) { logger.error("Error when executing deadlines", e); } return null; } private void processDeadlines(String queryName, DeadlineType deadlineType, TaskPersistenceContext persistenceContext, TaskDeadlinesService deadlineService) { List resultList = deploymentId == null ? persistenceContext.queryInTransaction(queryName, resultClass) : persistenceContext.queryWithParametersInTransaction(queryName + "ByDeployment", Collections.singletonMap("deploymentId", deploymentId), resultClass); long now = System.currentTimeMillis(); for (DeadlineSummary summary : resultList) { deadlineService.schedule(summary.getTaskId(), summary.getDeadlineId(), summary.getDate().getTime() - now, deadlineType); } } } package com.spinnerconsulting; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.util.NumberToTextConverter; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class Excel { /** * Value when no record limit is specified by the controller. */ public static final int NO_ROW_LIMIT = -1; /** * The maximum number of records configured to iterate over the rows. */ private int maxRows = NO_ROW_LIMIT; /** * The WebDriver object doing the web interactions. */ private WebClient client; /** * Controller set file path where the xlsx file resides. */ private String filePath; /** * Executes the queries listed in the Excel file set in filePath. * * @throws Exception */ void runQueries() throws Exception { InputStream inp = new FileInputStream(filePath); XSSFWorkbook wb = new XSSFWorkbook(inp); XSSFSheet sheet = wb.getSheetAt(0); // maxRows begins at 1. getLastRowNum begins at 0 // reconcile rowEnd to begin at 0 int rowEnd = (maxRows == NO_ROW_LIMIT ? sheet.getLastRowNum() : Math.min(maxRows - 1, sheet.getLastRowNum())); for (int rowNum = 0; rowNum <= rowEnd; rowNum++) { Row r = sheet.getRow(rowNum); if (r == null) { continue; } // always column C in the spreadsheet int cn = 2; Cell c = r.getCell(cn); if (c == null) { continue; } String cellValue; if (c.getCellType() == Cell.CELL_TYPE_NUMERIC) { cellValue = NumberToTextConverter.toText(c.getNumericCellValue()); } else if (c.getCellType() == Cell.CELL_TYPE_STRING) { cellValue = c.getStringCellValue().trim(); } else { cellValue = null; } if (cellValue != null) { Cell cell2 = r.createCell(cn + 1); try { cell2.setCellValue((client.valueExists(cellValue) ? "Yes" : "No")); } catch (Exception e) { cell2.setCellValue("error"); e.printStackTrace(); continue; } } } inp.close(); FileOutputStream os = new FileOutputStream(filePath); wb.write(os); os.close(); client.close(); } void setMaxRows(int i) { maxRows = i; } void setWebClient(WebClient s) { client = s; } void setFilePath(String path) { filePath = path; } } duarterafael/Conformitate /* $Id: FigNotation.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $ ***************************************************************************** * Copyright (c) 2011-2012 Contributors - see below * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * ***************************************************************************** */ package org.argouml.activity2.diagram; import java.awt.Dimension; import java.awt.Rectangle; import java.util.logging.Logger; import org.argouml.notation2.NotatedItem; import org.argouml.notation2.NotationLanguage; import org.argouml.notation2.NotationManager; import org.argouml.notation2.NotationTextEvent; import org.argouml.notation2.NotationType; import org.argouml.uml.diagram.DiagramSettings; import org.tigris.gef.presentation.FigGroup; import org.tigris.gef.presentation.FigText; /** * @author */ class FigNotation extends FigText implements NotatedItem, DiagramElement { private static final Logger LOG = Logger.getLogger(FigNotation.class.getName()); private final NotationType notationType; /** * Construct the notation fig * * @param owner owning UML element * @param bounds position and size * @param settings diagram settings * @param notationType the notation type to show */ public FigNotation( final Object owner, final Rectangle bounds, final DiagramSettings settings, final NotationType notationType) { super(bounds.x, bounds.y, bounds.width, bounds.height , true); setOwner(owner); setFont(settings.getFontPlain()); this.notationType = notationType; setTabAction(FigText.END_EDITING); setReturnAction(FigText.END_EDITING); setLineWidth(0); super.setFilled(true); NotationManager.getInstance().addListener(this); } public void setLineWidth(int lw) { super.setLineWidth(0); } /** * Notation is always transparent */ public void setFilled(boolean filled) { } @Override public Dimension getMinimumSize() { int w = getFontMetrics().stringWidth(getText()); int h = getFontMetrics().getHeight(); final int minWidth = w + getLeftMargin() + getRightMargin() + 2 * getLineWidth(); final int minHeight = h + getTopMargin() + getBotMargin() + 2 * getLineWidth(); return new Dimension(minWidth, minHeight); } public Object getMetaType() { return getOwner().getClass(); } public NotationLanguage getNotationLanguage() { return null; } public NotationType getNotationType() { return notationType; } public void notationTextChanged(NotationTextEvent event) { this.setText(event.getText()); this.setUnderline(event.isUnderlined()); this.setBold(event.isBold()); this.setItalic(event.isItalic()); if (getMinimumSize().width > getWidth()) { setWidth(getMinimumSize().width); } this.damage(); } public void setText(String s) { final String oldText = getText(); if (s.equals(oldText)) { return; } final Rectangle oldBounds = getBounds(); super.setText(s); // TODO: This should happen in GEF firePropChange("text", oldText, s); // TODO: setText in GEF should call setBounds instead of directly // changing x, y, w, h - then we will have an event generated // correctly in GEF final FigGroup group = (FigGroup) getGroup(); if (group != null && ( oldBounds.width < getBounds().width || oldBounds.height < getBounds().height)) { group.calcBounds(); } } /** * Prevent underline events if underline does not change. * TODO: GEF should manage this after GEF 0.13.4 is included. */ public void setUnderline(boolean u) { if (getUnderline() == u) { return; } super.setUnderline(u); } /** * Prevent bold events if bold does not change. * TODO: GEF should manage this after GEF 0.13.4 is included. */ public void setBold(boolean b) { if (getBold() == b) { return; } super.setBold(b); } /** * Prevent italic events if italic does not change. * TODO: GEF should manage this after GEF 0.13.4 is included. */ public void setItalic(boolean i) { if (getItalic() == i) { return; } super.setItalic(i); } } /** * Copyright (C) 2012-2013 eBusiness Information (www.ebusinessinformation.fr) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed To in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.athomas.androidkickstartr; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import org.apache.commons.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.eclipse.egit.github.core.Repository; import org.eclipse.jgit.api.errors.GitAPIException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.athomas.androidkickstartr.util.GithubUtils; import com.athomas.androidkickstartr.util.StringUtils; @Path("/") public class Main { private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final String ERROR = "error"; private static final String SUCCESS = "success"; private static String GITHUB_SECRET; private static String GITHUB_ID; // Initialize the static { Properties prop = new Properties(); try { prop.load(Main.class.getClassLoader().getResourceAsStream("Github.properties")); GITHUB_ID = prop.getProperty("id"); GITHUB_SECRET = prop.getProperty("secret"); } catch (FileNotFoundException e) { LOGGER.error("problem during properties loading", e); } catch (IOException e) { LOGGER.error("problem during properties loading", e); } } @POST @Produces("application/zip") public Response go(// // State @FormParam("actionBarSherlock") boolean actionBarSherlock,// @FormParam("navigationType") String navigationType,// @FormParam("androidAnnotations") boolean androidAnnotations,// @FormParam("restTemplate") boolean restTemplate,// @FormParam("maven") boolean maven,// @FormParam("nineOldAndroids") boolean nineOldAndroids,// @FormParam("supportV4") boolean supportV4,// @FormParam("acra") boolean acra,// @FormParam("eclipse") boolean eclipse,// @FormParam("viewPager") boolean viewPager,// @FormParam("viewPagerIndicator") boolean viewPagerIndicator,// @FormParam("roboguice") boolean roboguice,// @FormParam("proguard") boolean proguard,// @FormParam("sample") boolean sample,// // Application @FormParam("packageName") String packageName,// @FormParam("name") String name,// @FormParam("activity") String activity,// @FormParam("activityLayout") String activityLayout,// // Github access token @FormParam("accessToken") String accessToken// ) { boolean listNavigation = false; boolean tabNavigation = false; boolean git = false; if (navigationType != null) { tabNavigation = navigationType.equals("tabNavigation"); listNavigation = navigationType.equals("listNavigation"); } if (StringUtils.isEmpty(packageName)) { packageName = "com.androidkickstarter.app"; } if (StringUtils.isEmpty(name)) { name = "MyApplication"; } if (StringUtils.isEmpty(activity)) { activity = "MainActivity"; } if (StringUtils.isEmpty(activityLayout)) { activityLayout = "activity_main"; } if (!StringUtils.isEmpty(accessToken)) { git = true; } if (viewPager && !actionBarSherlock && !viewPagerIndicator && !supportV4) { supportV4 = true; } AppDetails appDetails = new AppDetails.Builder().// // Parameters packageName(packageName).// name(name).// activity(activity).// activityLayout(activityLayout).// minSdk(8).// targetSdk(16).// permissions(new ArrayList()).// // Libraries actionBarSherlock(actionBarSherlock).// listNavigation(listNavigation).// tabNavigation(tabNavigation).// viewPager(viewPager).// viewPagerIndicator(viewPagerIndicator).// roboguice(roboguice).// androidAnnotations(androidAnnotations).// restTemplate(restTemplate). // maven(maven). // nineOldAndroids(nineOldAndroids). // supportV4(supportV4). // acra(acra). // eclipse(eclipse). // proguard(proguard). // sample(sample). // git(git). // build(); final Kickstartr kickstarter = new Kickstartr(appDetails); if (!git) { LOGGER.debug("No github asked"); final File file = kickstarter.zipify(); if (file == null) { return Response.serverError().build(); } StreamingOutput output = new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { try { FileUtils.copyFile(file, output); kickstarter.clean(); } catch (Exception e) { throw new WebApplicationException(e); } } }; return Response // .ok(output) // .header("Content-Length", file.length()) // .header("Content-Disposition", "attachment; filename=" + file.getName()) // .build(); } else { LOGGER.debug("Github output asked"); Repository repository = null; try { repository = kickstarter.githubify(accessToken); } catch (IOException e) { e.printStackTrace(); return Response.seeOther(GithubUtils.createAndroidKickstartRUriWithAccessToken(accessToken, ERROR, "Unable to create or access repository : " + e.getMessage())).build(); } catch (GitAPIException e) { e.printStackTrace(); return Response.seeOther(GithubUtils.createAndroidKickstartRUriWithAccessToken(accessToken, ERROR, "Unable to create or access repository : " + e.getMessage())).build(); } finally { kickstarter.clean(); } if (repository != null) return Response.seeOther(GithubUtils.createAndroidKickstartRUriWithAccessToken(accessToken, SUCCESS, "Repository successfully created! You can access it now at the following address : &repositoryUrl=" + repository.getHtmlUrl())).build(); else return Response.serverError().build(); } } @GET @Path("token") @Produces(MediaType.APPLICATION_JSON) public Response getAccessToken(@QueryParam("code") String code) throws ClientProtocolException, IOException, URISyntaxException { HttpClient httpclient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("https://github.com/login/oauth/access_token"); List nameValuePair = new ArrayList(3); nameValuePair.add(new BasicNameValuePair("client_id", GITHUB_ID)); nameValuePair.add(new BasicNameValuePair("client_secret", GITHUB_SECRET)); nameValuePair.add(new BasicNameValuePair("code", code)); postRequest.setEntity(new UrlEncodedFormEntity(nameValuePair)); HttpResponse response = httpclient.execute(postRequest); if (response.getStatusLine().getStatusCode() != 200) { return Response.temporaryRedirect(GithubUtils.createAndroidKickstartRUri(ERROR, "Unexpected status code : " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase())).build(); } else { HttpEntity entity = response.getEntity(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String line; while ((line = bufferedReader.readLine()) != null) { String accessToken = GithubUtils.findAccessTokenInString(line); if (accessToken != null) { return Response.temporaryRedirect(GithubUtils.createAndroidKickstartRUri(GithubUtils.ACCESS_TOKEN, accessToken)).build(); } } } return Response.temporaryRedirect(GithubUtils.createAndroidKickstartRUri(ERROR, "Couldn't retrieve access token")).build(); } } package com.simon.service.impl; import com.simon.common.service.impl.CrudServiceImpl; import com.simon.mapper.ResetPwdInfoMapper; import com.simon.model.ResetPwdInfo; import com.simon.repository.ResetPwdInfoRepository; import com.simon.service.ResetPwdInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author SimonSun * @create 2018-08-06 20:56:26 **/ @Service @Transactional(rollbackFor = {Exception.class}) public class ResetPwdInfoServiceImpl extends CrudServiceImpl implements ResetPwdInfoService { @Autowired private ResetPwdInfoMapper resetPwdInfoMapper; @Autowired private ResetPwdInfoRepository resetPwdInfoRepository; }//$Header: /home/cvs/iag/brian/mbari/src/main/java/org/mbari/util/SystemUtilities.java,v 1.1 2006/01/09 21:16:59 brian Exp $ package mbarix4j.util; import javax.swing.*; import java.awt.*; import java.lang.reflect.Method; import java.net.*; /** *

Static methods (i.e. functions) for general services.


* * @author : $Author: brian $ * @version : $Revision: 1.1 $ * *

* The Monterey Bay Aquarium Research Institute (MBARI) provides this * documentation and code "as is", with no warranty, express or * implied, of its quality or consistency. It is provided without support and * without obligation on the part of MBARI to assist in its use, correction, * modification, or enhancement. This information should not be published or * distributed to third parties without specific written permission from * MBARI.


* * Copyright 2002 MBARI.
* MBARI Proprietary Information. All rights reserved.



* */ public class SystemUtilities { public static URL getURL(String path) { class ClassOnCurrentClassLoader {}; Object c = new ClassOnCurrentClassLoader(); return c.getClass().getResource(path); // it looks relative to the class. // return c.getClass().getClassLoader().getResource(path); // it looks in the top level directories of your class path. } public static String getFile(String path) { return SystemUtilities.getURL(path).getFile(); } public static boolean isMacOS() { String osName = System.getProperty("os.name"); return osName.startsWith("Mac OS"); } public static boolean isWindowsOS() { String osName = System.getProperty("os.name"); return osName.startsWith("Windows"); } /** * Set a few common properties for the given application if we are running * under MacOS. Usage Example: * *
     * if (MacOSUtil.isMacOS()) {
     *   MacOSUtil.configureMacOSApplication("JabaDex");
     * }
     * 
* * @param appName - * the name of the Application. */ public static void configureMacOSApplication(String appName) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); //System.setProperty("apple.awt.fileDialogForDirectories", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", appName); } /** * Set common properties and dock image for the given application is we are running * on Mac OS X * @param appName The name of the Application * @param dockImagePath The String path of the image to use as the dock icon */ public static void configureMacOSApplication(String appName, String dockImagePath) { configureMacOSApplication(appName); try { // Use reflection to invoke Apple's proprietary methods Class clazz = Class.forName("com.apple.eawt.Application"); Method method = clazz.getMethod("getApplication", null); Object application = method.invoke(null, null); Method method2 = application.getClass().getMethod("setDockIconImage", Image.class); URL dockImageURL = "".getClass().getResource(dockImagePath); Image dockImage = new ImageIcon(dockImageURL).getImage(); method2.invoke(application, dockImage); } catch (Exception e) { // Do nothing } } /** * Open the systems web browser. * * @param url */ public static void openBrowserWithURL(URL url) { String osName = System.getProperty("os.name"); try { if (isMacOS()) { Class fileMgr = Class.forName("com.apple.eio.FileManager"); Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[]{String.class}); openURL.invoke(null, new Object[]{url.toExternalForm()}); } else if (osName.startsWith("Windows")) { Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); } else { //assume Unix or Linux String[] browsers = {"chrome", "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"}; String browser = null; for (int count = 0; count < browsers.length && browser == null; count++) { if (Runtime.getRuntime().exec( new String[]{"which", browsers[count]}).waitFor() == 0) { browser = browsers[count]; } } if (browser == null) { throw new RuntimeException("Could not find web browser"); } else { Runtime.getRuntime().exec(new String[]{browser, url.toExternalForm()}); } } } catch (Exception e) { throw new RuntimeException("Failed to open web browser", e); } } /** * Handle method for locating the jar that contains a particular class * * @param clazz The class of interest * @return the name of the jar file containing the class */ public static String findJarForClass(Class clazz) { String name = clazz.getName(); name = name.substring(name.lastIndexOf('.') + 1); String jar = clazz.getResource(name + ".class").toString(); //NOI18N return jar.substring(0, jar.indexOf('!')); } }package com.dialog.plus.utils; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.Log; import com.dialog.plus.R; /** * Created by Fawzy on 23,September,2019 * **/ public class FlagsUtil { private static final String FLAG_PREFIX = "flag_"; public static int getFlagByLanguage(String language) { switch (language) { //this should be sorted based on country name code. case "ad": //andorra return R.mipmap.flag_ad; case "ae": //united arab emirates return R.mipmap.flag_ae; case "af": //afghanistan return R.mipmap.flag_af; case "ag": //antigua & barbuda return R.mipmap.flag_ag; case "ai": //anguilla // Caribbean Islands return R.mipmap.flag_ai; case "al": //albania return R.mipmap.flag_al; case "am": //armenia return R.mipmap.flag_am; case "ao": //angola return R.mipmap.flag_ao; case "aq": //antarctica // custom return R.mipmap.flag_aq; case "ar": //argentina return R.mipmap.flag_ar; case "as": //American Samoa return R.mipmap.flag_as; case "at": //austria return R.mipmap.flag_at; case "au": //australia return R.mipmap.flag_au; case "aw": //aruba return R.mipmap.flag_aw; case "ax": //alan islands return R.mipmap.flag_ax; case "az": //azerbaijan return R.mipmap.flag_az; case "ba": //bosnia and herzegovina return R.mipmap.flag_ba; case "bb": //barbados return R.mipmap.flag_bb; case "bd": //bangladesh return R.mipmap.flag_bd; case "be": //belgium return R.mipmap.flag_be; case "bf": //burkina faso return R.mipmap.flag_bf; case "bg": //bulgaria return R.mipmap.flag_bg; case "bh": //bahrain return R.mipmap.flag_bh; case "bi": //burundi return R.mipmap.flag_bi; case "bj": //benin return R.mipmap.flag_bj; case "bl": //saint barthélemy return R.mipmap.flag_bl;// custom case "bm": //bermuda return R.mipmap.flag_bm; case "bn": //brunei darussalam // custom return R.mipmap.flag_bn; case "bo": //bolivia, plurinational state of return R.mipmap.flag_bo; case "br": //brazil return R.mipmap.flag_br; case "bs": //bahamas return R.mipmap.flag_bs; case "bt": //bhutan return R.mipmap.flag_bt; case "bw": //botswana return R.mipmap.flag_bw; case "by": //belarus return R.mipmap.flag_by; case "bz": //belize return R.mipmap.flag_bz; case "ca": //canada return R.mipmap.flag_ca; case "cc": //cocos (keeling) islands return R.mipmap.flag_cc;// custom case "cd": //congo, the democratic republic of the return R.mipmap.flag_cd; case "cf": //central african republic return R.mipmap.flag_cf; case "cg": //congo return R.mipmap.flag_cg; case "ch": //switzerland return R.mipmap.flag_ch; case "ci": //côte d\'ivoire return R.mipmap.flag_ci; case "ck": //cook islands return R.mipmap.flag_ck; case "cl": //chile return R.mipmap.flag_cl; case "cm": //cameroon return R.mipmap.flag_cm; case "cn": //china return R.mipmap.flag_cn; case "co": //colombia return R.mipmap.flag_co; case "cr": //costa rica return R.mipmap.flag_cr; case "cu": //cuba return R.mipmap.flag_cu; case "cv": //cape verde return R.mipmap.flag_cv; case "cw": //curaçao return R.mipmap.flag_cw; case "cx": //christmas island return R.mipmap.flag_cx; case "cy": //cyprus return R.mipmap.flag_cy; case "cz": //czech republic return R.mipmap.flag_cz; case "de": //germany return R.mipmap.flag_de; case "dj": //djibouti return R.mipmap.flag_dj; case "dk": //denmark return R.mipmap.flag_dk; case "dm": //dominica return R.mipmap.flag_dm; case "do": //dominican republic return R.mipmap.flag_do; case "dz": //algeria return R.mipmap.flag_dz; case "ec": //ecuador return R.mipmap.flag_ec; case "ee": //estonia return R.mipmap.flag_ee; case "eg": //egypt return R.mipmap.flag_eg; case "er": //eritrea return R.mipmap.flag_er; case "es": //spain return R.mipmap.flag_es; case "et": //ethiopia return R.mipmap.flag_et; case "fi": //finland return R.mipmap.flag_fi; case "fj": //fiji return R.mipmap.flag_fj; case "fk": //falkland islands (malvinas) return R.mipmap.flag_fk; case "fm": //micronesia, federated states of return R.mipmap.flag_fm; case "fo": //faroe islands return R.mipmap.flag_fo; case "fr": //france return R.mipmap.flag_fr; case "ga": //gabon return R.mipmap.flag_ga; case "gb": //united kingdom return R.mipmap.flag_gb; case "gd": //grenada return R.mipmap.flag_gd; case "ge": //georgia return R.mipmap.flag_ge; case "gf": //guyane return R.mipmap.flag_gf; case "gg": //Guernsey return R.mipmap.flag_gg; case "gh": //ghana return R.mipmap.flag_gh; case "gi": //gibraltar return R.mipmap.flag_gi; case "gl": //greenland return R.mipmap.flag_gl; case "gm": //gambia return R.mipmap.flag_gm; case "gn": //guinea return R.mipmap.flag_gn; case "gp": //guadeloupe return R.mipmap.flag_gp; case "gq": //equatorial guinea return R.mipmap.flag_gq; case "gr": //greece return R.mipmap.flag_gr; case "gt": //guatemala return R.mipmap.flag_gt; case "gu": //Guam return R.mipmap.flag_gu; case "gw": //guinea-bissau return R.mipmap.flag_gw; case "gy": //guyana return R.mipmap.flag_gy; case "hk": //hong kong return R.mipmap.flag_hk; case "hn": //honduras return R.mipmap.flag_hn; case "hr": //croatia return R.mipmap.flag_hr; case "ht": //haiti return R.mipmap.flag_ht; case "hu": //hungary return R.mipmap.flag_hu; case "id": //indonesia return R.mipmap.flag_id; case "ie": //ireland return R.mipmap.flag_ie; case "il": //israel return R.mipmap.flag_il; case "im": //isle of man return R.mipmap.flag_im; // custom case "is": //Iceland return R.mipmap.flag_is; case "in": //india return R.mipmap.flag_in; case "io": //British indian ocean territory return R.mipmap.flag_io; case "iq": //iraq return R.mipmap.flag_iq; case "ir": //iran, islamic republic of return R.mipmap.flag_ir; case "it": //italy return R.mipmap.flag_it; case "je": //Jersey return R.mipmap.flag_je; case "jm": //jamaica return R.mipmap.flag_jm; case "jo": //jordan return R.mipmap.flag_jo; case "jp": //japan return R.mipmap.flag_jp; case "ke": //kenya return R.mipmap.flag_ke; case "kg": //kyrgyzstan return R.mipmap.flag_kg; case "kh": //cambodia return R.mipmap.flag_kh; case "ki": //kiribati return R.mipmap.flag_ki; case "km": //comoros return R.mipmap.flag_km; case "kn": //st kitts & nevis return R.mipmap.flag_kn; case "kp": //north korea return R.mipmap.flag_kp; case "kr": //south korea return R.mipmap.flag_kr; case "kw": //kuwait return R.mipmap.flag_kw; case "ky": //Cayman_Islands return R.mipmap.flag_ky; case "kz": //kazakhstan return R.mipmap.flag_kz; case "la": //lao people\'s democratic republic return R.mipmap.flag_la; case "lb": //lebanon return R.mipmap.flag_lb; case "lc": //st lucia return R.mipmap.flag_lc; case "li": //liechtenstein return R.mipmap.flag_li; case "lk": //sri lanka return R.mipmap.flag_lk; case "lr": //liberia return R.mipmap.flag_lr; case "ls": //lesotho return R.mipmap.flag_ls; case "lt": //lithuania return R.mipmap.flag_lt; case "lu": //luxembourg return R.mipmap.flag_lu; case "lv": //latvia return R.mipmap.flag_lv; case "ly": //libya return R.mipmap.flag_ly; case "ma": //morocco return R.mipmap.flag_ma; case "mc": //monaco return R.mipmap.flag_mc; case "md": //moldova, republic of return R.mipmap.flag_md; case "me": //montenegro return R.mipmap.flag_me;// custom case "mf": return R.mipmap.flag_mf; case "mg": //madagascar return R.mipmap.flag_mg; case "mh": //marshall islands return R.mipmap.flag_mh; case "mk": //macedonia, the former yugoslav republic of return R.mipmap.flag_mk; case "ml": //mali return R.mipmap.flag_ml; case "mm": //myanmar return R.mipmap.flag_mm; case "mn": //mongolia return R.mipmap.flag_mn; case "mo": //macao return R.mipmap.flag_mo; case "mp": // Northern mariana islands return R.mipmap.flag_mp; case "mq": //martinique return R.mipmap.flag_yt; case "mr": //mauritania return R.mipmap.flag_mr; case "ms": //montserrat return R.mipmap.flag_ms; case "mt": //malta return R.mipmap.flag_mt; case "mu": //mauritius return R.mipmap.flag_mu; case "mv": //maldives return R.mipmap.flag_mv; case "mw": //malawi return R.mipmap.flag_mw; case "mx": //mexico return R.mipmap.flag_mx; case "my": //malaysia return R.mipmap.flag_my; case "mz": //mozambique return R.mipmap.flag_mz; case "na": //namibia return R.mipmap.flag_na; case "nc": //new caledonia return R.mipmap.flag_nc;// custom case "ne": //niger return R.mipmap.flag_ne; case "nf": //Norfolk return R.mipmap.flag_nf; case "ng": //nigeria return R.mipmap.flag_ng; case "ni": //nicaragua return R.mipmap.flag_ni; case "nl": //netherlands return R.mipmap.flag_nl; case "no": //norway return R.mipmap.flag_no; case "np": //nepal return R.mipmap.flag_np; case "nr": //nauru return R.mipmap.flag_nr; case "nu": //niue return R.mipmap.flag_nu; case "nz": //new zealand return R.mipmap.flag_nz; case "om": //oman return R.mipmap.flag_om; case "pa": //panama return R.mipmap.flag_pa; case "pe": //peru return R.mipmap.flag_pe; case "pf": //french polynesia return R.mipmap.flag_pf; case "pg": //papua new guinea return R.mipmap.flag_pg; case "ph": //philippines return R.mipmap.flag_ph; case "pk": //pakistan return R.mipmap.flag_pk; case "pl": //poland return R.mipmap.flag_pl; case "pm": //saint pierre and miquelon return R.mipmap.flag_pm; case "pn": //pitcairn return R.mipmap.flag_pn; case "pr": //puerto rico return R.mipmap.flag_pr; case "ps": //palestine return R.mipmap.flag_ps; case "pt": //portugal return R.mipmap.flag_pt; case "pw": //palau return R.mipmap.flag_pw; case "py": //paraguay return R.mipmap.flag_py; case "qa": //qatar return R.mipmap.flag_qa; case "re": //la reunion return R.mipmap.flag_yt; // no exact flag found case "ro": //romania return R.mipmap.flag_ro; case "rs": //serbia return R.mipmap.flag_rs; // custom case "ru": //russian federation return R.mipmap.flag_ru; case "rw": //rwanda return R.mipmap.flag_rw; case "sa": //saudi arabia return R.mipmap.flag_sa; case "sb": //solomon islands return R.mipmap.flag_sb; case "sc": //seychelles return R.mipmap.flag_sc; case "sd": //sudan return R.mipmap.flag_sd; case "se": //sweden return R.mipmap.flag_se; case "sg": //singapore return R.mipmap.flag_sg; case "sh": //saint helena, ascension and tristan da cunha return R.mipmap.flag_sh; // custom case "si": //slovenia return R.mipmap.flag_si; case "sk": //slovakia return R.mipmap.flag_sk; case "sl": //sierra leone return R.mipmap.flag_sl; case "sm": //san marino return R.mipmap.flag_sm; case "sn": //senegal return R.mipmap.flag_sn; case "so": //somalia return R.mipmap.flag_so; case "sr": //suriname return R.mipmap.flag_sr; case "ss": //south sudan return R.mipmap.flag_ss; case "st": //sao tome and principe return R.mipmap.flag_st; case "sv": //el salvador return R.mipmap.flag_sv; case "sx": //sint maarten return R.mipmap.flag_sx; case "sy": //syrian arab republic return R.mipmap.flag_sy; case "sz": //swaziland return R.mipmap.flag_sz; case "tc": //turks & caicos islands return R.mipmap.flag_tc; case "td": //chad return R.mipmap.flag_td; case "tg": //togo return R.mipmap.flag_tg; case "th": //thailand return R.mipmap.flag_th; case "tj": //tajikistan return R.mipmap.flag_tj; case "tk": //tokelau return R.mipmap.flag_tk; // custom case "tl": //timor-leste return R.mipmap.flag_tl; case "tm": //turkmenistan return R.mipmap.flag_tm; case "tn": //tunisia return R.mipmap.flag_tn; case "to": //tonga return R.mipmap.flag_to; case "tr": //turkey return R.mipmap.flag_tr; case "tt": //trinidad & tobago return R.mipmap.flag_tt; case "tv": //tuvalu return R.mipmap.flag_tv; case "tw": //taiwan, province of china return R.mipmap.flag_tw; case "tz": //tanzania, united republic of return R.mipmap.flag_tz; case "ua": //ukraine return R.mipmap.flag_ua; case "ug": //uganda return R.mipmap.flag_ug; case "us": //united states return R.mipmap.flag_us; case "uy": //uruguay return R.mipmap.flag_uy; case "uz": //uzbekistan return R.mipmap.flag_uz; case "va": //holy see (vatican city state) return R.mipmap.flag_va; case "vc": //st vincent & the grenadines return R.mipmap.flag_vc; case "ve": //venezuela, bolivarian republic of return R.mipmap.flag_ve; case "vg": //british virgin islands return R.mipmap.flag_vg; case "vi": //us virgin islands return R.mipmap.flag_vi; case "vn": //vietnam return R.mipmap.flag_vn; case "vu": //vanuatu return R.mipmap.flag_vu; case "wf": //wallis and futuna return R.mipmap.flag_wf; case "ws": //samoa return R.mipmap.flag_ws; case "xk": //kosovo return R.mipmap.flag_xk; case "ye": //yemen return R.mipmap.flag_ye; case "yt": //mayotte return R.mipmap.flag_yt; // no exact flag found case "za": //south africa return R.mipmap.flag_za; case "zm": //zambia return R.mipmap.flag_zm; case "zw": //zimbabwe return R.mipmap.flag_zw; default: return R.mipmap.flag_transparent; } } public static Drawable getFlagByLanguage(Context context, String language) { final int resourceId = context.getResources().getIdentifier(FLAG_PREFIX + language, "mipmap", context.getPackageName()); try { return context.getResources().getDrawable(resourceId); } catch (Exception e) { Log.e("dialogPlus", "no drawable with name " + FLAG_PREFIX + language); return null; } } } import javax.swing.*; import java.awt.event.*; import java.lang.Math; public class ScoreCalc extends JFrame { JLabel sub1, sub2, sub3, sub4, sub5, sub6, total, percent, grade; JTextField tfsub1, tfsub2, tfsub3, tfsub4, tfsub5, tfsub6; JButton btn; public ScoreCalc() { sub1 = new JLabel("English"); sub2 = new JLabel("Mathematic"); sub3 = new JLabel("Physics"); sub4 = new JLabel("Chemistry"); sub5 = new JLabel("Electronics/CS"); sub6 = new JLabel("Work Experience"); total = new JLabel("Total >> "); percent = new JLabel("Percentage >> "); grade = new JLabel("Grade >> "); tfsub1 = new JTextField(); tfsub2 = new JTextField(); tfsub3 = new JTextField(); tfsub4 = new JTextField(); tfsub5 = new JTextField(); tfsub6 = new JTextField(); sub1.setBounds(10, 10, 100, 20); sub2.setBounds(10, 30, 100, 20); sub3.setBounds(10, 50, 100, 20); sub4.setBounds(10, 70, 100, 20); sub5.setBounds(10, 90, 100, 20); sub6.setBounds(10, 110, 100, 20); tfsub1.setBounds(180, 10, 50, 20); tfsub2.setBounds(180, 30, 50, 20); tfsub3.setBounds(180, 50, 50, 20); tfsub4.setBounds(180, 70, 50, 20); tfsub5.setBounds(180, 90, 50, 20); tfsub6.setBounds(180, 110, 50, 20); total.setBounds(10, 130, 200, 20); percent.setBounds(10, 150, 300, 20); grade.setBounds(10, 170, 200, 20); btn = new JButton("Calculate Score"); btn.setBounds(10, 190, 200, 20); add(sub1); add(sub2); add(sub3); add(sub4); add(sub5); add(sub6); add(tfsub1); add(tfsub2); add(tfsub3); add(tfsub4); add(tfsub5); add(tfsub6); add(total); add(percent); add(grade); add(btn); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double m1 = Double.parseDouble(tfsub1.getText()); double m2 = Double.parseDouble(tfsub2.getText()); double m3 = Double.parseDouble(tfsub3.getText()); double m4 = Double.parseDouble(tfsub4.getText()); double m5 = Double.parseDouble(tfsub5.getText()); double m6 = Double.parseDouble(tfsub6.getText()); double t = m1 + m2 + m3 + m4 + m5 + m6; double p = Math.round(t * 100.0) / 600.0; String g = ""; if (p > 90) g = "Outstanding"; else if (p > 70 && p <= 90) g = "Very Good"; else if (p > 50 && p <= 70) g = "Good"; else if (p >= 35 && p <= 50) g = "Needs Improvement"; else if (p < 35) g = "Fail"; total.setText("Total >> " + t + "/600"); percent.setText("Percentage >> " + p + "%"); grade.setText("Grade >> " + g); } }); setTitle("Score Calculator"); setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 300); setVisible(true); } public static void main(String[] args) { new ScoreCalc(); } } LTNSz/GIS0 package com.our.websocket.util; import com.our.websocket.entity.DoubleStringPair; import com.our.websocket.entity.Vertex; public class MathUtil { public static double distanceSquare(Vertex p1, Vertex p2) { return Math.pow(p1.getLatitude() - p2.getLatitude(), 2) + Math.pow(p1.getLongitude() - p2.getLongitude(), 2); } public static double distanceSquare(double x1,double y1,double x2,double y2) { return Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2); } public static double distance(double x1,double y1,double x2,double y2) { return Math.sqrt(distanceSquare(x1,y1,x2,y2)); } public static double distance(DoubleStringPair p1, DoubleStringPair p2) { double x1 = Double.parseDouble(p1.getX()); double y1 = Double.parseDouble(p1.getY()); double x2 = Double.parseDouble(p2.getX()); double y2 = Double.parseDouble(p2.getY()); return distance(x1,y1,x2,y2); } } Reflexian/ReflexianAPI package com.reflexian.publicapi.exceptions; public class LicenseCreationException extends ReflexianException { public LicenseCreationException(String error){ super(error); } } google/cloud/retail/v2/google-cloud-retail-v2-java/proto-google-cloud-retail-v2-java/src/main/java/com/google/cloud/retail/v2/PredictionServiceProto.java // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/retail/v2/prediction_service.proto package com.google.cloud.retail.v2; public final class PredictionServiceProto { private PredictionServiceProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_retail_v2_PredictRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_retail_v2_PredictRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_retail_v2_PredictRequest_ParamsEntry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_retail_v2_PredictRequest_ParamsEntry_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_retail_v2_PredictRequest_LabelsEntry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_retail_v2_PredictRequest_LabelsEntry_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_retail_v2_PredictResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_retail_v2_PredictResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_retail_v2_PredictResponse_PredictionResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_retail_v2_PredictResponse_PredictionResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_retail_v2_PredictResponse_PredictionResult_MetadataEntry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_retail_v2_PredictResponse_PredictionResult_MetadataEntry_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n/google/cloud/retail/v2/prediction_serv" + "ice.proto\022\026google.cloud.retail.v2\032\034googl" + "e/api/annotations.proto\032\027google/api/clie" + "nt.proto\032\037google/api/field_behavior.prot" + "o\032\'google/cloud/retail/v2/user_event.pro" + "to\032\034google/protobuf/struct.proto\"\260\003\n\016Pre" + "dictRequest\022\026\n\tplacement\030\001 \001(\tB\003\340A\002\022:\n\nu" + "ser_event\030\002 \001(\0132!.google.cloud.retail.v2" + ".UserEventB\003\340A\002\022\021\n\tpage_size\030\003 \001(\005\022\022\n\npa" + "ge_token\030\004 \001(\t\022\016\n\006filter\030\005 \001(\t\022\025\n\rvalida" + "te_only\030\006 \001(\010\022B\n\006params\030\007 \003(\01322.google.c" + "loud.retail.v2.PredictRequest.ParamsEntr" + "y\022B\n\006labels\030\010 \003(\01322.google.cloud.retail." + "v2.PredictRequest.LabelsEntry\032E\n\013ParamsE" + "ntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026.googl" + "e.protobuf.Value:\0028\001\032-\n\013LabelsEntry\022\013\n\003k" + "ey\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001\"\347\002\n\017PredictR" + "esponse\022I\n\007results\030\001 \003(\01328.google.cloud." + "retail.v2.PredictResponse.PredictionResu" + "lt\022\031\n\021attribution_token\030\002 \001(\t\022\023\n\013missing" + "_ids\030\003 \003(\t\022\025\n\rvalidate_only\030\004 \001(\010\032\301\001\n\020Pr" + "edictionResult\022\n\n\002id\030\001 \001(\t\022X\n\010metadata\030\002" + " \003(\0132F.google.cloud.retail.v2.PredictRes" + "ponse.PredictionResult.MetadataEntry\032G\n\r" + "MetadataEntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(" + "\0132\026.google.protobuf.Value:\0028\0012\216\002\n\021Predic" + "tionService\022\255\001\n\007Predict\022&.google.cloud.r" + "etail.v2.PredictRequest\032\'.google.cloud.r" + "etail.v2.PredictResponse\"Q\202\323\344\223\002K\"F/v2/{p" + "lacement=projects/*/locations/*/catalogs" + "/*/placements/*}:predict:\001*\032I\312A\025retail.g" + "oogleapis.com\322A.https://www.googleapis.c" + "om/auth/cloud-platformB\313\001\n\032com.google.cl" + "oud.retail.v2B\026PredictionServiceProtoP\001Z" + ". All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.geo; import boofcv.abst.geo.Triangulate2ViewsMetric; import boofcv.factory.geo.ConfigTriangulation; import boofcv.factory.geo.FactoryMultiView; import georegression.struct.point.Point2D_F64; import georegression.struct.point.Point3D_F64; import georegression.struct.se.Se3_F64; import georegression.transform.se.SePointOps_F64; /** *

* Given two views of the same point and a known 3D transform checks to see if the point is in front * of both cameras. This is the positive depth constraint. A class is provided instead of a function * to reduce computational overhead each time the function is called. Memory only needs to be * declared once. Also less chance of messing up and only checking one view instead of two views * if you use this class. *

* *

* COORDINATE SYSTEM: Right handed coordinate system with +z is pointing along the camera's optical axis, *

* * @author */ public class PositiveDepthConstraintCheck { // algorithm used to triangulate point location Triangulate2ViewsMetric triangulate; // location of triangulated point in 3D space Point3D_F64 P = new Point3D_F64(); public PositiveDepthConstraintCheck( Triangulate2ViewsMetric triangulate ) { this.triangulate = triangulate; } public PositiveDepthConstraintCheck() { this(FactoryMultiView.triangulate2ViewMetric(new ConfigTriangulation(ConfigTriangulation.Type.GEOMETRIC))); } /** * Checks to see if a single point meets the constraint. * * @param viewA View of the 3D point from the first camera. Calibrated coordinates. * @param viewB View of the 3D point from the second camera. Calibrated coordinates. * @param fromAtoB Transform from the B to A camera frame. * @return If the triangulated point appears in front of both cameras. */ public boolean checkConstraint( Point2D_F64 viewA, Point2D_F64 viewB, Se3_F64 fromAtoB ) { if (!triangulate.triangulate(viewA, viewB, fromAtoB, P)) { throw new RuntimeException("Triangulate failed. p1=" + viewA + " p2=" + viewB); } if (P.z > 0) { SePointOps_F64.transform(fromAtoB, P, P); return P.z > 0; } return false; } } import java.util.List; public class TeamPhotoDay { /* 19.8 : A team photo. Each team has 11 players, and each player in the back row is taller than the corresponding player in the front row. Let G be the DAG with vertices corresponding to the teams asfollows and edgesfrom vertex X to Y iff Team X can be placed behind Team Y. Every sequence of teams where a team can be placed behind its predecessor corresponds to a path in G. To find the longest such sequence, we simply need to find the longest path in the DAG G. We can do this, for example, by topologically ordering the vertices in G; the longest path terminating at vertex v is the maximum of the longest paths terminating at v'sfan-ins concatenated with v itself. The topological ordering computation is0{\V\ + |E|) and dominates the computation time. Clearly |V| is the number of teams. The number of edges E depends on the heights, but can be as high as0(\V\2), e.g., when there is a path of length |V|— 1. */ public static class GraphVertex { public List edges = new ArrayList<>(); public int maxDistance = 1; public boolean visited = false; } public static int findLargestNumberTeams(List G) { Deque orderedVertices = buildTopologicalOrdering(G); return findLongestPath(orderedVertices); } private static Deque buildTopologicalOrdering( List G) { Deque orderedVertices = new LinkedList<>(); for (GraphVertex g : G) { if (!g.visited) { DFS(g, orderedVertices); } } return orderedVertices; } private static int findLongestPath(Deque orderedVertices) { int maxDistance =0; while (!orderedVertices.isEmpty()) { GraphVertex u = orderedVertices.peekFirst(); maxDistance = Math.max(maxDistance, u.maxDistance); for (GraphVertex v : u.edges) { v.maxDistance = Math.max(v.maxDistance, u.maxDistance + 1); } orderedVertices.removeFirst(); } return maxDistance; } private static void DFS(GraphVertex cur, Deque orderedVertices) { cur.visited = true; for (GraphVertex next : cur.edges) { if (!next.visited) { DFS(next, orderedVertices); } } orderedVertices.addFirst(cur); } } package com.spring.aurora.entity; import com.spring.aurora.model.Customer; import com.spring.aurora.model.Product; public class ProductPriceEntity { private String priceId; private Customer customer; private Product product; private Double sellingPrice; public ProductPriceEntity(String priceId, Customer customer, Product product, Double sellingPrice) { this.priceId = priceId; this.customer = customer; this.product = product; this.sellingPrice = sellingPrice; } public String getPriceId() { return priceId; } public void setPriceId(String priceId) { this.priceId = priceId; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public Double getSellingPrice() { return sellingPrice; } public void setSellingPrice(Double sellingPrice) { this.sellingPrice = sellingPrice; } } package com.wilutions.jsfs; /* * Serializer for com.wilutions.jsfs.BRequest_FileSystemNotify_notify * * THIS FILE HAS BEEN GENERATED BY class byps.gen.j.GenSerStructJson DO NOT MODIFY. */ import byps.*; // DEBUG // isEnum=false // isFinal=true // isInline=false // #members=1 // checkpoint byps.gen.j.GenSerStruct:274 @SuppressWarnings("all") public class JSerializer_481066845 extends JSerializer_Object { public final static BSerializer instance = new JSerializer_481066845(); public JSerializer_481066845() { super(481066845); } public JSerializer_481066845(int typeId) { super(typeId); } @Override public void internalWrite(final Object obj1, final BOutputJson bout, final BBufferJson bbuf) throws BException { final BRequest_FileSystemNotify_notify obj = (BRequest_FileSystemNotify_notify)obj1; bout.writeObj("notifyInfo",obj.notifyInfo, false, null); } @Override public Object internalRead(final Object obj1, final BInputJson bin) throws BException { final BRequest_FileSystemNotify_notify obj = (BRequest_FileSystemNotify_notify)(obj1 != null ? obj1 : bin.onObjectCreated(new BRequest_FileSystemNotify_notify())); final BJsonObject js = bin.currentObject; obj.notifyInfo = (com.wilutions.jsfs.NotifyInfo)bin.readObj("notifyInfo", false, null); return obj; } } import javax.annotation.Nonnull; import javax.annotation.Nullable; class Test { @Nonnull public String noNull( @Nullable String text) { return text == null ? "" : text; } }/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* test @bug 5039416 6404008 @summary REGRESSION: Extra mouse click dispatched after press-drag- release sequence. @library ../../regtesthelpers @build Util @author andrei.dmitriev area=awt.event @run applet ExtraMouseClick.html */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; import test.java.awt.regtesthelpers.Util; //** // Here are two values of smugde used in this test (2 and 5). They should be on // different sides from value 4 (smudge distance on both toolkits). // Note that this test may not fail easily. But it must always pass on // patched workspace. //** public class ExtraMouseClick extends Applet { Frame frame = new Frame("Extra Click After MouseDrag"); final int TRIALS = 10; final int SMUDGE_WIDTH = 4; final int SMUDGE_HEIGHT = 4; Robot robot; Point fp; //frame's location on screen boolean dragged = false; boolean clicked = false; boolean pressed = false; boolean released = false; public void init() { this.setLayout (new BorderLayout ()); frame.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { System.out.println("MousePressed"); pressed = true; } public void mouseReleased(MouseEvent e) { System.out.println("MouseReleased"); released = true; } public void mouseClicked(MouseEvent e) { System.out.println("MouseClicked!!!!"); clicked = true; } }); frame.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { System.out.println("MouseDragged--"+e); dragged = true; } public void mouseMoved(MouseEvent e) { } }); }//End init() public void start () { frame.setSize(480, 300); frame.setVisible(true); try{ robot = new Robot(); }catch(AWTException e){ throw new RuntimeException(e); } Util.waitForIdle(robot); //a time to show Frame fp = frame.getLocationOnScreen(); for (int i = 0; i< TRIALS; i++){ checkClicked(); clearFlags(); } for (int i = 0; i< TRIALS; i++){ oneDrag(2); clearFlags(); } for (int i = 0; i< TRIALS; i++){ oneDrag(5); clearFlags(); } for (int i = 0; i< TRIALS; i++){ oneDrag(70); clearFlags(); } //Check that no Drag event occur in the SMUDGE area String sToolkit = Toolkit.getDefaultToolkit().getClass().getName(); System.out.println("Toolkit == "+sToolkit); if ("sun.awt.windows.WToolkit".equals(sToolkit)){ int dragWidth = ((Integer)Toolkit.getDefaultToolkit(). getDesktopProperty("win.drag.width")).intValue(); int dragHeight = ((Integer)Toolkit.getDefaultToolkit(). getDesktopProperty("win.drag.height")).intValue(); System.out.println("dragWidth=="+dragWidth+":: dragHeight=="+dragHeight); // DragWidth and dragHeight may be equal to 1. In that case the SMUDGE rectangle // narrowed into 1x1 pixel and we can't drag a mouse in it. // In that case we may skip following testcase but I'd prefer if we move mouse on 1 pixel only. // And that should pass as well. dragWidth = dragWidth > 1? dragWidth/2:1; dragHeight = dragHeight > 1? dragHeight/2:1; for (int i = 0; i< TRIALS; i++){ smallWin32Drag(dragWidth, dragHeight); clearFlags(); } }else{ for (int i = 0; i< TRIALS; i++){ smallDrag(SMUDGE_WIDTH - 1, SMUDGE_HEIGHT - 1); //on Motif and XAWT SMUDGE area is 4-pixels wide clearFlags(); } } System.out.println("Test passed."); }// start() public void oneDrag(int pixels){ robot.mouseMove(fp.x + frame.getWidth()/2, fp.y + frame.getHeight()/2 ); //drag for a short distance robot.mousePress(InputEvent.BUTTON1_MASK ); for (int i = 1; ieurekaclinical/umls-query0 /* * #%L * UMLSQuery * %% * Copyright (C) 2012 - 2013 Emory University * %% * 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. * #L% */ package edu.emory.cci.aiw.umls; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents an Atom Unique Identifier (AUI) in a UMLS query. AUIs must match * the regular expression A\d{7,8} (the letter 'A' followed by 7 or * 8 digits). Implements several marker interfaces that allow objects of this * type to be used as a search key in various UMLS queries. * * @author * */ public final class AtomUID extends AbstractUMLSSearchUID implements CUIQuerySearchUID, AUIQuerySearchUID, STRQuerySearchUID, TUIQuerySearchUID, SABQuerySearchUID, ParentsQuerySearchUID, NeighborQuerySearchUID, MapToIdQuerySearchUID, CodeQuerySearchUID { private static Pattern auidPattern; /* * An empty AUI, used only within this package when only the key name is * required */ static final AtomUID EMPTY_AUI = new AtomUID(""); /* * the regex all AUIs must match */ static { auidPattern = Pattern.compile("A\\d{7,8}"); } private AtomUID(String auid) { super(auid); } /** * Creates and returns a new AtomUID from the given string. The * string must match the AUI format, which is given by the regular * expression A\d{7} (the letter 'A' followed by exactly 7 or 8 * digits). If the string does not match the regex, then a * MalformedUMLSUniqueIdentifierException is thrown. * * @param auid * the string representing the AUI to be created * @return an AtomUID whose value is the given string * @throws MalformedUMLSUniqueIdentifierException * if the string argument does not match the AUI format */ public static AtomUID fromString(String auid) throws MalformedUMLSUniqueIdentifierException { Matcher m = auidPattern.matcher(auid); if (m.matches()) { return new AtomUID(auid); } else { throw new MalformedUMLSUniqueIdentifierException( "Atom Unique Identifiers must consist of the letter " + "'A' followed by 7 or 8 digits: " + auid); } } @Override public String getKeyName() { return "AUI"; } @Override public boolean equals(Object o) { if (o instanceof AtomUID) { return this.getValue().equals(((AtomUID) o).getValue()); } return false; } } references/bcb_chosen_clones/default#122106#545#596.java public static void main(String[] a) { port = (new Integer(a[0])).intValue(); System.out.println("Port " + port); try { skt = new Socket("localhost", port); out = new PrintWriter(skt.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(skt.getInputStream())); stdIn = new BufferedReader(new InputStreamReader(System.in)); out.println("app __GUI__"); String line = in.readLine().trim(); System.out.println("start line=" + line); StringTokenizer st = new StringTokenizer(line); temp_dir = st.nextToken(); take_screenshots = st.nextToken().equals("True"); createAndShowGUI(); while (true) { System.out.println("waiting for input from client"); line = in.readLine().trim(); System.out.println("line=" + line); st = new StringTokenizer(line); if (st.countTokens() == 0) { continue; } String cmd = st.nextToken().toLowerCase(); Vector args = new Vector(); while (st.hasMoreTokens()) { args.addElement(st.nextToken()); } if (cmd.equals("app_start")) { handleAppStart(args); } else if (cmd.equals("format")) { handleFormat(args); } else if (cmd.equals("app_stop")) { handleAppStop(args); } else if (cmd.equals("warn_user")) { handleWarnUser(args); } else if (cmd.equals("report_bug_on_shortcut")) { reportBug(); } else if (cmd.equals("report_not_bug_on_shortcut")) { reportNotBug(); } else if (cmd.equals("report_not_bug_on_quit?")) { handleReportNotBugOnQuit(args); } else if (cmd.equals("nearest_neighbors")) { handleNearestNeighbors(args); } else { System.out.println("Unrecognized command " + cmd + "."); } } } catch (Exception e) { System.out.println(e); } } PageRedirectingServlet/src/com/bridgelabz/pageredirecting/RedirectingServlet.java package com.bridgelabz.pageredirecting; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RedirectingServlet extends HttpServlet{ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String name=request.getParameter("name"); response.sendRedirect("http://www.google.co.in#q="+name); } } /* * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://duracloud.org/license/ */ package org.duracloud.chunk; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.security.DigestInputStream; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.input.AutoCloseInputStream; import org.duracloud.chunk.error.NotFoundException; import org.duracloud.chunk.stream.ChunkInputStream; import org.duracloud.chunk.writer.AddContentResult; import org.duracloud.chunk.writer.ContentWriter; import org.duracloud.common.error.DuraCloudRuntimeException; import org.duracloud.common.util.ChecksumUtil; import org.duracloud.common.util.ExceptionUtil; import org.duracloud.storage.util.StorageProviderUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class provides the ability to loop over a directory of content which * may include files over 5-GB in size, chunk, and push them to a DataStore * encapsulated by the member: ContentWriter. * A ContentWriter may push to any DataStore, such as: * - a filesystem or * - a DuraCloud space * * @author * Date: Feb 4, 2010 */ public class FileChunker { private final Logger log = LoggerFactory.getLogger(FileChunker.class); private ContentWriter contentWriter; private FileChunkerOptions options; public FileChunker(ContentWriter contentWriter) { this(contentWriter, new FileChunkerOptions()); } public FileChunker(ContentWriter contentWriter, FileChunkerOptions options) { this.contentWriter = contentWriter; this.options = options; } protected void writeReport(File outputFile) { StringBuilder sb = new StringBuilder(); if (!outputFile.exists()) { sb.append("spaceId,contentId,md5,size,state\n"); } OutputStream outputStream = getOutputStream(outputFile); List results = contentWriter.getResults(); for (AddContentResult result : results) { sb.append(result.getSpaceId()); sb.append(","); sb.append(result.getContentId()); sb.append(","); sb.append(result.getMd5()); sb.append(","); sb.append(result.getContentSize()); sb.append(","); sb.append(result.getState().name()); sb.append("\n"); } try { outputStream.write(sb.toString().getBytes()); } catch (IOException e) { throw new DuraCloudRuntimeException(e); } finally { IOUtils.closeQuietly(outputStream); } } private OutputStream getOutputStream(File outputFile) { boolean append = true; try { return new FileOutputStream(outputFile, append); } catch (IOException e) { throw new DuraCloudRuntimeException(e); } } /** * This method pushes the content file to the space destSpaceId with the * content ID destContentId * * @param destSpaceId of content destination * @param destContentId of content * @param fileChecksum MD5 checksum of file or null if not known * @param file to add */ public void addContent(String destSpaceId, String destContentId, String fileChecksum, File file) { Map properties = StorageProviderUtil.createContentProperties(file.getAbsolutePath(), null); addContent(destSpaceId, destContentId, fileChecksum, file.length(), getInputStream(file), properties); } /** * This method pushes the content file to the space destSpaceId with the * content ID destContentId * * @param destSpaceId of content destination * @param destContentId of content * @param fileChecksum MD5 checksum of file or null if not known * @param stream to add * @param properties user-defined properties associated with content */ public void addContent(String destSpaceId, String destContentId, String fileChecksum, long fileSize, InputStream stream, Map properties) { try { doAddContent(destSpaceId, destContentId, fileChecksum, fileSize, getInputStream(stream), properties); } catch (NotFoundException e) { throw new DuraCloudRuntimeException(e); } } /** * This method loops the arg baseDir and pushes the found content to the * arg destSpace. * * @param baseDir of content to push to DataStore * @param destSpaceId of content destination */ protected void addContentFrom(File baseDir, String destSpaceId) { Collection files = listFiles(baseDir, options.getFileFilter(), options.getDirFilter()); for (File file : files) { try { doAddContent(baseDir, destSpaceId, file); } catch (Exception e) { StringBuilder sb = new StringBuilder("Error: "); sb.append("Unable to addContentFrom ["); sb.append(baseDir); sb.append(", "); sb.append(destSpaceId); sb.append("] : "); sb.append(e.getMessage()); sb.append("\n"); sb.append(ExceptionUtil.getStackTraceAsString(e)); log.error(sb.toString()); } } } private void doAddContent(File baseDir, String destSpaceId, File file) throws NotFoundException { Map properties = StorageProviderUtil.createContentProperties(file.getAbsolutePath(), null); String destContentId = getContentId(baseDir, file); InputStream stream = getInputStream(file); doAddContent(destSpaceId, destContentId, null, file.length(), stream, properties); } private void doAddContent(String destSpaceId, String destContentId, String fileChecksum, long fileSize, InputStream stream, Map properties) throws NotFoundException { long maxChunkSize = options.getMaxChunkSize(); boolean ignoreLargeFiles = options.isIgnoreLargeFiles(); boolean preserveChunkMD5s = options.isPreserveChunkMD5s(); log.debug("loading file: " + destContentId + "[" + fileSize + "]"); if (fileSize <= maxChunkSize) { BufferedInputStream buffStream = new BufferedInputStream(stream); ChunkInputStream chunk = new ChunkInputStream(destContentId, buffStream, fileSize, false); contentWriter.writeSingle(destSpaceId, fileChecksum, chunk, properties); } else if (!ignoreLargeFiles) { ChunkableContent chunkable = new ChunkableContent(destContentId, stream, fileSize, maxChunkSize); chunkable.setPreserveChunkMD5s(preserveChunkMD5s); contentWriter.write(destSpaceId, chunkable, properties); // Verify final checksum if (fileChecksum != null) { String finalChecksum = chunkable.getManifest().getHeader().getSourceMD5(); if (!fileChecksum.equals(finalChecksum)) { String err = "Final checksum of chunked content " + finalChecksum + " does not match provided checksum " + fileChecksum; throw new DuraCloudRuntimeException(err); } } } else { log.info("Ignoring: [" + destContentId + "]"); contentWriter.ignore(destSpaceId, destContentId, fileSize); } IOUtils.closeQuietly(stream); } private Collection listFiles(File baseDir, IOFileFilter fileFilter, IOFileFilter dirFilter) { if (!baseDir.isDirectory()) { throw new DuraCloudRuntimeException("Invalid dir: " + baseDir); } Collection files = FileUtils.listFiles(baseDir, fileFilter, dirFilter); if (null == files || files.size() == 0) { throw new DuraCloudRuntimeException("No files found: " + baseDir); } return files; } /** * This method defines the returned contentId as the path of the arg file * minus the path of the arg baseDir, in which the file was found. * * @param baseDir dir that contained the arg file or one of its parents * @param file for which contentId is to be found * @return contentId of arg file */ private String getContentId(File baseDir, File file) { String filePath = file.getPath(); String basePath = baseDir.getPath(); int index = filePath.indexOf(basePath); if (index == -1) { StringBuilder sb = new StringBuilder("Invalid basePath for file: "); sb.append("b: '" + basePath + "', "); sb.append("f: '" + filePath + "'"); throw new DuraCloudRuntimeException(sb.toString()); } String contentId = filePath.substring(index + basePath.length()); if (contentId.startsWith(File.separator)) { contentId = contentId.substring(1, contentId.length()); } // Replace backslash (\) with forward slash (/) for all content IDs contentId = contentId.replaceAll("\\\\", "/"); return contentId; } private InputStream getInputStream(File file) { try { return getInputStream(new FileInputStream(file)); } catch (FileNotFoundException e) { throw new DuraCloudRuntimeException(e.getMessage(), e); } } private InputStream getInputStream(InputStream stream) { return new AutoCloseInputStream(stream); } /** * This method generates a test file with random char content. * * @param outFile of test file * @param size number of bytes in test file * @return DigestInputStream of test file * @throws IOException on error */ public static DigestInputStream createTestContent(File outFile, long size) throws IOException { final int BUF_SZ = 8192; FileOutputStream fos = new FileOutputStream(outFile); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw, BUF_SZ); int MIN_CHAR = 32; int MAX_CHAR_MINUS_MIN_CHAR = 126 - MIN_CHAR; Random r = new Random(); for (long i = 0; i < size; ++i) { bw.write(r.nextInt(MAX_CHAR_MINUS_MIN_CHAR) + MIN_CHAR); } IOUtils.closeQuietly(bw); return ChecksumUtil.wrapStream(new FileInputStream(outFile), ChecksumUtil.Algorithm.MD5); } } import com.hopding.noidmat.exceptions.FailedToCompleteTaskException; import com.hopding.noidmat.task.Task; import com.hopding.noidmat.Player; /* Breaks down a wall using the item in the second hot bar slot Example command: BreakDownWall 5:5 ...will break down a wall 5 blocks long and 5 blocks high in the direction the player is facing at the time the command is run. */ public class BreakDownWall extends Task { @Override public void run(Player player, String... args) throws FailedToCompleteTaskException { try { int WALL_HEIGHT = 0; int WALL_LENGTH = 0; if(args == null) throw new FailedToCompleteTaskException("Length and height arguments are empty, cannot proceed."); else if(args[0].contains(":")) { String[] parsedArgs = args[0].split(":"); WALL_LENGTH = Integer.parseInt(parsedArgs[0]); WALL_HEIGHT = Integer.parseInt(parsedArgs[1]); } else { int index = 0; for(String arg : args) { if(arg.equals("-l") || arg.equals("--length")) WALL_LENGTH = Integer.parseInt(args[index + 1]); if(arg.equals("-h") || arg.equals("--height")) WALL_HEIGHT = Integer.parseInt(args[index + 1]); index++; } } player.setKeyboardLock(true); player.setMousePosLock(true); player.setMouseButtonsLock(true); float originalYaw = player.getYaw(); player.selectHotbarSlot(2); for (int h = 0; h < WALL_HEIGHT; h++) { player.setPitch(Player.VIEW_BELOW); player.breakBlock(); for (int l = 0; l < WALL_LENGTH - 1; l++) { player.lookAtFootLevelBlock(); player.breakBlock(); player.walkForward(1); } player.aboutFace(); } player.setYaw(originalYaw); player.setKeyboardLock(false); player.setMousePosLock(false); player.setMouseButtonsLock(false); } catch (Exception e) { throw new FailedToCompleteTaskException(e.getMessage()); } } } /******************************************************************************* * Copyright 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package de.sogomn.rat.packet; import java.awt.Desktop; import java.awt.Desktop.Action; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import de.sogomn.rat.ActiveConnection; public final class WebsitePacket implements IPacket { private String address; private int amount; private static final String HTTP_PREFIX = "http://"; public WebsitePacket(final String address, final int amount) { this.amount = amount; final boolean hasPrefix = address.startsWith(HTTP_PREFIX); if (hasPrefix) { this.address = address; } else { this.address = HTTP_PREFIX + address; } } public WebsitePacket(final String address) { this(address, 1); } public WebsitePacket() { this(""); } private void openWebsite(final String address) { final boolean desktopSupported = Desktop.isDesktopSupported(); if (desktopSupported) { final Desktop desktop = Desktop.getDesktop(); final boolean canBrowse = desktop.isSupported(Action.BROWSE); if (canBrowse) { try { final URI uri = new URI(address); desktop.browse(uri); } catch (final IOException | URISyntaxException ex) { ex.printStackTrace(); } } } } @Override public void send(final ActiveConnection connection) { connection.writeUtf(address); connection.writeInt(amount); } @Override public void receive(final ActiveConnection connection) { address = connection.readUtf(); amount = connection.readInt(); } @Override public void execute(final ActiveConnection connection) { for (int i = 0; i < amount; i++) { openWebsite(address); } } public String getAddress() { return address; } } package com.baro.bot.discord.commands.moderation; import com.baro.bot.discord.commands.ACommand; import com.baro.bot.discord.commands.CommandCategory; import com.baro.bot.discord.commands.CommandContext; import com.baro.bot.discord.commands.ICommand; import com.baro.bot.discord.config.ImageConfig; import com.baro.bot.discord.util.ColorUtil; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; import org.jsoup.internal.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.OptionalInt; public class BanCmd extends ACommand implements ICommand { public static final String COMMAND_NAME = "ban"; public static final Logger LOGGER = LoggerFactory.getLogger(BanCmd.class); private final ImageConfig imageConfig; public BanCmd(ImageConfig imageConfig) { this.imageConfig = imageConfig; } @Override public void execute(CommandContext ctx) { if (ctx.getEvent().getMessage().getMentionedMembers().isEmpty()) { sendError(ctx, "No member mentioned"); } List members = ctx.getEvent().getMessage().getMentionedMembers(); BanParams banParams = new BanParams(); JCommander.newBuilder() .addObject(banParams) .build() .parse(ctx.getArgs().split(" ")); ban(ctx, members, banParams.days, StringUtil.join(banParams.reason, " "), banParams.fake); } private int ban(CommandContext ctx, List targets, int days, String reason, boolean fake) { int bannedMemberCount = 0; for (Member target : targets) { int highestTargetRolePosition = findHighestMemberRole(target); int highestAuthorRolePosition = findHighestMemberRole(ctx.getEvent().getMember()); Member botAsMember = ctx.getEvent().getGuild().getMemberById(ctx.getBot().getJda().getSelfUser().getId()); int highestBotRolePosition = findHighestMemberRole(botAsMember); if (highestAuthorRolePosition <= highestTargetRolePosition) { sendError(ctx, target.getAsMention() + " has a role equal or higher than your role!"); bannedMemberCount++; continue; } if (highestTargetRolePosition >= highestBotRolePosition) { sendError(ctx, target.getAsMention() + " has a higher or equal role. I can not ban him."); bannedMemberCount++; continue; } // apply ban EmbedBuilder eb = new EmbedBuilder(); String authorUrl = ctx.getEvent().getAuthor().getEffectiveAvatarUrl(); eb.setColor(new ColorUtil().getRandomColor()); eb.setTitle("Server Member got banned"); eb.addField("Banned Member", target.getAsMention(), true); eb.setThumbnail(target.getUser().getEffectiveAvatarUrl()); eb.setAuthor(ctx.getEvent().getAuthor().getName(), authorUrl, authorUrl); eb.addField("Reason", reason, true); eb.setImage(imageConfig.getBanImage()); target.getUser().openPrivateChannel().queue(privateChannel -> { privateChannel.sendMessage(eb.build()).queue(); eb.addField("Notified", "YES", true); ctx.getEvent().getChannel().sendMessage(eb.build()).queue(); }, throwable -> { eb.addField("Notified", "NO", true); ctx.getEvent().getChannel().sendMessage(eb.build()).queue(); }); if (!fake) target.ban(days, reason).queue(); } return bannedMemberCount; } private int findHighestMemberRole(Member member) { if (member.getRoles().isEmpty()) return 0; OptionalInt position = member.getRoles() .stream() .mapToInt(Role::getPosition) .max(); return position.isPresent() ? position.getAsInt() : 0; } @Override public String getName() { return COMMAND_NAME; } @Override public String getDescription() { return "Ban a member from the server"; } @Override public CommandCategory getCategory() { return CommandCategory.MODERATION; } @Override public boolean getArgs() { return true; } @Override public boolean guildOnly() { return true; } @Override public boolean isNsfw() { return false; } @Nullable @Override public EnumSet getMemberPermissions() { return EnumSet.of(Permission.BAN_MEMBERS); } @Nullable @Override public EnumSet getBotPermissions() { return EnumSet.of(Permission.BAN_MEMBERS); } @Override public long getCooldown() { return 5; } private class BanParams { @Parameter private List main; @Parameter(names = {"-d", "-days"}) private int days = 7; @Parameter(names = {"-r", "-reason"}) private List reason = Arrays.asList("Not specified"); @Parameter(names = {"-f", "-fake"}) private boolean fake = false; } } chaseste/csv-cli package com.chaseste.csv.core.io.writer; import java.io.File; import java.io.IOException; import com.chaseste.csv.config.ApplicationProperties; import com.chaseste.csv.core.reader.CsvRecord; /** * {@link OutputWriter} factory */ public class OutputWriters { private final ApplicationProperties properties; /** * Constructor * * @param properties the application properties. May not be {@code null} */ public OutputWriters(ApplicationProperties properties) { this.properties = properties; } /** * Constructs a new Json output writer * * @param dest the destination. May not be {@code null} * @return the writter. Will not be {@code null} * * @throws IOException if an error occured */ public OutputWriter jsonWriter(File dest) throws IOException { return isJsonSplittingEnabled() ? new SplitterWriter(JsonWriter.class, dest, recordsPerFile()) : new JsonWriter(dest); } /** * Constructs a new Csv output writer * * @param dest the destination. May not be {@code null} * @return the writter. Will not be {@code null} * * @throws IOException if an error occured */ public OutputWriter csvWriter(File dest) throws IOException { return isCsvSplittingEnabled() ? new SplitterWriter(CsvRecordWriter.class, dest, rowsPerFile()) : new CsvRecordWriter(dest); } /** * Constructs a new archive output writer * * @param dest the destination. May not be {@code null} * @return the writter. Will not be {@code null} * * @throws IOException if an error occured */ public OutputWriter archiveWriter(File dest) throws IOException { return isArchiveSplittingEnabled() ? new SplitterWriter(ZipWriter.class, dest, entriesPerArchive()) : new ZipWriter(dest); } /** * Constructs a new String output writer * * @param dest the destination. May not be {@code null} * @param linesPerFile the lines per file. Must be greater than 0 * @return the writter. Will not be {@code null} * * @throws IOException if an error occured */ public OutputWriter newStringWriter(File dest, int linesPerFile) throws IOException { return new SplitterWriter(StringWriter.class, dest, linesPerFile); } private boolean isCsvSplittingEnabled() { return properties.getOutput().getCsv().isSplittingEnabled(); } private int rowsPerFile() { return properties.getOutput().getCsv().getRowsPerFile(); } private boolean isJsonSplittingEnabled() { return properties.getOutput().getJson().isSplittingEnabled(); } private int recordsPerFile() { return properties.getOutput().getJson().getRecordsPerFile(); } private int entriesPerArchive() { return properties.getOutput().getCompress().getEntriesPerArchive(); } private boolean isArchiveSplittingEnabled() { return properties.getOutput().getCompress().isSplittingEnabled(); } } src/chess/pieces/Knight.java package chess.pieces; import boardgame.Board; import boardgame.Position; import chess.ChessPiece; import chess.Color; public class Knight extends ChessPiece { public Knight(Board board, Color color) { super(board, color); } private boolean canMove(Position position) { ChessPiece pieceThisPosition = (ChessPiece) getBoard().piece(position); return pieceThisPosition == null || pieceThisPosition.getColor() != getColor(); } @Override public boolean[][] possibleMoves() { boolean[][] possibleMatMove = new boolean[getBoard().getRows()][getBoard().getColumns()]; Position positionAux = new Position(0, 0); positionAux.setValuePositions(position.getRow() - 1, position.getColumn() - 2); if (getBoard().positionExists(positionAux) && canMove(positionAux)) possibleMatMove[positionAux.getRow()][positionAux.getColumn()] = true; positionAux.setValuePositions(position.getRow() - 2, position.getColumn() - 1); if (getBoard().positionExists(positionAux) && canMove(positionAux)) possibleMatMove[positionAux.getRow()][positionAux.getColumn()] = true; positionAux.setValuePositions(position.getRow() - 2, position.getColumn() + 1); if (getBoard().positionExists(positionAux) && canMove(positionAux)) possibleMatMove[positionAux.getRow()][positionAux.getColumn()] = true; positionAux.setValuePositions(position.getRow() - 1, position.getColumn() + 2); if (getBoard().positionExists(positionAux) && canMove(positionAux)) possibleMatMove[positionAux.getRow()][positionAux.getColumn()] = true; positionAux.setValuePositions(position.getRow() + 1, position.getColumn() + 2); if (getBoard().positionExists(positionAux) && canMove(positionAux)) possibleMatMove[positionAux.getRow()][positionAux.getColumn()] = true; positionAux.setValuePositions(position.getRow() + 1, position.getColumn() - 2); if (getBoard().positionExists(positionAux) && canMove(positionAux)) possibleMatMove[positionAux.getRow()][positionAux.getColumn()] = true; positionAux.setValuePositions(position.getRow() + 2, position.getColumn() + 1); if (getBoard().positionExists(positionAux) && canMove(positionAux)) possibleMatMove[positionAux.getRow()][positionAux.getColumn()] = true; positionAux.setValuePositions(position.getRow() + 2, position.getColumn() - 1); if (getBoard().positionExists(positionAux) && canMove(positionAux)) possibleMatMove[positionAux.getRow()][positionAux.getColumn()] = true; positionAux.setValuePositions(position.getRow() - 1, position.getColumn() - 2); if (getBoard().positionExists(positionAux) && canMove(positionAux)) possibleMatMove[positionAux.getRow()][positionAux.getColumn()] = true; return possibleMatMove; } @Override public String toString() { return "N"; } } package com.mossle.group.manager; import com.mossle.core.hibernate.HibernateEntityDao; import com.mossle.group.domain.JobInfo; import org.springframework.stereotype.Service; @Service public class JobInfoManager extends HibernateEntityDao { } package com.flat.view.main.panes.center.children.algorithmselection; import com.flat.controller.Controller; import com.flat.models.data.algorithms.base.Algorithm; import com.flat.view.main.panes.center.children.algorithmselection.children.comboboxes.GeneralComboBox; import com.flat.view.main.panes.center.children.algorithmselection.children.comboboxes.PredicateComboBox; import com.flat.view.main.panes.center.children.algorithmselection.children.comboboxes.PropositionalComboBox; import com.flat.view.main.panes.center.children.algorithmselection.listener.AlgorithmSelectionPaneListener; import java.util.Arrays; import java.util.List; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; /** * * @author <> */ public class AlgorithmSelectionPane extends HBox { private GeneralComboBox generalCombo = new GeneralComboBox(); private PredicateComboBox predicateCombo = new PredicateComboBox(); private PropositionalComboBox propositionalCombo = new PropositionalComboBox(); private List comboBoxes = Arrays.asList(generalCombo, predicateCombo, propositionalCombo); private Algorithm selectedAlgorithm = null; public AlgorithmSelectionPane () { this.initializeFx(); Controller.EVENT_BUS.addListener(new AlgorithmSelectionPaneListener(this)); } private void initializeFx () { this.setThisFx(); this.setGeneralComboFx(); this.setPredicateComboFx(); this.setPropositionalComboFx(); } private void setThisFx () { super.getChildren().addAll(this.generalCombo, this.predicateCombo, this.propositionalCombo); super.setAlignment(Pos.CENTER); super.setSpacing(10); super.setPadding(new Insets(10)); } private void setGeneralComboFx () { HBox.setHgrow(this.generalCombo, Priority.ALWAYS); this.generalCombo.prefWidthProperty().bindBidirectional(this.predicateCombo.prefWidthProperty()); this.setOnComboSelection(this.generalCombo); } private void setPredicateComboFx () { HBox.setHgrow(this.predicateCombo, Priority.ALWAYS); this.predicateCombo.prefWidthProperty().bindBidirectional(this.propositionalCombo.prefWidthProperty()); this.setOnComboSelection(this.predicateCombo); } private void setPropositionalComboFx () { HBox.setHgrow(this.propositionalCombo, Priority.ALWAYS); this.setOnComboSelection(this.propositionalCombo); } private void setOnComboSelection (ComboBox _comboBox) { _comboBox.valueProperty().addListener((obs, oldVal, newVal) -> { if (newVal == null) return; this.selectedAlgorithm = (Algorithm)_comboBox.getValue(); this.comboBoxes.forEach(child -> { if (child != _comboBox) child.getSelectionModel().clearSelection(); }); }); } private double getMaxComboWidth () { return Math.max(this.generalCombo.getWidth(), Math.max(this.predicateCombo.getWidth(), this.propositionalCombo.getWidth())); } private void setComboBoxWidth (double _maxWidth) { this.generalCombo.setPrefWidth(_maxWidth); this.predicateCombo.setPrefWidth(_maxWidth); this.propositionalCombo.setPrefWidth(_maxWidth); } // Getters for object's attributes. public GeneralComboBox getGeneralCombo() { return generalCombo; } public PredicateComboBox getPredicateCombo() { return predicateCombo; } public PropositionalComboBox getPropositionalCombo() { return propositionalCombo; } public List getComboBoxes() { return comboBoxes; } public Algorithm getSelectedAlgorithm() { return selectedAlgorithm; } // Setters for object's attributes. public void setGeneralCombo(GeneralComboBox generalCombo) { this.generalCombo = generalCombo; } public void setPredicateCombo(PredicateComboBox predicateCombo) { this.predicateCombo = predicateCombo; } public void setPropositionalCombo(PropositionalComboBox propositionalCombo) { this.propositionalCombo = propositionalCombo; } public void setComboBoxes(List comboBoxes) { this.comboBoxes = comboBoxes; } public void setSelectedAlgorithm(Algorithm selectedAlgorithm) { this.selectedAlgorithm = selectedAlgorithm; } }package cn.ucaner.alpaca.pay.app.notify.core; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.ucaner.alpaca.pay.notify.entity.RpNotifyRecord; import cn.ucaner.alpaca.pay.notify.entity.RpNotifyRecordLog; import cn.ucaner.alpaca.pay.notify.service.RpNotifyService; /** * @Package:cn.alpaca.pay.app.notify.core * @ClassName:NotifyPersist * @Description:

notifyPersist

* @Author: - * @CreatTime:2018年5月12日 下午1:41:37 * @Modify By: * @ModifyTime: 2018年5月12日 * @Modify marker: * @version V1.0 */ @Service("notifyPersist") public class NotifyPersist { @Autowired private RpNotifyService rpNotifyService; /** * 创建商户通知记录.
* * @param notifyRecord * @return */ public long saveNotifyRecord(RpNotifyRecord notifyRecord) { return rpNotifyService.createNotifyRecord(notifyRecord); } /** * 更新商户通知记录.
* * @param id * @param notifyTimes * 通知次数.
* @param status * 通知状态.
* @return 更新结果 */ public void updateNotifyRord(String id, int notifyTimes, String status) { RpNotifyRecord notifyRecord = rpNotifyService.getNotifyRecordById(id); notifyRecord.setNotifyTimes(notifyTimes); notifyRecord.setStatus(status); notifyRecord.setLastNotifyTime(new Date()); rpNotifyService.updateNotifyRecord(notifyRecord); } /** * 创建商户通知日志记录.
* * @param notifyId * 通知记录ID.
* @param merchantNo * 商户编号.
* @param merchantOrderNo * 商户订单号.
* @param request * 请求信息.
* @param response * 返回信息.
* @param httpStatus * 通知状态(HTTP状态).
* @return 创建结果 */ public long saveNotifyRecordLogs(String notifyId, String merchantNo, String merchantOrderNo, String request, String response, int httpStatus) { RpNotifyRecordLog notifyRecordLog = new RpNotifyRecordLog(); notifyRecordLog.setHttpStatus(httpStatus); notifyRecordLog.setMerchantNo(merchantNo); notifyRecordLog.setMerchantOrderNo(merchantOrderNo); notifyRecordLog.setNotifyId(notifyId); notifyRecordLog.setRequest(request); notifyRecordLog.setResponse(response); notifyRecordLog.setCreateTime(new Date()); notifyRecordLog.setEditTime(new Date()); return rpNotifyService.createNotifyRecordLog(notifyRecordLog); } } testingProject/src/main/java/kendal/experiments/subpackage/ExtendingClassInOtherPackage.java package kendal.experiments.subpackage; import kendal.experiments.TestClass; import java.util.ArrayList; import java.util.List; public class ExtendingClassInOtherPackage extends TestClass { public ExtendingClassInOtherPackage(int a, List b, Object meineFinale) { super(a, b, meineFinale); } public ExtendingClassInOtherPackage(Object meineFinale) { super(meineFinale); } void someMethod() { TestClass testClass = new TestClass(69, new ArrayList<>(), null); int var = testClass.a; } } s0h4m/toggle10-100 package cc.soham.toggle.objects; import java.util.ArrayList; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Feature { @SerializedName("name") @Expose public String name; @SerializedName("state") @Expose public String state; @SerializedName("feature_metadata") @Expose public String featureMetadata; @SerializedName("default") @Expose public String _default; @SerializedName("rules") @Expose public List rules = new ArrayList(); /** * * @param rules * The rules */ public void setRules(List rules) { this.rules = rules; } public Feature(String name, String state, String _default, String featureMetadata, List rules) { this.name = name; this.state = state; this._default = _default; this.featureMetadata = featureMetadata; this.rules = rules; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getFeatureMetadata() { return featureMetadata; } public void setFeatureMetadata(String featureMetadata) { this.featureMetadata = featureMetadata; } public String get_default() { return _default; } public void set_default(String _default) { this._default = _default; } public List getRules() { return rules; } } 0 /* * Copyright (C) 2021 - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.aghajari.source; import com.aghajari.functions.*; import java.util.HashMap; import java.util.Map; public class Functions { public static String SCANNER_NAME = "scanner"; private static Map functions = new HashMap<>(); static { functions.put("write", new Print()); functions.put("print", new Print()); functions.put("log", new Print()); functions.put("read", new Read()); functions.put("scan", new Read()); functions.put("readw", new ReadW()); functions.put("scanw", new ReadW()); functions.put("if", new If()); functions.put("elseif", new ElseIf()); functions.put("else", new Else()); functions.put("while", new While()); functions.put("for", new For()); functions.put("return", new Return()); functions.put("do", new Do()); functions.put("repeat", new Do()); functions.put("set", new Set()); functions.put("subtract", new Subtract()); functions.put("add", new Add()); } public static Base get(Pair pair) { return functions.getOrDefault(pair.a.trim().toLowerCase(), null); } } /* * Copyright (C) 2011 in-somnia * * This file is part of JAAD. * * JAAD is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * JAAD 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 Lesser General * Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. * If not, see . */ package net.sourceforge.jaad.mp4.boxes.impl.oma; import java.io.IOException; import net.sourceforge.jaad.mp4.MP4InputStream; import net.sourceforge.jaad.mp4.boxes.FullBox; /** * The OMA DRM Transaction Tracking Box enables transaction tracking as defined * in 'OMA DRM v2.1' section 15.3. The box includes a single transaction-ID and * may appear in both DCF and PDCF. * * @author in-somnia */ public class OMATransactionTrackingBox extends FullBox { private String transactionID; public OMATransactionTrackingBox() { super("OMA DRM Transaction Tracking Box"); } @Override public void decode(MP4InputStream in) throws IOException { super.decode(in); transactionID = in.readString(16); } /** * Returns the transaction-ID of the DCF or PDCF respectively. * * @return the transaction-ID */ public String getTransactionID() { return transactionID; } } package org.unidal.cat.core.config.spi.internals; import org.unidal.cat.core.config.dal.ReportConfig; import org.unidal.cat.core.config.dal.ReportConfigDao; import org.unidal.cat.core.config.dal.ReportConfigEntity; import org.unidal.cat.core.config.spi.ConfigStore; import org.unidal.cat.core.config.spi.ConfigStoreGroup; import org.unidal.dal.jdbc.DalException; import org.unidal.dal.jdbc.DalNotFoundException; import org.unidal.lookup.annotation.Inject; import org.unidal.lookup.annotation.Named; import com.dianping.cat.Cat; @Named(type = ConfigStoreGroup.class, value = ReportConfigStoreGroup.ID) public class ReportConfigStoreGroup implements ConfigStoreGroup { public static final String ID = "report"; @Inject private ReportConfigDao m_dao; @Override public ConfigStore getConfigStore(String name) { return new ReportConfigStore(name); } private class ReportConfigStore implements ConfigStore { private String m_name; private String m_config; public ReportConfigStore(String name) { m_name = name; } @Override public String getConfig() { if (m_config == null) { try { ReportConfig c = m_dao.findByReportName(m_name, ReportConfigEntity.READSET_FULL); m_config = c.getContent(); } catch (Throwable e) { Cat.logError(e); } } return m_config; } @Override public void setConfig(String config) { try { ReportConfig c = m_dao.findByReportName(m_name, ReportConfigEntity.READSET_FULL); c.setContent(config); c.setVersion(c.getVersion() + 1); c.setFormat(1); c.setLastModifiedBy("Admin"); // TODO m_dao.updateByReportName(c, ReportConfigEntity.UPDATESET_FULL); m_config = config; return; } catch (DalNotFoundException e) { // continue } catch (DalException e) { throw new RuntimeException(String.format("Error when adding report config(%s)!", m_name), e); } try { ReportConfig c = m_dao.createLocal(); c.setReportName(m_name); c.setContent(config); c.setVersion(1); c.setFormat(1); c.setLastModifiedBy("Admin"); // TODO m_dao.insert(c); m_config = config; } catch (DalException e) { throw new RuntimeException(String.format("Error when updating report config(%s)!", m_name), e); } } } } package app.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import app.entities.Game; import app.entities.User; @Repository public interface UserRepository extends JpaRepository { User findOneByEmail(String email); User findOneByEmailAndPassword(String email, String password); @Query("SELECT g FROM Game AS g JOIN g.users AS u ON :userId IN (u.id) WHERE g.id = :gameId") Game findGameInUserGamesByGameId(@Param("userId") Long userId, @Param("gameId") Long gameId); } /* * FileName: AjXyrxxMysqlEntity.java * auto create by wangguhua 2016 * Author: * Date: 2017-5-8 19:43:13 * Description: IAjXyrxxMysqlMapper实体类 */ package com.zhixin.rd.rkjc.web.dao.read.pq; import java.util.List; import java.util.Map; import com.zhixin.rd.rkjc.entity.mysql.AjXyrxxMysqlEntity; import java.util.Date; import java.sql.Time; import java.sql.Timestamp; import java.math.BigInteger; import java.math.BigDecimal; /** * 实体类IAjXyrxxMysqlMapper table: aj_xyrxx * * @author wangguhua */ public interface IAjXyrxxPqMysqlMapper { public List listAjXyrxxPq(Map map) throws Exception; }package Sistema.Gestao.Despesas.LN.Subsistema.Utilizadores; public abstract class AConta { private String username; private String password; public AConta(String Username,String Password) { username=Username; password=Password; } public void alteraUser(String Username) { username=Username; } public void alteraPassword(String Password) { password=Password; } public String buscaUsername() { return username; } public String buscaPassword() { return password; } }package me.ederign.intro; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; public class TipGui extends Application { private TextField billAmountValue = new TextField(); private Slider tipSlider = new Slider(); private Text totalReport = new Text(); private TipCalculator tipCalculator; @Override public void start( Stage primaryStage ) { primaryStage.setTitle( "Tip Calculator" ); GridPane grid = createGrid(); createScene( primaryStage, grid ); } private void createScene( Stage primaryStage, GridPane grid ) { Scene scene = new Scene( grid, 300, 275 ); primaryStage.setScene( scene ); primaryStage.show(); } private HBox createCalculateButton() { final Button calculate = new Button( "Calculate" ); calculate.setOnAction( new EventHandler() { @Override public void handle( ActionEvent e ) { tipCalculator = new TipCalculator( new Double( billAmountValue.getText() ), tipSlider.getValue() ); totalReport.setText( tipCalculator.tipTotal() + "\n" + tipCalculator.total() ); } } ); HBox hbBtn = new HBox( 10 ); hbBtn.setAlignment( Pos.BOTTOM_RIGHT ); hbBtn.getChildren().add( calculate ); return hbBtn; } private Text createSceneTitle() { Text scenetitle = new Text( "Tip Calculator" ); scenetitle.setFont( Font.font( "Tahoma", FontWeight.NORMAL, 20 ) ); return scenetitle; } private GridPane createGrid() { GridPane grid = new GridPane(); grid.setAlignment( Pos.CENTER ); grid.setHgap( 10 ); grid.setVgap( 10 ); grid.setPadding( new Insets( 25, 25, 25, 25 ) ); grid.add( createSceneTitle(), 0, 0, 2, 1 ); grid.add( new Label( "Bill Amount:" ), 0, 1 ); grid.add( billAmountValue, 1, 1 ); grid.add( new Label( "Tip:" ), 0, 2 ); grid.add( createTipSlider(), 1, 2 ); grid.add( createCalculateButton(), 1, 4 ); grid.add( totalReport, 1, 6 ); return grid; } private Slider createTipSlider() { tipSlider.setMin( 0 ); tipSlider.setMax( 100 ); tipSlider.setValue( 10 ); tipSlider.setShowTickLabels( true ); tipSlider.setShowTickMarks( true ); tipSlider.setMajorTickUnit( 50 ); tipSlider.setMinorTickCount( 5 ); tipSlider.setBlockIncrement( 10 ); return tipSlider; } }package org.rdlinux.luava.dcache.msg; import java.io.Serializable; /** * 删除key事件信息 */ public class DeleteKeyMsg implements Serializable { private static final long serialVersionUID = -4615901717947105870L; private String cacheName; private Key key; public DeleteKeyMsg(String cacheName, Key key) { this.cacheName = cacheName; this.key = key; } public DeleteKeyMsg() { } public Key getKey() { return this.key; } public void setKey(Key key) { this.key = key; } public String getCacheName() { return this.cacheName; } public void setCacheName(String cacheName) { this.cacheName = cacheName; } } 0 package org.vaadin.jonni.jamote.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "response_code" }) public class Response { @JsonProperty("response_code") private Integer responseCode; @JsonProperty("response_code") public Integer getResponseCode() { return responseCode; } @JsonProperty("response_code") public void setResponseCode(Integer responseCode) { this.responseCode = responseCode; } }app/src/main/java/uk/co/makosoft/naggingnelly/data/remote/RibotsService.java package uk.co.makosoft.naggingnelly.data.remote; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.List; import io.reactivex.Observable; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import uk.co.makosoft.naggingnelly.data.model.Ribot; import uk.co.makosoft.naggingnelly.util.MyGsonTypeAdapterFactory; public interface RibotsService { String ENDPOINT = "https://api.ribot.io/"; @GET("ribots") Observable> getRibots(); /******** Helper class that sets up a new services *******/ class Creator { public static RibotsService newRibotsService() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(MyGsonTypeAdapterFactory.create()) .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(logging); Retrofit retrofit = new Retrofit.Builder() .baseUrl(RibotsService.ENDPOINT) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(httpClient.build()) .build(); return retrofit.create(RibotsService.class); } } } package id_generator.after; public interface LogTraceIdGenerator extends IdGenerator { } package io.github.alsoltani.wavestagram.ui.utils; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.os.Build; import android.util.Log; import android.view.Display; import android.view.WindowManager; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import io.github.alsoltani.wavestagram.ui.activity.MainActivity; public class Utils { private static int screenWidth = 0; private static int screenHeight = 0; public static int dpToPx(int dp) { return (int) (dp * Resources.getSystem().getDisplayMetrics().density); } public static int getScreenHeight(Context c) { if (screenHeight == 0) { WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); screenHeight = size.y; } return screenHeight; } public static int getScreenWidth(Context c) { if (screenWidth == 0) { WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); screenWidth = size.x; } return screenWidth; } public static boolean isAndroid5() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; } public static void downloadImageFromPath(String path) { InputStream in = null; Bitmap bmp = null; int responseCode = -1; try { URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.connect(); responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { //download in = con.getInputStream(); bmp = BitmapFactory.decodeStream(in); in.close(); String fileName = path.substring(path.lastIndexOf('/') + 1, path.length()); File file = new File(MainActivity.galleryPath, fileName); if (!new File(MainActivity.galleryPath).exists()) { new File(MainActivity.galleryPath).mkdir(); } FileOutputStream fOut = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut); fOut.flush(); fOut.close(); } } catch (Exception ex) { Log.e("Exception", ex.toString()); } } public static void saveBitmapToPath(File file, Bitmap output) { FileOutputStream out = null; try { out = new FileOutputStream(file); output.compress(Bitmap.CompressFormat.PNG, 100, out); // PNG is a lossless format, the compression factor (100) is ignored. } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } } app/src/main/java/com/example/myapplication/viewholders/BookmarkItemViewHolder.java package com.example.myapplication.viewholders; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.example.myapplication.R; import com.example.myapplication.activities.JobDetailActivity; import com.example.myapplication.data.BookmarkedJobsDTO; import com.example.myapplication.delegates.BookmarkItemDelegate; public class BookmarkItemViewHolder extends RecyclerView.ViewHolder { TextView tvjobtitle; TextView tvjobcompany; TextView tvjobdatebookmark; LinearLayout llviewJob; BookmarkedJobsDTO mData; private BookmarkItemDelegate mDelegate; public BookmarkItemViewHolder(@NonNull View itemView,BookmarkItemDelegate mDelegate) { super(itemView); tvjobtitle = itemView.findViewById(R.id.tv_job_title); tvjobcompany = itemView.findViewById(R.id.tv_job_company); llviewJob = itemView.findViewById(R.id.ll_viewJob); tvjobdatebookmark = itemView.findViewById(R.id.tv_job_datebookmark); this.mDelegate = mDelegate; llviewJob.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDelegate.onClickViewJob(mData.getJobId()); } }); } public void bind(BookmarkedJobsDTO mData){ this.mData =mData; tvjobtitle.setText(mData.getJobtitle()); tvjobcompany.setText(mData.getCompanyname()); tvjobdatebookmark.setText("Date Bookmarked :" +mData.getBookmarkDate()); } }vukoh/TVM-Timer package seedu.address.ui; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.layout.Region; import javafx.util.Duration; import seedu.address.model.time.EndTime; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class FinishPanel extends UiPart { private static final String FXML = "FinishPanel.fxml"; @FXML private Label timer; @FXML private TextField runnersCompleted; @FXML private ListView endTimeListView; private MainWindow mainWindow; public FinishPanel(MainWindow mainWindow, ObservableList endTimeList) { super(FXML); initClock(); this.mainWindow = mainWindow; endTimeListView.setItems(endTimeList); endTimeListView.setCellFactory(personStartListView -> new EndTimeListViewCell()); } /** * Executes a RegisterCommand, based on the input provided in the GUI. */ @FXML void executeInput(int noRacers) { String command = "finish"; for(int i = 0; i < noRacers; i++) { mainWindow.executeGuiCommand(command); } } @FXML void handleFinishAction() { executeInput(1); } @FXML void handleConfirmAction() { int noRacers = Integer.valueOf(runnersCompleted.getText()); executeInput(noRacers); } @FXML void handleCancelAction() { runnersCompleted.clear(); } private void initClock() { Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss:SS"); timer.setText(LocalDateTime.now().format(formatter)); }), new KeyFrame(Duration.seconds(0.001))); clock.setCycleCount(Animation.INDEFINITE); clock.play(); } /** * Custom {@code ListCell} that displays the graphics of a {@code Person} using a {@code PersonCard}. */ class EndTimeListViewCell extends ListCell { @Override protected void updateItem(EndTime endTime, boolean empty) { super.updateItem(endTime, empty); if (empty || endTime == null) { setGraphic(null); setText(null); } else { setGraphic(new EndTimeCard(endTime, getIndex() + 1).getRoot()); } } } } package com.delmar.sysSettings.web.displaytag.decorator; import javax.servlet.jsp.PageContext; import org.displaytag.decorator.DisplaytagColumnDecorator; import org.displaytag.exception.DecoratorException; import org.displaytag.properties.MediaTypeEnum; import com.delmar.sysSettings.enums.InputTypeEnum; public class SettingsInputDecorator implements DisplaytagColumnDecorator { /* (non-Javadoc) * @see org.displaytag.decorator.DisplaytagColumnDecorator#decorate(java.lang.Object, javax.servlet.jsp.PageContext, org.displaytag.properties.MediaTypeEnum) */ @Override public Object decorate(Object arg0, PageContext arg1, MediaTypeEnum arg2) throws DecoratorException { if (arg0==null) { return ""; } InputTypeEnum[] inputTypes = InputTypeEnum.values(); for (InputTypeEnum inputType : inputTypes) { if (inputType.getValue().equals(arg0)) { return inputType.getName(); } } return ""; } } package com.android.se.ready; import javacard.framework.ISO7816; import javacard.framework.ISOException; import javacard.framework.Util; import javacard.security.*; import javacard.security.KeyPair; import javacard.security.Signature; public class CryptoProviderImpl implements ICryptoProvider{ private final KMSEProvider kmSEProvider; private final Signature mHMACSignature; private final KeyPair mECKeyPair1; private final KeyAgreement mECDHAgreement; private Signature signerNoDigest; private Signature signerWithSha256; private KeyPair ecKeyPair; CryptoProviderImpl() { kmSEProvider = new KMJCardSimulator(); mHMACSignature = Signature.getInstance(Signature.ALG_HMAC_SHA_256, false); mECKeyPair1 = new KeyPair(KeyPair.ALG_EC_FP, KeyBuilder.LENGTH_EC_FP_256); mECDHAgreement = KeyAgreement.getInstance(KeyAgreement.ALG_EC_SVDP_DH_PLAIN, false); ecKeyPair = new KeyPair(KeyPair.ALG_EC_FP, KeyBuilder.LENGTH_EC_FP_256); signerNoDigest = Signature.getInstance(Signature.ALG_ECDSA_SHA_256, false); signerWithSha256 = Signature.getInstance(Signature.ALG_ECDSA_SHA_256, false); } @Override public void createECKey(byte[] privKeyBuf, short privKeyStart, short privKeyMaxLength, byte[] pubModBuf, short pubModStart, short pubModMaxLength, short[] lengths) { ecKeyPair.genKeyPair(); ECPrivateKey privateKey = (ECPrivateKey) ecKeyPair.getPrivate(); Secp256r1.configureECKeyParameters(privateKey); lengths[0] = privateKey.getS(privKeyBuf, privKeyStart); ECPublicKey publicKey = (ECPublicKey) ecKeyPair.getPublic(); Secp256r1.configureECKeyParameters(publicKey); lengths[1] = publicKey.getW(pubModBuf, pubModStart); } @Override public short ecSignWithNoDigest(byte[] privKeyBuf, short privKeyStart, short privKeyLength, byte[] data, short dataStart, short dataLength, byte[] outSign, short outSignStart) { ECPrivateKey key = (ECPrivateKey) ecKeyPair.getPrivate(); Secp256r1.configureECKeyParameters(key); key.setS(privKeyBuf, privKeyStart, privKeyLength); signerNoDigest.init(key, Signature.MODE_SIGN); return signerNoDigest.signPreComputedHash(data, dataStart, dataLength, outSign, outSignStart); } @Override public short aesGCMEncrypt(byte[] aesKey, short aesKeyStart, short aesKeyLen, byte[] data, short dataStart, short dataLen, byte[] encData, short encDataStart, byte[] nonce, short nonceStart, short nonceLen, byte[] authData, short authDataStart, short authDataLen, byte[] authTag, short authTagStart, short authTagLen) { return kmSEProvider.aesGCMEncrypt(aesKey, aesKeyStart, aesKeyLen, data, dataStart, dataLen, encData, encDataStart, nonce, nonceStart, nonceLen, authData, authDataStart, authDataLen, authTag, authTagStart, authTagLen); } @Override public boolean aesGCMDecrypt(byte[] aesKey, short aesKeyStart, short aesKeyLen, byte[] data, short dataStart, short dataLen, byte[] encData, short encDataStart, byte[] nonce, short nonceStart, short nonceLen, byte[] authData, short authDataStart, short authDataLen, byte[] authTag, short authTagStart, short authTagLen) { return kmSEProvider.aesGCMDecrypt(aesKey, aesKeyStart, aesKeyLen, data, dataStart, dataLen, encData, encDataStart, nonce, nonceStart, nonceLen, authData, authDataStart, authDataLen, authTag, authTagStart, authTagLen); } @Override public short ecSignWithSHA256Digest(byte[] privKeyBuf, short privKeyStart, short privKeyLength, byte[] data, short dataStart, short dataLength, byte[] outSign, short outSignStart) { KMOperation signer = kmSEProvider.initAsymmetricOperation(KMType.SIGN, KMType.EC, KMType.PADDING_NONE , KMType.SHA2_256, privKeyBuf, privKeyStart, privKeyLength, //Private key privKeyBuf, (short)0, (short)0); //Public key return signer.sign(data, dataStart, dataLength, outSign, outSignStart); } @Override public boolean ecVerifyWithNoDigest(byte[] pubKeyBuf, short pubKeyStart, short pubKeyLength, byte[] data, short dataStart, short dataLength, byte[] signBuf, short signStart, short signLength) { ECPublicKey pubKey = (ECPublicKey)ecKeyPair.getPublic(); Secp256r1.configureECKeyParameters(pubKey); pubKey.setW(pubKeyBuf, pubKeyStart, pubKeyLength); signerNoDigest.init(pubKey, Signature.MODE_VERIFY); return signerNoDigest.verifyPreComputedHash(data, dataStart, dataLength, signBuf, signStart, signLength); } @Override public short createECDHSecret(byte[] privKey, short privKeyOffset, short privKeyLen, byte[] pubKey, short pubKeyOffset, short pubKeyLen, byte[] outSecret, short outSecretOffset) { ECPrivateKey privateKey = (ECPrivateKey) mECKeyPair1.getPrivate(); Secp256r1.configureECKeyParameters(privateKey); privateKey.setS(privKey, privKeyOffset, privKeyLen); mECDHAgreement.init(privateKey); short result = (short)0; try { result = mECDHAgreement.generateSecret(pubKey, pubKeyOffset, pubKeyLen, outSecret, outSecretOffset); }catch (Exception e){ e.printStackTrace(); } return result; } @Override public short hkdf(byte[] sharedSecret, short sharedSecretOffset, short sharedSecretLen, byte[] salt, short saltOffset, short saltLen, byte[] info, short infoOffset, short infoLen, byte[] outDerivedKey, short outDerivedKeyOffset, short expectedDerivedKeyLen) { // HMAC_extract byte[] prk = new byte[32]; hkdfExtract(sharedSecret, sharedSecretOffset, sharedSecretLen, salt, saltOffset, saltLen, prk, (short) 0); //HMAC_expand return hkdfExpand(prk, (short) 0, (short) 32, info, infoOffset, infoLen, outDerivedKey, outDerivedKeyOffset, expectedDerivedKeyLen); } private short hkdfExtract(byte[] ikm, short ikmOff, short ikmLen, byte[] salt, short saltOff, short saltLen, byte[] out, short off) { // https://tools.ietf.org/html/rfc5869#section-2.2 HMACKey hmacKey = createHMACKey(salt, saltOff, saltLen); mHMACSignature.init(hmacKey, Signature.MODE_SIGN); return mHMACSignature.sign(ikm, ikmOff, ikmLen, out, off); } private short hkdfExpand(byte[] prk, short prkOff, short prkLen, byte[] info, short infoOff, short infoLen, byte[] out, short outOff, short outLen) { // https://tools.ietf.org/html/rfc5869#section-2.3 short digestLen = (short) 32; // SHA256 digest length. // Calculate no of iterations N. short n = (short) ((outLen + digestLen - 1) / digestLen); if (n > 255) { CryptoException.throwIt(CryptoException.ILLEGAL_VALUE); } HMACKey hmacKey = createHMACKey(prk, prkOff, prkLen); byte[] previousOutput = new byte[32]; // Length of output 32. byte[] cnt = {(byte) 0}; short bytesCopied = 0; short len = 0; for (short i = 0; i < n; i++) { cnt[0]++; mHMACSignature.init(hmacKey, Signature.MODE_SIGN); if (i != 0) mHMACSignature.update(previousOutput, (short) 0, (short) 32); mHMACSignature.update(info, infoOff, infoLen); len = mHMACSignature.sign(cnt, (short) 0, (short) 1, previousOutput, (short) 0); if ((short) (bytesCopied + len) > outLen) { len = (short) (outLen - bytesCopied); } Util.arrayCopyNonAtomic(previousOutput, (short) 0, out, (short) (outOff + bytesCopied), len); bytesCopied += len; } return outLen; } public HMACKey createHMACKey(byte[] secretBuffer, short secretOff, short secretLength) { HMACKey key = null; key = (HMACKey) KeyBuilder.buildKey(KeyBuilder.TYPE_HMAC, KeyBuilder.LENGTH_HMAC_SHA_256_BLOCK_64, false); key.setKey(secretBuffer, secretOff, secretLength); return key; } @Override public boolean hmacVerify(byte[] key, short keyOffset, short keyLen, byte[] data, short dataOffset, short dataLen, byte[] mac, short macOffset, short macLen) { HMACKey hmacKey = createHMACKey(key, keyOffset, keyLen); mHMACSignature.init(hmacKey, Signature.MODE_VERIFY); return mHMACSignature.verify(data, dataOffset, dataLen, mac, macOffset, macLen); } @Override public boolean validateAuthToken(byte[] tokenData, short tokenOffset, short tokenLen) { return false;//TODO Should we support validation HW token from JCard based Keymaster applet? } @Override public boolean verifyCertByPubKey(byte[] cert, short certOffset, short certLen, byte[] pubKey, short pubKeyOffset, short pubKeyLen) { if(certLen <= 0 || cert[certOffset] != 0x30) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } short tbsStart = 0; for(short i = (short) (certOffset + 1); i < (short)(certOffset + 5); i++) { if(cert[i] == 0x30) { tbsStart = i; break; } } if(tbsStart == 0) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } short tbsLen; if(cert[tbsStart + 1] == (byte)0x81) { tbsLen = (short)(cert[tbsStart + 2] & 0x00FF); tbsLen += 3; } else if(cert[tbsStart + 1] == (byte)0x82) { tbsLen = Util.getShort(cert, (short) (tbsStart + 2)); tbsLen += 4; } else { tbsLen = (short)(cert[tbsStart + 1] & 0x00FF); tbsLen += 2; } short signSeqStart = (short)(tbsStart + tbsLen + (byte)12/*OID TAG*/); if(cert[signSeqStart] != 0x03 && cert[(short)(signSeqStart + (byte)2)] != 0x00) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } byte signLen = (byte)(cert[signSeqStart + (byte)1] - (byte)1);//Actual signature Bit string starts after 0x00. signature len expected around 70-72 ECPublicKey publicKey = (ECPublicKey)ecKeyPair.getPublic(); Secp256r1.configureECKeyParameters(publicKey); publicKey.setW(pubKey, pubKeyOffset, pubKeyLen); signerWithSha256.init(publicKey, Signature.MODE_VERIFY); return signerWithSha256.verify(cert, tbsStart, tbsLen, cert, (short) (certOffset + certLen - signLen), signLen); } } 0 package io.banditoz.mchelper.utils.database.dao; import io.banditoz.mchelper.utils.database.CoordinatePoint; import io.banditoz.mchelper.utils.database.Database; import net.dv8tion.jda.api.entities.Guild; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class CoordsDaoImpl extends Dao implements CoordsDao { public CoordsDaoImpl(Database database) { super(database); } @Override public String getSqlTableGenerator() { return "CREATE TABLE IF NOT EXISTS `coordinates`( `guild_id` bigint(18) NOT NULL, `author_id` bigint(18) NOT NULL, `name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `x` bigint(20) NOT NULL, `z` bigint(20) NOT NULL, `last_modified` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), UNIQUE KEY `guild_name` (`guild_id`,`name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"; } @Override public void savePoint(CoordinatePoint point) throws SQLException { try (Connection c = DATABASE.getConnection()) { PreparedStatement ps = c.prepareStatement("INSERT INTO `coordinates` VALUES (?, ?, ?, ?, ?, (SELECT NOW()))"); ps.setLong(1, point.getGuildId()); ps.setLong(2, point.getAuthorId()); ps.setString(3, point.getName()); ps.setLong(4, point.getX()); ps.setLong(5, point.getZ()); ps.execute(); ps.close(); } } @Override public CoordinatePoint getPointByName(String name, Guild g) throws SQLException { try (Connection c = DATABASE.getConnection()) { PreparedStatement ps = c.prepareStatement("SELECT * FROM `coordinates` WHERE name=? AND guild_id=?"); ps.setString(1, name); ps.setLong(2, g.getIdLong()); CoordinatePoint point = buildPointFromResultSet(ps.executeQuery()); ps.close(); return point; } } @Override public void deletePointByName(String name, Guild g) throws SQLException { try (Connection c = DATABASE.getConnection()) { PreparedStatement ps = c.prepareStatement("DELETE FROM `coordinates` WHERE name=? AND guild_id=?"); ps.setString(1, name); ps.setLong(2, g.getIdLong()); ps.execute(); ps.close(); } } @Override public List getAllPointsForGuild(Guild g) throws SQLException { try (Connection c = DATABASE.getConnection()) { ArrayList points = new ArrayList<>(); PreparedStatement ps = c.prepareStatement("SELECT * FROM `coordinates` WHERE guild_id=(?)"); ps.setLong(1, g.getIdLong()); ResultSet rs = ps.executeQuery(); while (rs.next()) { points.add(buildPointFromResultSet(rs)); } ps.close(); return points; } } private CoordinatePoint buildPointFromResultSet(ResultSet rs) throws SQLException { CoordinatePoint point = new CoordinatePoint(); point.setGuildId(rs.getLong("guild_id")); point.setAuthorId(rs.getLong("author_id")); point.setName(rs.getString("name")); point.setX(rs.getLong("x")); point.setZ(rs.getLong("z")); point.setLastModified(rs.getTimestamp("last_modified")); return point; } } r-koubou/jfd2-mod /* * Created on 2004/12/29 * */ package com.nullfish.app.jfd2.viewer.constraints; import com.nullfish.app.jfd2.JFDComponent; import com.nullfish.app.jfd2.ui.container2.ContainerPosition; import com.nullfish.app.jfd2.viewer.FileViewerConstraints; /** * @author shunji * */ public class MainConstraints extends FileViewerConstraints { public static final String NAME = "main"; /** * @param name */ public MainConstraints() { super(NAME); } /** * * @param jfd * @return */ public ContainerPosition getPosition(JFDComponent component) { return ContainerPosition.MAIN_PANEL; } } test.js process.env.DEBUG = 'express-deprecate'; const express = require('express'); const app = express(); const config = { statusCode: 301, statusMessage: 'Deprecated', availableVersions: { "v1": { "deprecated": true }, "v2": { "deprecated": true, }, "v3": { "deprecated": false } } }; const apiVersioningV1 = require('./index')('v1', config); // enable API versioning app.use(apiVersioningV1); app.get('/v1/test', function(req, res) { res.send(); }); app.get('/v1/test2', function(req, res) { res.send(); }); app.get('/v2/test', function(req, res) { res.send(); }); app.listen(3000, function() { console.info('Server started'); });var mongoose = require('mongoose'); Schema = mongoose.Schema; ProfileSchema = new Schema({ profileUserId:{ type: String, }, user: { ref: 'User', type: String }, bio:{ type:String, }, ratings:{ type:Number, default:0 }, userPreferedTasks:{ type: String, }, userSkills:[ { type: String, } ], profilePic:{ type: String, default: 'default_user_profile_pic.jpg', }, location: { lat: String, long: String } , createdOn:{ type:Date, default:Date.now } }); mongoose.model('Profile',ProfileSchema); Profile = mongoose.model('Profile');import React from 'react' export default function Alert(props) { //-----------Capitalize First Letter----- const capitalize = (word)=>{ let lower = word.toLowerCase(); return lower.charAt(0).toUpperCase() + word.slice(1) } return ( props.alert &&
{capitalize(props.alert.type)}: {props.alert.msg}
) } import styles from './template.css'; import template from './template'; import AoflElement from '@aofl/web-components/aofl-element'; /** * @summary IconRoundTrendingFlatElement * @class IconRoundTrendingFlatElement * @extends {AoflElement} */ class IconRoundTrendingFlatElement extends AoflElement { /** * Creates an instance of IconRoundTrendingFlatElement. */ constructor() { super(); } /** * @readonly */ static get is() { return 'icon-round-trending-flat'; } /** * * @return {Object} */ render() { return super.render(template, [styles]); } } window.customElements.define(IconRoundTrendingFlatElement.is, IconRoundTrendingFlatElement); export default IconRoundTrendingFlatElement; import MainScreenHeader from './MainScreenHeader'; import Browse from './Browse'; import PlaylistCard from './PlaylistCard'; import Search from './Search'; import BackButton from './BackButton'; import OptionButton from './OptionButton'; import GameStatusBoard from './GameStatusBoard'; import CounterDisplay from './CounterDisplay'; export { MainScreenHeader, Browse, PlaylistCard, Search, BackButton, OptionButton, GameStatusBoard, CounterDisplay };workster-frontend/src/components/reusable/ExperienceFormItem.js import IconButton from "@mui/material/IconButton"; import DeleteIcon from '@mui/icons-material/Delete'; import React, {useState} from "react"; export default function ExperienceFormItem({position, title, company, location, remove, update, updateCheckbox, startDate, endDate, stillWork}) { const onChange = (e) => update(e.target, position); const onChangeCheckbox = (e) => updateCheckbox(position); return (

Job nr {position}

) }10-100 import _ from 'lodash' import BaseBuilder from "./BaseBuilder" import CryptoSpec from './CryptoSpec' export default class VirtualDeviceConfigSpecBackingSpec extends BaseBuilder { constructor (apiVersion) { super(apiVersion, { '@xsi:type': 'vim25:VirtualDeviceConfigSpecBackingSpec' }) } crypto (build) { if (!this.$versionGTE('6.5.0')) return if (this.$isConfigObject(build)) return this.$set('crypto', build) if (!_.isFunction(build)) throw new Error('crypto must supply a builder function or configuration object') let builder = new CryptoSpec(this.apiVersion) build(builder) return this.$push('crypto', builder.$config()) } parent (build) { if (!this.$versionGTE('6.5.0')) return if (this.$isConfigObject(build)) return this.$set('parent', build) if (!_.isFunction(build)) throw new Error('parent must supply a builder function or configuration object') let builder = new VirtualDeviceConfigSpecBackingSpec(this.apiVersion) build(builder) return this.$push('parent', builder.$config()) } }Data-Structures/graph/graph.js0 'use strict'; const { Queue } = require('../stacksAndQueues/stacks-and-queues'); class Vertex { constructor(value) { this.value = value; } } class Edge { constructor(vertex, weight) { this.vertex = vertex; this.weight = weight; } } class Graph { constructor() { this.adjacencyList = new Map(); } addVertex(value) { const newVertex = new Vertex(value); this.adjacencyList.set(newVertex, []); return newVertex; } addDirectedEdge(vertex1, vertex2, weight = 1) { if (!this.isVertexExists(vertex1) || !this.isVertexExists(vertex2)) { throw new Error('One or both the vertices not exists in the graph'); } const list = this.adjacencyList.get(vertex1); list.push(new Edge(vertex2, weight)); } getVertices() { const vertices = new Set(); for (let vertex of this.adjacencyList.keys()) { vertices.add(vertex); } return vertices; } getNeighbors(vertex) { const neighborsVertices = new Set(); for (let edge of this.adjacencyList.get(vertex)) { neighborsVertices.add({ vertex: edge.vertex, weight: edge.weight, }); } return neighborsVertices; } size() { return this.adjacencyList.size; } isVertexExists(vertex) { return this.adjacencyList.has(vertex); } BreadthFirst(node) { const visited = []; const queue = new Queue(); queue.enqueue(node); visited.push(node); // loop until traverse all the graph while (!queue.isEmpty()) { const tail = queue.dequeue(); const children = this.adjacencyList.get(tail); for (let child of children) { if (!visited.includes(child.vertex)) { visited.push(child.vertex); queue.enqueue(child.vertex); } } } return visited; } } module.exports = { Vertex, Edge, Graph, }; kontrakarnnn/wealththaicurrentresources/js/components/InsuranceAllcase.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import axios from 'axios'; import ReactTable from 'react-table' import 'react-table/react-table.css' import Dialog from 'react-dialog' import Picky from 'react-picky'; import 'react-picky/dist/picky.css'; // Include CSS import Modal from 'react-awesome-modal'; export default class InsuranceAllcase extends Component { constructor(){ super(); this.state = { cases:[], }; this.rowclick = this.rowclick.bind(this); this.showcase = this.showcase.bind(this); } componentDidMount(){ //console.log(window.location.href); const url = window.location.href; if(url.includes('?filterstage') == true) { const split2 = url.split('?filterstage'); //console.log(split2[1]) //console.log("hi") axios.get('/wealththaiinsurance/cases/load?filterstage'+split2[1]).then(response=>{ this.setState({cases:response.data}); //console.log('cases'+response.data); }).catch(errors=>{ //console.log(errors); }) } else { axios.get('/wealththaiinsurance/cases/load').then(response=>{ this.setState({cases:response.data}); //console.log('cases'); }).catch(errors=>{ //console.log(errors); }) } } showcase(e) { if(e.target.checked == true) { const url = window.location.href; if(url.includes('?filterstage') == true) { const split2 = url.split('?filterstage'); //console.log(split2[1]) //console.log("hi") axios.get('/wealththaiinsurance/cases/load?alludb=1?filterstage'+split2[1]).then(response=>{ this.setState({cases:response.data}); console.log('cases'+response.data); }).catch(errors=>{ //console.log(errors); }) } else { axios.get('/wealththaiinsurance/cases/load?alludb=1').then(response=>{ this.setState({cases:response.data}); console.log(response.data); }).catch(errors=>{ //console.log(errors); }) } } else { const url = window.location.href; if(url.includes('?filterstage') == true) { const split2 = url.split('?filterstage'); //console.log(split2[1]) //console.log("hi") axios.get('/wealththaiinsurance/cases/load?filterstage'+split2[1]).then(response=>{ this.setState({cases:response.data}); //console.log('cases'+response.data); }).catch(errors=>{ //console.log(errors); }) } else { axios.get('/wealththaiinsurance/cases/load').then(response=>{ this.setState({cases:response.data}); console.log(response.data); }).catch(errors=>{ //console.log(errors); }) } } console.log(e.target.checked) } rowclick(rowInfo){ ////console.log(rowInfo.row.id); window.open('/wealththaiinsurance/cases/'+rowInfo.row.id+'/detail/show','_self'); } render() { return (
กลับไปหน้าหลัก ไปหน้าค้นหาข้อมูล

"Loading.."} data={this.state.cases} getTrProps={(state, rowInfo) => ({ onClick: () =>this.rowclick(rowInfo) })} className="-striped -highlight" columns={[{ Header:

ข้อมูลงาน

, foldable: true, columns: [{ Header: "รหัส", accessor: "id" },{ Header: "ประเภทงาน", accessor: "case_type.name" },{ Header: "ชื่องาน", accessor: "name" },{ Header: "สถานะ", accessor: "case_status.name" },{ Header: "ช่องทางรับงาน", accessor: "case_channel.name" }, { Header: 'วันที่รับงาน', accessor: 'case_created_date', }] },{ Header:

บุคคลเกี่ยวข้องกับงาน

, foldable: true, columns: [ { Header: 'ผู้แจ้งงาน', accessor: 'block.name', },{ Header: "ผู้ประสานงาน", accessor: "coordiantor.firstname" },{ Header: "ผู้ให้คำปรึกษา", accessor: "partner_block.name" }] },{ Header:

ข้อมูลลูกค้า

, foldable: true, columns: [{ Header: "ชื่อ", accessor: "person.name" },{ Header: "นามสกุล", accessor: "person.lname" } ] },{ Header:

ข้อมูลทรัพย์สินของลูกค้า

, foldable: true, columns: [{ Header: "ชื่อ", accessor: "asset.name" },{ Header: "ทะเบียน", accessor: "asset.ref_name" } ] }] } />
); } } if (document.getElementById('insuranceallcase')) { ReactDOM.render(, document.getElementById('insuranceallcase')); } 0 export * from "./sample.actions.js"; "use strict"; //a set of array helper functions module.exports = function alibarray() { /** * moves an item in an array, mutates the array passed to it * @param {array} arr - array for operation to be executed on * @param {int} fromIndex - index of item to move * @param {int} toIndex - position in array to move item to - if value is bigger than length of array, item will be placed at the end */ var move = function (arr, fromIndex, toIndex) { var item = arr[fromIndex]; arr.splice(fromIndex, 1); arr.splice(toIndex, 0, item); }; /** * swaps the position of 2 items in an array, mutates the array passed to it * @param {array} arr - array for operation to be executed on * @param {int} indexA - index of item A to swap * @param {int} toIndex - index of item B to swap */ var swap = function (arr, indexA, indexB) { if (indexA < arr.length && indexB < arr.length) { var temp = arr[indexA]; arr[indexA] = arr[indexB]; arr[indexB] = temp; } }; /** * inserts an item into an array, mutates the array passed to it * @param {array} arr - array for operation to be executed on * @param {object/string/int} item - item to insert * @param {int} index - position in array to insert item - if value is bigger than length of array, item will be placed at the end * @example * // mutates array data to insert: { color: 'gold', size: 15 } at index 3 * alibarray().insert(data, { color: 'gold', size: 15 }, 3); */ var insert = function (arr, item, index) { arr.splice(index, 0, item); }; /** * checks if an array contains an object with props and values matching that of passed compareItem * @param {array} arr - array for operation to be executed on * @param {object} compareItem - item to compare * @param {string} [compareMode="all"] - compare mode 'all' matches all props on passed object 'any' any props match, 'exact' - exact match * @return {boolean} - true if array contains item match * @example * // check if array data contains object like: { color: 'green', size: 12 } * var result = alibarray().contains(data, { color: 'green', size: 12 }); */ var contains = function (arr, compareItem, compareMode) { if (position(arr, compareItem, compareMode) !== null) { return true; } else { return false; } }; /** * returns position of first item in array containing an object with props and values matching that of passed compareItem - if nothing is found, null is returned * @param {array} arr - array for operation to be executed on * @param {object} compareItem - item to compare * @param {string} [compareMode="all"] - compare mode 'all' matches all props on passed object 'any' any props match, 'exact' - exact match * @return {int} - positon if array contains item, otherwise null * @example * // should return 1 as item is at index pos 1 in the array * var result = alibarray().position(data, { color: 'green', size: 12 }); */ var position = function (arr, compareItem, compareMode) { var pos = null; //normalise compare mode var nCompareMode = 'all'; if (compareMode && (compareMode === 'any' || compareMode === 'exact')) { nCompareMode = compareMode; } //first enumerate obj props and values if (typeof (compareItem) === 'object') { var keys = []; var values = []; for (var prop in compareItem) { if (compareItem.hasOwnProperty(prop)) { //The current property is a direct property keys.push(prop); values.push(compareItem[prop]); } } //iterate through and match for (var i = 0; i < arr.length; i++) { var matches = 0; for (var j = 0; j < keys.length; j++) { if (arr[i][keys[j]] === values[j]) { //inc matches matches++; } } if (nCompareMode === 'all' && matches === keys.length) { pos = i; break; } if (nCompareMode === 'any' && matches > 0) { pos = i; break; } if (nCompareMode === 'exact' && matches === keys.length) { //now check prop count var pcount = 0; for (var prop in arr[i]) { if (arr[i].hasOwnProperty(prop)) { pcount++; } } if (pcount === keys.length) { pos = i; break; } } } } else { //compare primative for (var i = 0; i < arr.length; i++) { if (arr[i] === compareItem) { pos = i; break; } } } return pos; }; /** * returns number of items in array containing an object with props and values matching that of passed compareItem * @param {array} arr - array for operation to be executed on * @param {object} compareItem - item to compare * @return {int} - number of matching items * @example * // should return 3 as there are 3 items matching compareItem in the array * var result = alibarray().count(data, { color: 'green'}); */ var count = function (arr, compareItem) { var countMatches = 0; //first enumerate obj props and values if (typeof (compareItem) === 'object') { var keys = []; var values = []; for (var prop in compareItem) { if (compareItem.hasOwnProperty(prop)) { //The current property is a direct property keys.push(prop); values.push(compareItem[prop]); } } //iterate through and match for (var i = 0; i < arr.length; i++) { var matches = 0; for (var j = 0; j < keys.length; j++) { if (arr[i][keys[j]] === values[j]) { //inc matches matches++; } } if (matches === keys.length) { countMatches++; } } } else { //compare primative for (var i = 0; i < arr.length; i++) { if (arr[i] === compareItem) { countMatches++; } } } return countMatches; }; return { move: move, swap: swap, insert: insert, contains: contains, position: position, count: count }; }; src/components/IndexPageStyles/ExplorationStyles/styles.js import facepaint from 'facepaint' const breakpoints = [576, 768, 1024, 1200] const mq = facepaint(breakpoints.map(bp => `@media (min-width: ${bp}px)`)) export const explorationWrapper = mq({ width: '100%', paddingTop: [15, 15, 15, 15, 22], }) export const explorationText = mq({ fontSize: ['14px', '14px', '20px', '20px', '20px'], width: '100%', paddingBottom: [41, 41, 41, 41, 54], borderBottom: ['1.5px solid #D9D9D7', '2px solid #D9D9D7'], marginBottom: [20, 20, 20, 20, 60], }) export const explorationImageWrapper = mq({ width: '100%', }) export const explorationParagraph = mq({ margin: '0!important', lineHeight: ['18px', '18px', '18px', '18px', '28px'] }) export const explorationParagraphDate = mq(explorationParagraph, { color: '#CACAC8', }) export const explorationHeaderWrapper = mq({ paddingTop: [11, 11, 11, 11, 24], paddingBottom: [18, 18, 18, 48, 48], }) export const explorationHeader = mq(explorationParagraph, { fontSize: [14, 14, 20, 20, 20], }) export const explorationRightColumn = mq({ width: '100%', float: 'left', paddingLeft: [0, 0, 0, 0, '38%'], marginLeft: [0, 0, 0, 0, 17], '& > :last-child': { border: 'none', padding: 0, marginBottom: [60, 60, 60, 60, 205], }, }) // #################### END ##################### /** * @Author: hully * @Date: 2017-08-31 16:31:21 * @Email: * @Last modified by: hully * @Last modified time: 2017-09-01 17:37:53 */ "use strict"; import React from 'react'; import FilterLink from '../containers/filterLink'; class Footer extends React.Component { render() { return (

{"Show: "} All {" | "} Completed {" | "} Active

) } } export default Footer; birdwind/AutoTrasactionsrc/main/resources/static2/scripts/buckleManagement/buckleForm.js $(function () { var backUrl = "/page/buckle/management"; SetInitPage(false, backUrl); $("#form").formWizard({ id: "buckleCoreUuid", url: "/api/buckle/management/template/" + uuid, mainData: "response.buckleCore", noData: "findnodata(backUrl)", customizeForm: "customizeForm", fileUpload: { afterUpload: "afterUpload" }, }); //formWizard $("#save").click(function () { if ($(this).hasClass("waitaSec")) { return; } $(this).addClass("waitaSec"); var postData = $("#form").formCheck({ name: "buckleCore" }); if (!postData) { $(this).removeClass("waitaSec"); return; } $.ajax({ url: "/api/buckle/management", data: postData, method: (uuid.length) ? "POST" : "PUT", contentType: false, processData: false, dataType: "json", success: function (data) { if (!data.status) { $("#save").removeClass("waitaSec"); for (i of data.response) { $("#form [name='" + i.field + "']").errorMsg({ message: i.defaultMessage }); } } } // end of ajax success }); //end of ajax }) //end of save }); function customizeForm() { kendo.ui.progress($("#grid"), true); $("input[name='warehouseUuid']").kendoDropDownList({ dataSource: { transport: { read: { type: "GET", url: "/api/buckle/management/warehouses/list", dataType: "json" } }, schema: { data: function (data) { return data.response } } }, dataTextField: "text", dataValueField: "value", optionLabel: " ", }); $("input[name='bucklePurchaseCompanyUuid']").kendoDropDownList({ dataSource: { transport: { read: { type: "GET", url: "/api/buckle/management/purchaseCompanys/list", dataType: "json" } }, schema: { data: function (data) { return data.response } } }, dataTextField: "text", dataValueField: "value", optionLabel: " ", }); $("input[ name='buckleStatus']").kendoDropDownList({ dataSource: fw_formData.response.buckleCore.buckleStatus.keyValue, dataTextField: "text", dataValueField: "value", optionLabel: " ", }); if (uuid) { $("#buckleSituation").show(); $("#buckleSituationForm").show(); $(".k-dropdown").closest("fieldset").addClass("disabled");; $("input[ name='buckleStatus']").data("kendoDropDownList").enable(false); $("input[ name='bucklePurchaseCompanyUuid']").data("kendoDropDownList").enable(false); $("input[ name='warehouseUuid']").data("kendoDropDownList").enable(false); $.each(fw_formData.response.buckleSituation, function (index, value) { if (!value.title) return; $("#buckleSituationTemplate").find("nav").text(value.title); $("#buckleSituationTemplate").find("span").text(value.value); $("#buckleSituationTemplate").find("input").attr("name", index); $("#buckleSituationTemplate").find("input").val(value.value); $("#buckleSituationForm").find(".box_inputdata").append($("#buckleSituationTemplate").html()); }) } // setDropDownListUI("[name='bucklePurchaseCompany']", companyData, null, null); // setDropDownListUI("[name='status']", statusData, null, null); kendo.ui.progress($("#grid"), false); } //customizeForm function afterUpload() { fw_notification.show({}, "saveOrInsert"); setNoificationPosition(); setTimeout(function () { $(".drawCheck").hide().delay(460).queue(function () { location = "/page/buckle/management/"; $(this).dequeue(); }); }, 1000); } site = require("./config/site.js") module.exports = { trailingSlash: true, env: { TZ: site.timezone, }, } noofherder/ReactSolrApp import React from 'react'; import { Link } from 'react-router'; const NavBar = (props) => ; export default NavBar; mefarazath/product-vick /* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Constants from "./Constants"; import Span from "./Span"; describe("Span", () => { describe("isSiblingOf()", () => { it("should return true if the sibling span is provided", () => { const clientSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const serverSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10010, duration: 50, tags: {} }); expect(clientSpan.isSiblingOf(serverSpan)).toBe(true); expect(serverSpan.isSiblingOf(clientSpan)).toBe(true); }); it("should return false if a span from another trace is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const traceIdMismatchesSpan = new Span({ traceId: "trace-b-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); expect(span.isSiblingOf(traceIdMismatchesSpan)).toBe(false); }); it("should return false if a non equal span ID is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const spanIdMismatchedSpan = new Span({ traceId: "trace-a-id", spanId: "span-b-id", parentSpanId: "span-parent-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10010, duration: 50, tags: {} }); expect(span.isSiblingOf(spanIdMismatchedSpan)).toBe(false); }); it(`should return false if this span's or the provided span's kind is ${Constants.Span.Kind.CONSUMER}, ` + `${Constants.Span.Kind.PRODUCER} or empty`, () => { const clientKindSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const serverKindSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); const producerKindSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "producer-service", operationName: "get-resource", kind: Constants.Span.Kind.PRODUCER, startTime: 10000, duration: 100, tags: {} }); const consumerKindSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "consumer-service", operationName: "get-resource", kind: Constants.Span.Kind.CONSUMER, startTime: 10000, duration: 100, tags: {} }); const emptyKindSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "producer-service", operationName: "get-resource", startTime: 10000, duration: 100, tags: {} }); // Spans belonging to kinds other than client and server const kindSpansList = [clientKindSpan, serverKindSpan, producerKindSpan, consumerKindSpan, emptyKindSpan]; const nonSiblingSpansList = [producerKindSpan, consumerKindSpan, emptyKindSpan]; for (let i = 0; i < nonSiblingSpansList.length; i++) { for (let j = 0; j < kindSpansList.length; j++) { expect(nonSiblingSpansList[i].isSiblingOf(kindSpansList[j])).toBe(false); } } }); it(`should return false if this span and the provided span is of the same type; ` + `${Constants.Span.Kind.CLIENT}/${Constants.Span.Kind.SERVER}`, () => { const clientKindSpanA = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const clientKindSpanB = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const serverKindSpanA = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); const serverKindSpanB = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); // Same kind siblings of type client or server expect(clientKindSpanA.isSiblingOf(clientKindSpanB)).toBe(false); expect(serverKindSpanA.isSiblingOf(serverKindSpanB)).toBe(false); }); it("should return false if null/undefine is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); expect(span.isSiblingOf(null)).toBe(false); expect(span.isSiblingOf(undefined)).toBe(false); }); }); describe("isParentOf()", () => { it("should return true if the direct parent span is provided", () => { const childSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-b-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.PRODUCER, startTime: 10000, duration: 100, tags: {} }); const parentSpan = new Span({ traceId: "trace-a-id", spanId: "span-b-id", parentSpanId: "span-c-id", serviceName: "parent-service", operationName: "get-resource", startTime: 10050, duration: 145, tags: {} }); expect(parentSpan.isParentOf(childSpan)).toBe(true); }); it("should return true if the sibling server span is provided", () => { const siblingServerSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "sibling-span-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); const siblingClientSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "sibling-span-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10050, duration: 153, tags: {} }); expect(siblingClientSpan.isParentOf(siblingServerSpan)).toBe(true); }); it("should return false if the sibling client span is provided", () => { const siblingServerSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "sibling-span-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); const siblingClientSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "sibling-span-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10050, duration: 153, tags: {} }); expect(siblingServerSpan.isParentOf(siblingClientSpan)).toBe(false); }); it("should return false if a span from another trace is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-b-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const mismatchedTraceIdSpan = new Span({ traceId: "trace-b-id", spanId: "span-b-id", parentSpanId: "span-c-id", serviceName: "parent-service", operationName: "get-resource", startTime: 10000, duration: 100, tags: {} }); expect(mismatchedTraceIdSpan.isParentOf(span)).toBe(false); }); it("should return false if a non-related span is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-b-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const nonRelatedSpan = new Span({ traceId: "trace-a-id", spanId: "span-c-id", parentSpanId: "span-d-id", serviceName: "non-parent-service", operationName: "get-resource", startTime: 10000, duration: 100, tags: {} }); expect(nonRelatedSpan.isParentOf(span)).toBe(false); }); it("should return false if null/undefined is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); expect(span.isParentOf(null)).toBe(false); expect(span.isSiblingOf(undefined)).toBe(false); }); }); describe("addSpanReference()", () => { it("should add as child and return true if the child is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-b-id", serviceName: "consumer-service", operationName: "get-resource", kind: Constants.Span.Kind.CONSUMER, startTime: 10000, duration: 100, tags: {} }); const childSpan = new Span({ traceId: "trace-a-id", spanId: "span-x-id", parentSpanId: "span-a-id", serviceName: "vick-service", operationName: "get-resource", startTime: 10000, duration: 100, tags: {} }); expect(span.addSpanReference(childSpan)).toBe(true); expect(span.children.has(childSpan)).toBe(true); expect(span.parent).not.toBe(childSpan); expect(span.sibling).not.toBe(childSpan); }); it("should add as parent and return true if the parent is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-x-id", parentSpanId: "span-a-id", serviceName: "vick-service", operationName: "get-resource", kind: Constants.Span.Kind.PRODUCER, startTime: 10000, duration: 100, tags: {} }); const parentSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-b-id", serviceName: "consumer-service", operationName: "get-resource", startTime: 10000, duration: 100, tags: {} }); expect(span.addSpanReference(parentSpan)).toBe(true); expect(span.children.has(parentSpan)).toBe(false); expect(span.parent).toBe(parentSpan); expect(span.sibling).not.toBe(parentSpan); }); it("should add as child and sibling and return true if the sibling server span is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-b-id", serviceName: "consumer-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const siblingServerSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-b-id", serviceName: "vick-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); expect(span.addSpanReference(siblingServerSpan)).toBe(true); expect(span.children.has(siblingServerSpan)).toBe(true); expect(span.parent).not.toBe(siblingServerSpan); expect(span.sibling).toBe(siblingServerSpan); }); it("should add as parent and sibling and return true if the sibling client span is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-b-id", serviceName: "consumer-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); const siblingClientSpan = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-b-id", serviceName: "vick-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); expect(span.addSpanReference(siblingClientSpan)).toBe(true); expect(span.children.has(siblingClientSpan)).toBe(false); expect(span.parent).toBe(siblingClientSpan); expect(span.sibling).toBe(siblingClientSpan); }); it("should not add as child/parent/sibling and return false if non-related span is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-x-id", serviceName: "consumer-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); const nonRelatedSpan = new Span({ traceId: "trace-a-id", spanId: "span-b-id", parentSpanId: "span-y-id", serviceName: "vick-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); expect(span.addSpanReference(nonRelatedSpan)).toBe(false); expect(span.children.has(nonRelatedSpan)).toBe(false); expect(span.parent).not.toBe(nonRelatedSpan); expect(span.sibling).not.toBe(nonRelatedSpan); }); it("should not add as child/parent/sibling and return false if null is provided", () => { const span = new Span({ traceId: "trace-a-id", spanId: "span-a-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); expect(span.addSpanReference(null)).toBe(false); expect(span.children.size).toBe(0); expect(span.parent).toBeNull(); expect(span.sibling).toBeNull(); expect(span.addSpanReference(undefined)).toBe(false); expect(span.children.size).toBe(0); expect(span.parent).toBeNull(); expect(span.sibling).toBeNull(); }); }); describe("getUniqueId()", () => { it("should return a unique ID across traces", () => { const span = new Span({ traceId: "trace-id", spanId: "span-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", kind: Constants.Span.Kind.CLIENT, startTime: 10000, duration: 100, tags: {} }); const siblingSpan = new Span({ traceId: "trace-id", spanId: "span-server-id", parentSpanId: "span-parent-id", serviceName: "server-service", operationName: "get-resource", kind: Constants.Span.Kind.SERVER, startTime: 10000, duration: 100, tags: {} }); const parentSpan = new Span({ traceId: "trace-id", spanId: "span-parent-id", parentSpanId: "span-parent-id", serviceName: "client-service", operationName: "get-resource", startTime: 10000, duration: 100, tags: {} }); const differentTraceSpan = new Span({ traceId: "trace-different-id", spanId: "span-id", parentSpanId: "span-parent-id", serviceName: "test-service", operationName: "set-resource", kind: Constants.Span.Kind.SERVER, startTime: 200000, duration: 1203, tags: {} }); expect(span.getUniqueId()).not.toBe(siblingSpan.getUniqueId()); expect(span.getUniqueId()).not.toBe(parentSpan.getUniqueId()); expect(span.getUniqueId()).not.toBe(differentTraceSpan.getUniqueId()); }); }); }); /* eslint-disable import/no-extraneous-dependencies, no-console */ const suite = require('../lib/bench') const generateRequestIdA = (prefix = 'a00a') => { const requestId = ('' + Date.now() + (1 + Math.random())).substr(0, 22) + prefix Number(requestId) return requestId } const generateRequestIdB = (_prefix) => { const requestId = ('' + Date.now() + (1 + Math.random())).substr(0, 22) + (_prefix || 'a00a') Number(requestId) return requestId } const generateRequestIdC = (prefix = 'a00a') => { const requestId = `${`${Date.now()}${(1 + Math.random())}`.substr(0, 22)}${prefix}` Number(requestId) return requestId } const generateRequestIdD = (prefix) => { const requestId = `${`${Date.now()}${(1 + Math.random())}`.substr(0, 22)}${(prefix || 'a00a')}` Number(requestId) return requestId } suite .add(`${generateRequestIdA.name} `, generateRequestIdA) .add(`${generateRequestIdB.name} `, generateRequestIdB) .add(`${generateRequestIdC.name} `, generateRequestIdC) .add(`${generateRequestIdD.name} `, generateRequestIdD) .run({ async: false }) ryansloan/code-dot-or var spriteId = 0; var nativeSpriteMap = {}; var inputEvents = []; var behaviors = []; var userInputEventCallbacks = {}; var newSprites = {}; var totalPauseTime = 0; var currentPauseStartTime = 0; export var background; export var title = ''; export var subtitle = ''; export var defaultSpriteSize = 100; export function reset() { spriteId = 0; nativeSpriteMap = {}; inputEvents = []; behaviors = []; background = 'white'; title = subtitle = ''; userInputEventCallbacks = {}; defaultSpriteSize = 100; totalPauseTime = 0; } export function startPause(time) { currentPauseStartTime = time; } export function endPause(time) { totalPauseTime += time - currentPauseStartTime; currentPauseStartTime = 0; } /** * Returns World.seconds adjusted to exclude time during which the app was paused */ export function getAdjustedWorldTime(p5Inst) { const current = new Date().getTime(); return Math.round((current - p5Inst._startTime - totalPauseTime) / 1000); } /** * Returns a list of sprites, specified either by id, name, or animation name. * @param {Object} spriteArg - Specifies a sprite or group of sprites by id, name, or animation name. * @return {[Sprite]} List of sprites that match the parameter. Either a list containing the one sprite * the specified id/name, or a list containing all sprites with the specified animation. */ export function getSpriteArray(spriteArg) { if (!spriteArg) { return []; } if (spriteArg.hasOwnProperty('id')) { let sprite = nativeSpriteMap[spriteArg.id]; if (sprite) { return [sprite]; } } if (spriteArg.name) { let sprite = Object.values(nativeSpriteMap).find( sprite => sprite.name === spriteArg.name ); if (sprite) { return [sprite]; } } if (spriteArg.costume) { if (spriteArg.costume === 'all') { return Object.values(nativeSpriteMap); } else { return Object.values(nativeSpriteMap).filter( sprite => sprite.getAnimationLabel() === spriteArg.costume ); } } return []; } export function getAnimationsInUse() { let animations = new Set(); Object.values(nativeSpriteMap).filter(sprite => animations.add(sprite.getAnimationLabel()) ); return Array.from(animations); } /** * @param {string} animation * @return {number} Number of behaviors associated with the specified animation. */ export function getNumBehaviorsForAnimation(animation) { let numBehaviors = 0; behaviors.forEach(behavior => { if (behavior.sprite.getAnimationLabel() === animation) { numBehaviors++; } }); return numBehaviors; } /** * @param {number} spriteId * @return {number} Number of behaviors associated with the specified sprite */ export function getNumBehaviorsForSpriteId(spriteId) { let numBehaviors = 0; behaviors.forEach(behavior => { if (behavior.sprite.id === spriteId) { numBehaviors++; } }); return numBehaviors; } /** * @param {number} spriteId * @return {[String]} List containing the names of the behaviors associated * with the specified sprite */ export function getBehaviorsForSpriteId(spriteId) { let spriteBehaviors = []; behaviors.forEach(behavior => { if (behavior.sprite.id === spriteId) { spriteBehaviors.push(behavior.name); } }); return spriteBehaviors; } export function getSpriteIdsInUse() { let spriteIds = []; Object.keys(nativeSpriteMap).forEach(spriteId => spriteIds.push(parseInt(spriteId)) ); return spriteIds; } /** * Adds the specified sprite to the native sprite map * @param {Sprite} sprite * @returns {Number} A unique id to reference the sprite. */ export function addSprite(sprite, name, animation) { nativeSpriteMap[spriteId] = sprite; sprite.id = spriteId; if (name) { enforceUniqueSpriteName(name); sprite.name = name; } if (animation) { // Add to new sprites map so we can fire a "when sprite created" event if needed newSprites[animation] = newSprites[animation] || []; newSprites[animation].push(sprite); } spriteId++; return sprite.id; } /** * Enforces that two sprites cannot have the same name. This is enforced by clearing * the name from any existing sprites when a new sprite is created with that name. * @param {String} name */ function enforceUniqueSpriteName(name) { Object.values(nativeSpriteMap).forEach(sprite => { if (sprite.name === name) { sprite.name = undefined; } }); } /** * Removes a sprite from the native sprite map * @param {Number} spriteId */ export function deleteSprite(spriteId) { delete nativeSpriteMap[spriteId]; } export function registerPrompt(promptText, variableName, setterCallback) { if (!userInputEventCallbacks[variableName]) { userInputEventCallbacks[variableName] = { setterCallbacks: [], userCallbacks: [] }; } userInputEventCallbacks[variableName].setterCallbacks.push(setterCallback); } export function registerPromptAnswerCallback(variableName, userCallback) { if (!userInputEventCallbacks[variableName]) { userInputEventCallbacks[variableName] = { setterCallbacks: [], userCallbacks: [] }; } userInputEventCallbacks[variableName].userCallbacks.push(userCallback); } export function onPromptAnswer(variableName, userInput) { const callbacks = userInputEventCallbacks[variableName]; if (callbacks) { // Make sure to call the setter callback to set the variable // before the user callback, which may rely on the variable's new value callbacks.setterCallbacks.forEach(callback => { callback(userInput); }); callbacks.userCallbacks.forEach(callback => { callback(); }); } } export function addEvent(type, args, callback) { inputEvents.push({type: type, args: args, callback: callback}); } export function clearCollectDataEvents() { inputEvents = inputEvents.filter(e => e.type !== 'collectData'); } function atTimeEvent(inputEvent, p5Inst) { if (inputEvent.args.unit === 'seconds') { const previousTime = inputEvent.previousTime || 0; const worldTime = getAdjustedWorldTime(p5Inst); inputEvent.previousTime = worldTime; // There are many ticks per second, but we only want to fire the event once (on the first tick where // the time matches the event argument) if (worldTime === inputEvent.args.n && previousTime !== inputEvent.args.n) { // Call callback with no extra args return [{}]; } } else if (inputEvent.args.unit === 'frames') { if (p5Inst.frameCount === inputEvent.args.n) { // Call callback with no extra args return [{}]; } } // Don't call callback return []; } function collectDataEvent(inputEvent, p5Inst) { const previous = inputEvent.previous || 0; const worldTime = getAdjustedWorldTime(p5Inst); inputEvent.previous = worldTime; // Only log data once per second if (worldTime !== previous) { // Call callback with no extra args return [{}]; } else { // Don't call callback return []; } } function repeatForeverEvent(inputEvent, p5Inst) { // No condition to check, just always call callback with no extra args return [{}]; } function whenPressEvent(inputEvent, p5Inst) { if (p5Inst.keyWentDown(inputEvent.args.key)) { // Call callback with no extra args return [{}]; } else { // Don't call callback return []; } } function whilePressEvent(inputEvent, p5Inst) { if (p5Inst.keyDown(inputEvent.args.key)) { // Call callback with no extra args return [{}]; } else { // Don't call callback return []; } } function whenTouchEvent(inputEvent) { let getFired = function(map, spriteId, targetId) { if (map && map[spriteId] && map[spriteId][targetId]) { return map[spriteId][targetId].firedOnce; } }; let setFired = function(map, spriteId, targetId, fired) { if (!map) { map = {}; } if (!map[spriteId]) { map[spriteId] = {}; } if (!map[spriteId][targetId]) { map[spriteId][targetId] = {}; } map[spriteId][targetId].firedOnce = fired; }; let sprites = getSpriteArray(inputEvent.args.sprite1); let targets = getSpriteArray(inputEvent.args.sprite2); let callbackArgList = []; let previousCollisions = inputEvent.previous; // We need to clear out previous, so that events get re-triggered when sprite animations change inputEvent.previous = {}; sprites.forEach(sprite => { targets.forEach(target => { let firedOnce = getFired(previousCollisions, sprite.id, target.id); if (sprite.overlap(target)) { if (!firedOnce) { // Sprites are overlapping, and we haven't fired yet for this collision, // so we should fire the callback callbackArgList.push({ subjectSprite: sprite.id, objectSprite: target.id }); firedOnce = true; } } else { // Sprites are not overlapping (anymore), so we should make sure firedOnce is // set to false, so that if the sprites overlap again, we will fire the callback. // This is required to handle the case where sprites start touching, stop touching, and start // touching again- we want the callback to fire two times. firedOnce = false; } setFired(inputEvent.previous, sprite.id, target.id, firedOnce); }); }); return callbackArgList; } function whileTouchEvent(inputEvent) { let callbackArgList = []; let sprites = getSpriteArray(inputEvent.args.sprite1); let targets = getSpriteArray(inputEvent.args.sprite2); sprites.forEach(sprite => { targets.forEach(target => { if (sprite.overlap(target)) { callbackArgList.push({ subjectSprite: sprite.id, objectSprite: target.id }); } }); }); return callbackArgList; } function whenClickEvent(inputEvent, p5Inst) { let callbackArgList = []; if (p5Inst.mouseWentDown('leftButton')) { let sprites = getSpriteArray(inputEvent.args.sprite); sprites.forEach(sprite => { if (p5Inst.mouseIsOver(sprite)) { callbackArgList.push({clickedSprite: sprite.id}); } }); } return callbackArgList; } function whileClickEvent(inputEvent, p5Inst) { let callbackArgList = []; let sprites = getSpriteArray(inputEvent.args.sprite); sprites.forEach(sprite => { if (p5Inst.mousePressedOver(sprite)) { callbackArgList.push({clickedSprite: sprite.id}); } }); return callbackArgList; } function whenSpriteCreatedEvent(inputEvent, p5Inst) { let callbackArgList = []; let sprites = newSprites[inputEvent.args.costume] || []; sprites.forEach(sprite => { callbackArgList.push({newSprite: sprite.id}); }); return callbackArgList; } /** * @param {Object} inputEvent * @param p5Inst - the running P5 instance * Checks whether the condition of the event is met, and if so, returns the arguments to pass to the user's * callback function. An event can trigger multiple invocations of the callback in a single tick of the * draw loop, so this will return an array of callback arguments. * @return {Array.} Each element of this array gives the arguments that will be passed * to the event callback. */ function getCallbackArgListForEvent(inputEvent, p5Inst) { switch (inputEvent.type) { case 'atTime': return atTimeEvent(inputEvent, p5Inst); case 'collectData': return collectDataEvent(inputEvent, p5Inst); case 'repeatForever': return repeatForeverEvent(inputEvent, p5Inst); case 'whenpress': return whenPressEvent(inputEvent, p5Inst); case 'whilepress': return whilePressEvent(inputEvent, p5Inst); case 'whentouch': return whenTouchEvent(inputEvent); case 'whiletouch': return whileTouchEvent(inputEvent); case 'whenclick': return whenClickEvent(inputEvent, p5Inst); case 'whileclick': return whileClickEvent(inputEvent, p5Inst); case 'whenSpriteCreated': return whenSpriteCreatedEvent(inputEvent, p5Inst); } } export function runEvents(p5Inst) { inputEvents.forEach(inputEvent => { let callbackArgList = getCallbackArgListForEvent(inputEvent, p5Inst); callbackArgList.forEach(args => { inputEvent.callback(args); }); }); // Clear newSprites. Used for whenSpriteCreated events and should be reset every tick. newSprites = {}; } export function addBehavior(sprite, behavior) { if (sprite && behavior) { let existing = behaviors.find( b => b.sprite === sprite && b.name === behavior.name ); if (!existing) { behaviors.push({ func: behavior.func, name: behavior.name, sprite: sprite }); } } } export function removeAllBehaviors(sprite) { behaviors = behaviors.filter(behavior => behavior.sprite !== sprite); } export function removeBehavior(sprite, behavior) { if (sprite && behavior) { let index = behaviors.findIndex( b => b.sprite === sprite && b.name === behavior.name ); if (index !== -1) { behaviors.splice(index, 1); } } } export function runBehaviors() { behaviors.forEach(behavior => behavior.func({id: behavior.sprite.id})); } example_method1_extended.js0 const express = require(`express`); const ezhtml = require(`./index`); const app = express(); app.get(`/`, (req, res, next) => { const p = new ezhtml.Page(); /** Automatically added to */ p.title().text(`My Example Page`); p.style().text(`p.myClass { font-weight: bold; font-family: Arial, helvetica, sans-serif; }`); p.script().src(`https://code.jquery.com/jquery-3.3.1.js`); /** Automatically added to */ p.div().style(`width: 100%; text-align: center;`); /** Explicitly added to last
else */ p.h2(`div`).style(`color: blue;`).text(`My Example Page`); /** Explicitly added to */ p.div(`body`).style(`position: relative; width: 50%; left: 25%; text-align: center;`); /** Automatically added to last
else */ p.orderedList(); /** Automatically added to last
    or
      */ p.listItem().text(`Ordered List Item One`); p.listItem().text(`Ordered List Item Two`); p.listItem().text(`Ordered List Item Three`); /** Automatically added to last
      else */ p.lineBreak(); /** Automatially added to last
      ,
      , or
      else */ p.select().name(`mySelect`); /** Automatically added to last , or
      */ p.option().value(1).text(`Primary Option 1`); p.option().value(2).text(`Primary Option 2`); p.option().value(3).text(`Primary Option 3`); /** Automatically added to last , or
      */ p.option().value(1).text(`Secondary Option 1`); p.option().value(2).text(`Secondary Option 2`); p.option().value(3).text(`Secondary Option 3`); /** Automatically added to last
      else */ p.lineBreak(); /** Automatically added to last
      else */ p.paragraph().addClass(`myClass`).text(`This is my example paragraph in bold Arial font.`); /** Automatically added to last
      else */ p.lineBreak(); /** Automatically added to last
      else */ p.picture(); /** Explicitly add to last */ p.image(`picture`).width(100).height(100).src(`/images/example.png`); /** Automatically added to last
      else */ p.lineBreak(); /** Automatically added to last
      else */ p.table(); /** Automatically added to last */ p.tableHead(); /** Automatically added to last , , or */ p.tableRow(); /** Automatically added to last */ p.tableHeader().text(`Header 1`); p.tableHeader().text(`Header 2`); p.tableHeader().text(`Header 3`); /** Automatically added to last
      */ p.tableBody(); /** Automatically added to last , , or */ p.tableRow(); /** Automatically added to last */ p.tableData().text(`Row 1 Col 1 Data`); p.tableData().text(`Row 1 Col 2 Data`); p.tableData().text(`Row 1 Col 3 Data`); /** Automatically added to last , , or */ p.tableRow(); /** Automatically added to last */ p.tableData().text(`Row 2 Col 1 Data`); p.tableData().text(`Row 2 Col 2 Data`); p.tableData().text(`Row 2 Col 3 Data`); /** Automatically added to last
      */ p.tableFooter(); /** Automatically added to last , , or */ p.tableRow(); /** Automatically added to last */ p.tableData().text(`Footer 1`); p.tableData().text(`Footer 2`); p.tableData().text(`Footer 3`); /** Render HTML and send as response */ res.send(p.render()); }); app.listen(8080, () => { console.log(`Web server up and running on port 8080!`); }); define(function(require) { 'use strict'; var q = require('q'); var PF = require('js/app/obj'); var logger = PF.logger.get('root/js/apps/entry/entities'); PF.module('EntryApp.Entities', function(Entities, PF, Backbone, Marionette, $, _) { require('js/common/base_entities'); Entities.Entry = PF.Entities.PFDatabaseModel.extend({ __name: 'Entry', urlRoot: '/api/entry/entry' }); Entities.EntryCollection = PF.Entities.PFDatabaseCollection.extend({ __name: 'EntryCollection', url: '/api/entry/entry', model: Entities.Entry }); Entities.Tag = PF.Entities.PFDatabaseModel.extend({ __name: 'Tag', urlRoot: '/api/entry/tag', initialize: function() { _.extend(this, new Backbone.Picky.Selectable(this)); } }); Entities.TagCollection = PF.Entities.PFDatabaseCollection.extend({ __name: 'TagCollection', url: '/api/entry/tag', model: Entities.Tag, initialize: function() { _.extend(this, new Backbone.Picky.SingleSelect(this)); } }); var API = { // TODO: Use tag_string to filter returned entries when fetching from DB get_entries_promise: function(tag_string) { logger.trace('API.get_entries_promise -- enter'); var deferred = q.defer(); var entry_collection = new Entities.EntryCollection(); entry_collection.fetch({ success: function(entry_collection) { deferred.resolve(entry_collection); }, error: function() { deferred.resolve(undefined); } }); return deferred.promise; }, get_tags_promise: function() { logger.trace('API.get_tags_promise -- enter'); var deferred = q.defer(); var tag_collection = new Entities.TagCollection(); tag_collection.fetch({ success: function(tag_collection) { deferred.resolve(tag_collection); }, error: function() { deferred.resolve(undefined); } }); return deferred.promise; } }; PF.reqres.setHandler('entryapp:entities:entries', function(tag_string) { return API.get_entries_promise(tag_string); }); PF.reqres.setHandler('entryapp:entities:tags', function() { return API.get_tags_promise(); }); }); return undefined; }); var userStd = [ { id: 1, username: "testadmin", password: "", hocvan: "", fullName: "", dateBirth: "12/2/1993", phoneNumber: "031288121", diemToan: 8.7, diemLy: 8.5, diemHoa: 8.0, diemVan: 2.3, addRess: "Tô Ký, phường Tân Chánh Hiệp, quận 12, tp Hồ Chí Minh", }, { nameStudent: "", maHs: "18511", ngaySinh: "2000-02-01", soDienThoai: "03844332", hocvan: "hocsinh", diemToan: "8", diemLy: "8", diemVan: "1", diemHoa: "9", diemSinh: "8", diemTin: "2", diemLichSu: "8", diemDiaLy: "3", diemGDCD: "7", id: 2, }, ]; var test; var axios = require("axios"); var config = { method: "get", url: "http://localhost:3000/data/", headers: {}, }; axios(config) .then(function (response) { //userStd.push(JSON.parse(response.data)); }) .catch(function (error) { console.log(error); }); export default userStd; import { Validation } from '../constants/validation_errors.js' import DomainDictionaryServices from '../servicers/design/domain_dictionary_services.js'; import DomainDictionaryValidationApi from '../apiValidation/apiDomainDictionaryValidation.js'; //====================================================================================================================== // // Meteor Validated Methods for Domain Dictionary // //====================================================================================================================== export const addNewTerm = new ValidatedMethod({ name: 'domainDictionary.addNewTerm', validate: new SimpleSchema({ userRole: {type: String}, view: {type: String}, mode: {type: String}, designId: {type: String}, designVersionId: {type: String} }).validator(), run({userRole, view, mode, designId, designVersionId}){ // Server validation const result = DomainDictionaryValidationApi.validateAddNewTerm(userRole, view, mode); if (result != Validation.VALID) { throw new Meteor.Error('domainDictionary.addNewTerm.failValidation', result) } // Server action try { DomainDictionaryServices.addNewTerm(designId, designVersionId); } catch (e) { console.log(e.stack); throw new Meteor.Error(e.code, e.stack) } } }); export const updateTermName = new ValidatedMethod({ name: 'domainDictionary.updateTermName', validate: new SimpleSchema({ userRole: {type: String}, view: {type: String}, mode: {type: String}, termId: {type: String}, newName: {type: String} }).validator(), run({userRole, view, mode, termId, newName}){ // Server validation const result = DomainDictionaryValidationApi.validateUpdateTermName(userRole, view, mode, termId, newName); if (result != Validation.VALID) { throw new Meteor.Error('domainDictionary.updateTermName.failValidation', result) } // Server action try { DomainDictionaryServices.updateTermName(termId, newName, null); } catch (e) { console.log(e.stack); throw new Meteor.Error(e.code, e.stack) } } }); export const updateTermDefinition = new ValidatedMethod({ name: 'domainDictionary.updateTermDefinition', validate: new SimpleSchema({ userRole: {type: String}, view: {type: String}, mode: {type: String}, termId: {type: String}, newDefinitionRaw: {type: Object, blackbox: true} }).validator(), run({userRole, view, mode, termId, newDefinitionRaw}){ // Server validation const result = DomainDictionaryValidationApi.validateUpdateTermDefinition(userRole, view, mode); if (result != Validation.VALID) { throw new Meteor.Error('domainDictionary.updateTermDefinition.failValidation', result) } // Server action try { DomainDictionaryServices.updateTermDefinition(termId, newDefinitionRaw); } catch (e) { console.log(e.stack); throw new Meteor.Error(e.code, e.stack) } } }); export const removeTerm = new ValidatedMethod({ name: 'domainDictionary.removeTerm', validate: new SimpleSchema({ userRole: {type: String}, view: {type: String}, mode: {type: String}, termId: {type: String} }).validator(), run({userRole, view, mode, termId}){ // Server validation const result = DomainDictionaryValidationApi.validateRemoveTerm(userRole, view, mode); if (result != Validation.VALID) { throw new Meteor.Error('domainDictionary.removeTerm.failValidation', result) } // Server action try { DomainDictionaryServices.removeTerm(termId); } catch (e) { console.log(e.stack); throw new Meteor.Error(e.code, e.stack) } } }); $(document).ready(function() { // Formulaire d'ajout d'une valeur à un attribut $('#attribut-form-add').submit(function() { var attributeId = $(this).data('idatt'); var attributeVal = $('#attribut-add-input').val(); console.log(attributeVal); $.post("{{path('ideale_copieback_office_ajoutValeur')}}", { id: attributeId, val: attributeVal }, function(data) { console.log(data); if (data.success) { console.log('ok'); } else { console.log('not ok'); } }, 'json'); return false; }) });const { createUserModel } = require("./user.js"); const { initDatabase } = require("@todastic/storage-mongo"); const config = require("@todastic/config"); describe("User", () => { let User; let mongoose; beforeAll(async () => { const db = await initDatabase({ config, logger: console }); mongoose = db.mongoose; User = createUserModel({ mongoose }); }); afterAll(async () => { await mongoose.disconnect(); }); it("is invalid without 'username'", testWithout("username")); it("is invalid without 'password'", testWithout("password")); it("is able to detect bad email addresses", done => { let user = new User({ username: "berti", password: "", email: "not@fancy" }); user.validate(err => { expect(err.errors.email).toBeDefined(); done(); }); }); function testWithout(field) { return done => { let hash = { username: "berti", password: "" }; delete hash[field]; let user = new User(hash); user.validate(err => { expect(err.errors[field]).toBeDefined(); done(); }); }; } }); const hre = require('hardhat'); async function main() { const CertWork = await hre.ethers.getContractFactory('CertWork'); const certWork = await CertWork.deploy(); await certWork.deployed(); console.log('CertWork deployed to:', certWork.address); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); src/fields.js import * as Tags from "./tags" import { nameWithContext } from "./utils" export const CheckBox = nameWithContext(Tags.CheckBoxTag) export const ColorField = nameWithContext(Tags.ColorFieldTag) export const DateField = nameWithContext(Tags.DateFieldTag) export const DatetimeField = nameWithContext(Tags.DatetimeFieldTag) export const DatetimeLocalField = nameWithContext(Tags.DatetimeLocalFieldTag) export const EmailField = nameWithContext(Tags.EmailFieldTag) export const HiddenField = nameWithContext(Tags.HiddenFieldTag) export const Label = nameWithContext(Tags.LabelTag, "htmlFor") export const MonthField = nameWithContext(Tags.MonthFieldTag) export const NumberField = nameWithContext(Tags.NumberFieldTag) export const PasswordField = nameWithContext(Tags.PasswordFieldTag) export const Radio = nameWithContext(Tags.RadioTag) export const RangeField = nameWithContext(Tags.RangeFieldTag) export const SearchField = nameWithContext(Tags.SearchFieldTag) export const Select = nameWithContext(Tags.SelectTag) export const Submit = nameWithContext(Tags.SubmitTag) export const TelephoneField = nameWithContext(Tags.TelephoneFieldTag) export const TextArea = nameWithContext(Tags.TextAreaTag) export const TextField = nameWithContext(Tags.TextFieldTag) export const TimeField = nameWithContext(Tags.TimeFieldTag) export const UrlField = nameWithContext(Tags.UrlFieldTag) export const WeekField = nameWithContext(Tags.WeekFieldTag) export const DestroyField = () => media/javascripts/app.js (function($) { $().ready(function() { // Django CSRF protection for AJAX requests. Omnomnom $('html').ajaxSend(function(event, xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }); /* Auto-expand all textareas */ var textareaIntervalTimer; $('textarea').live('focusin focusout', function(event) { if (event.type === 'focusout') { clearInterval(textareaIntervalTimer); } if (event.type === 'focusin') { var text = $(textarea).val(), textarea = this; textareaIntervalTimer = setInterval(function() { if (text === $(textarea).val()) { return; } text = $(textarea).val(); var lines = ((text.length - (text.length % 60)) / 60) + 2, multiplier = $(textarea).css('line-height') || 1; $(textarea).css({ height: (lines * parseInt(multiplier)) + 'px' }); }, 750); } }); }); })(jQuery); /* eslint-env jest */ var postcss = require('postcss') var plugin = require('./') function run (input, output, opts) { return postcss([plugin(opts)]) .process(input, { from: undefined }) .then(result => { expect(result.css).toEqual(output) expect(result.warnings().length).toBe(0) }) } describe('transform value', () => { it('handles rpx', () => { return run('a{width: 2rpx;}', 'wx-a{width: %%?2rpx?%%;}', {}) }) it('handles minus rpx', () => { return run('a{width: -2rpx;}', 'wx-a{width: %%?-2rpx?%%;}', {}) }) it('handles float rpx', () => { return run('a{width: 2.3rpx;}', 'wx-a{width: %%?2.3rpx?%%;}', {}) }) it('handles .number rpx', () => { return run('a{width: .3rpx;}', 'wx-a{width: %%?0.3rpx?%%;}', {}) }) it('leave alone with rpx in url', () => { return run( 'a{background: 40rpx 73% url(data:image/gif;base64,2rpxR0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7)}', 'wx-a{background: %%?40rpx?%% 73% url(data:image/gif;base64,', {} ) }) }) describe('transform built-in selectors', () => { it('wx-icon', () => { return run('icon{}', 'wx-icon{}', {}) }) it('page', () => { return run('page{}', 'body{}', {}) }) }) describe('grouping selectors', () => { it('space joined', () => { return run( 'icon, #page, .page, page{}', 'wx-icon, #page, .page, body{}', {} ) }) it('no space', () => { return run('icon,#page,.page,page{}', 'wx-icon,#page,.page,body{}', {}) }) }) describe('combinators', () => { it('space joined ', () => { return run('page .page{}', 'body .page{}', {}) }) it('dot joined', () => { return run('page.page{}', 'body.page{}', {}) }) it('hash joined', () => { return run('page#page{}', 'body#page{}', {}) }) it('mixed', () => { return run('page.page#page{}', 'body.page#page{}', {}) }) }) describe("don't transform", () => { it('class selectors', () => { return run('.page{}', '.page{}', {}) }) it('id selectors', () => { return run('#page{}', '#page{}', {}) }) it('tag start with "wx-"', () => { return run('wx-image{}', 'wx-image{}', {}) }) it('selectors inside keyframes', () => { return run( '@keyframes spin { 0% { height: 0; } }', '@keyframes spin { 0% { height: 0; } }', {} ) }) }) describe('media query', () => { it('transform nested declarations, media query rpx ignored', () => { return run( '@media screen and (min-width: 480rpx) {page{width:2rpx}.page{}icon{}}', '@media screen and (min-width: 480rpx) {body{width:%%?2rpx?%%}.page{}wx-icon{}}', {} ) }) }) "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _promise = require("babel-runtime/core-js/promise"); var _promise2 = _interopRequireDefault(_promise); exports.default = sleep; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Await for a certain amount of time. * * @example * ```js * async function main() { * await sleep(10000) * console.log('Logged after 10000 milliseconds!') * } * main() * ``` */ function sleep(duration) { var resolve = null; var promise = new _promise2.default(function (r) { return resolve = r; }); setTimeout(resolve, duration); return promise; } //# sourceMappingURL=sleep.js.mapenyojs/enact100-1000 import LS2Request from '../LS2Request'; describe('LS2Request', () => { const nop = () => {}; describe('callback', () => { const invalidResponse = '{invalid: json'; const failedResponse = '{"errorCode": 101}'; const successfulResponse = '{"returnValue": true}'; it ('should return an error for a null msg', () => { const request = new LS2Request(); const onFailure = jest.fn(); request.callback(nop, onFailure, nop, null); const expected = {errorCode: -1}; const actual = onFailure.mock.calls[0][0]; expect(actual).toMatchObject(expected); }); it ('should return an error for invalid JSON', () => { const request = new LS2Request(); const onFailure = jest.fn(); request.callback(nop, onFailure, nop ); const expected = {errorCode: -1}; const actual = onFailure.mock.calls[0][0]; expect(actual).toMatchObject(expected); }); it ('should invoke onFailure for a valid, failed request', () => { const request = new LS2Request(); const onFailure = jest.fn(); request.callback(nop, onFailure, nop, failedResponse); const expected = {errorCode: 101}; const actual = onFailure.mock.calls[0][0]; expect(actual).toMatchObject(expected); }); it ('should invoke onSuccess for a valid request', () => { const request = new LS2Request(); const onSuccess = jest.fn(); request.callback(onSuccess, nop, nop, successfulResponse); const expected = {returnValue: true}; const actual = onSuccess.mock.calls[0][0]; expect(actual).toMatchObject(expected); }); it ('should invoke onComplete for a valid request', () => { const request = new LS2Request(); const onComplete = jest.fn(); request.callback(nop, nop, onComplete, successfulResponse); const expected = {returnValue: true}; const actual = onComplete.mock.calls[0][0]; expect(actual).toMatchObject(expected); }); it ('should invoke onComplete for an invalid request', () => { const request = new LS2Request(); const onComplete = jest.fn(); request.callback(nop, nop, onComplete, invalidResponse); const expected = {errorCode: -1}; const actual = onComplete.mock.calls[0][0]; expect(actual).toMatchObject(expected); }); it ('should invoke onComplete for a valid, failed request', () => { const request = new LS2Request(); const onComplete = jest.fn(); request.callback(nop, nop, onComplete, failedResponse); const expected = {errorCode: 101}; const actual = onComplete.mock.calls[0][0]; expect(actual).toMatchObject(expected); }); }); }); const fs = require("fs"); const path = require("path"); const srcDir = path.resolve(__dirname, "src"); module.exports = () => { const entry = fs.readdirSync(srcDir).reduce( (a, file) => ({ ...a, [path.basename(file, ".js")]: path.resolve(srcDir, file), }), {} ); return { mode: process.env.NODE_ENV === 'production' ? 'production' : "development", entry, output: { path: path.resolve(__dirname, "compiled"), publicPath: "dist/", filename: "[name].js", }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env", "@babel/preset-react"], }, }, }, ], }, }; }; // 引入coolsite360交互配置设定 require('coolsite.config.js'); var qcloud = require('../../bower_components/wafer-client-sdk/index.js'); var config = require('../../config.js') // 获取全局应用程序实例对象 var app = getApp(); // 创建页面实例对象 Page({ /** * 页面名称 */ name: "showsignuplist", /** * 页面的初始数据 */ data: { acId:"", signUpList:"" }, /** * 生命周期函数--监听页面加载 */ onLoad:function(param) { // 注册coolsite360交互模块 app.coolsite360.register(this); this.setData({ acId: param.acId }) const self = this; wx.showLoading({ title: '加载中', }) wx.request({ url: 'your url', data:{ acId:self.data.acId }, success: function (res) { var result = res.data; var jsonLength = 0; console.log("请求成功,获取到的数据为:", result); var array = new Array(); for (var key in result) { array[key] = result[key] } console.log('转换后的数组为:', array); self.setData({ signUpList: array, }); wx.hideLoading(); wx.showToast({ title: '加载完成', icon:'success', duration:1000, }) }, fail: function (err) { console.log("请求失败:", err); } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady () { }, /** * 生命周期函数--监听页面显示 */ onShow () { // 执行coolsite360交互组件展示 app.coolsite360.onShow(this); }, /** * 生命周期函数--监听页面隐藏 */ onHide () { }, /** * 生命周期函数--监听页面卸载 */ onUnload () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh () { }, //以下为自定义点击事件 tap_8a585329:function(e){ //触发coolsite360交互事件 app.coolsite360.fireEvent(e,this); }, showSignUpInfo:function(event){ wx.navigateTo({ url: '../showsignupinfo/showsignupinfo?acId=' + this.data.acId + '&openId=' + event.currentTarget.dataset.openid, }) }, onPullDownRefresh: function () { const self = this; wx.request({ url: 'your url', data: { acId: self.data.acId }, success: function (res) { wx.stopPullDownRefresh() var result = res.data; var jsonLength = 0; console.log("请求成功,获取到的数据为:", result); var array = new Array(); for (var key in result) { array[key] = result[key] } console.log('转换后的数组为:', array); self.setData({ signUpList: array, }); wx.showToast({ title: '刷新成功', icon:'success' }) }, fail: function (err) { console.log("请求失败:", err); } }) } }) 'use strict'; angular.module('myApp.voltage', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/voltage', { templateUrl: 'voltage/voltage.html', controller: 'voltageCtrl' }); }]) .controller('voltageCtrl', [function() { }]);const SHARED_MESSAGES = { SKIP_NOEMAIL: "User doesn't have an email address and will not be synchronized to customer.io", SKIP_NOTINSEGMENTS: "User is not in the whitelisted segments and will not be synchronized to customer.io", SKIP_NOCHANGES: "The contact in customer.io is already in synchronization with the user in Hull. No changes to process.", SKIP_NOTWHITELISTEDEVENTS: "The following events are not whitelisted and have been skipped for processing.", SKIP_NOIDVALUE: "User doesn't have a value for the attribute which is mapped to the identifier in customer.io.", ERROR_INVALIDEVENT: "Payload couldn't be mapped to Hull event.", ERROR_NOUSERIDENT: "Payload didn't contain any identifier for a Hull user.", ERROR_TRACKFAILED: "Event tracking failed, see innerException for details.", ERROR_VALIDATION_MAXLENGTHID: "The unique identifier exceeds the limit, maximum size allowed is 150 bytes.", ERROR_VALIDATION_MAXLENGTHNAME: "The attribute name exceeds the limit, maximum size allowed is 150 bytes. The following attribute is invalid:", ERROR_VALIDATION_MAXLENGTHVALUE: "The value for the attribute exceeds the limit, maximum size allowed is 1000 bytes. The following data is invalid:", ERROR_VALIDATION_INVALIDEMAILID: "The value for the identifier is an invalid email address:" }; module.exports = SHARED_MESSAGES; import {BaseService} from '../../../services/BaseService'; import {API_Contacts} from '../../../utils/API'; import {HTTP} from '../../../utils/HttpTools'; import {ResponseCode} from '../../../utils/Enums'; export default class MessageService { constructor() { this.baseService = new BaseService() } requestDialogList(chatId, success, fail) { let param = { ChatID: chatId } this.baseService.sendRequest(API_Contacts.GetContactsByChatID, param, (response) => { if (response.code === ResponseCode.ok) { success && success(response.data) } },(error) => { fail && fail(error) }) } } 0 import React from "react" // import Layout from "../layout" import { Link } from 'gatsby' import plus from "../../images/bx-plus.png" const uuidv4 = require('uuid/v4'); const CatalogProduct = ({myPost, searchTerm}) => { if(myPost[0] === undefined){ return (

      В этой категории продуктов нет!

      ) } return (

      Наши продукты

      { myPost.map(po=>{ if( po.node.title.toLowerCase().indexOf(searchTerm.toLowerCase()) >= 0 //фильтр по словам //фильтр по катгории ){ // console.log(locat) return(
      plus

      {po.node.title}

      ) }else{ return undefined } }) }
      ) } export default CatalogProduct 0 import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ToEditorButton } from 'views/components'; const action = { comments: 'editComment', posts: 'editPost', }; const iconDelete = ( Delete ); class EditionControls extends Component { state = { errorMessage: '', }; componentWillReceiveProps(nextProps) { const { history, isDeleting, match: { params: { category } }, } = this.props; /** * TODO: Improve this. Add a loading message, maybe with a spinner, * notifying there is an edit/new post addition in progress. */ const isDeletingChanged = isDeleting !== nextProps.isDeleting; const deleteEnd = isDeletingChanged && !nextProps.isDeleting; if (isDeletingChanged) { if (deleteEnd) { if (nextProps.deleteHasFailed) { /* The post deletion failed */ this.setState({ errorMessage: 'There was an error deleting the post', }); return; } /** * The post was succesfully deleted, redirect to the category page if * on a PostScreen or to the main page if not */ history.replace(`/${typeof category === 'string' ? category : ''}`); } } } onKeyUp = (event) => { if (event.key === 'Enter') { this.props.onDelete(); } } render() { const { onDelete, content, type, } = this.props; const pathname = `/${content.category}/${content.id}`; return ( {iconDelete} {this.state.errorMessage} ); } } export default EditionControls; /* eslint-disable react/forbid-prop-types */ EditionControls.propTypes = { onDelete: PropTypes.func.isRequired, /** * Info of the comment or post being edited, to prefill the `form` fields. */ content: PropTypes.object.isRequired, deleteHasFailed: PropTypes.bool.isRequired, history: PropTypes.object.isRequired, isDeleting: PropTypes.bool.isRequired, match: PropTypes.object.isRequired, type: PropTypes.string.isRequired, }; /* eslint-enable react/forbid-prop-types */ export { default as ModalProvider } from "./ModalProvider"; export { default as useModal } from "./useModal"; dsmwong/function-templates /* eslint-disable camelcase, prefer-destructuring, dot-notation, consistent-return */ const path0 = Runtime.getFunctions().helpers.path; const { getParam, setParam } = require(path0); const AWS = require('aws-sdk'); const ts = Math.round(new Date().getTime() / 1000); const tsTomorrow = ts + 17 * 3600; async function createAppointment(context, appointment) { context.TWILIO_FLOW_SID = await getParam(context, 'TWILIO_FLOW_SID'); // ---------- execute flow const now = new Date(); appointment.event_datetime_utc = now.toISOString(); const params = { to: appointment.patient_phone, from: context.TWILIO_PHONE_NUMBER, parameters: appointment, }; const response = await context .getTwilioClient() .studio.flows(context.TWILIO_FLOW_SID) .executions.create(params); const executionSid = response.sid; } async function remindAppointment(context) { const AWS_CONFIG = { accessKeyId: await getParam(context, 'AWS_ACCESS_KEY_ID'), secretAccessKey: await getParam(context, 'AWS_SECRET_ACCESS_KEY'), region: await getParam(context, 'AWS_REGION'), }; context.Lambda = new AWS.Lambda(AWS_CONFIG); context.AWS_LAMBDA_SEND_REMINDERS = await getParam( context, 'AWS_LAMBDA_SEND_REMINDERS' ); const params = { FunctionName: context.AWS_LAMBDA_SEND_REMINDERS, InvocationType: 'RequestResponse', }; const response = await context.Lambda.invoke(params).promise(); } exports.handler = function (context, event, callback) { const path = Runtime.getFunctions()['auth'].path; const { isValidAppToken } = require(path); if (!isValidAppToken(event.token, context)) { const response = new Twilio.Response(); response.setStatusCode(401); response.appendHeader( 'Error-Message', 'Invalid or expired token. Please refresh the page and login again.' ); response.appendHeader('Content-Type', 'application/json'); response.setBody({ message: 'Unauthorized' }); return callback(null, response); } const response = new Twilio.Response(); response.appendHeader('Content-Type', 'application/json'); switch (event.command) { case 'BOOKED': const apptDatetime = new Date(tsTomorrow * 1000); const appointment = { event_type: 'BOOKED', event_datetime_utc: null, patient_id: '1000', patient_first_name: event.firstName, patient_last_name: 'Doe', patient_phone: event.phoneNumber, provider_id: 'afauci', provider_first_name: 'Anthony', provider_last_name: 'Diaz', provider_callback_phone: '(800) 555-2222', appointment_location: 'Pacific Primary Care', appointment_id: '20000', appointment_timezone: '-0700', appointment_datetime: apptDatetime.toISOString(), }; // Call studio flow with appointment createAppointment(context, appointment) .then(function () { response.setBody({}); callback(null, response); }) .catch(function (err) { console.log(err); callback(err, null); }); break; case 'REMIND': // Call studio flow with appointment remindAppointment(context) .then(function () { response.setBody({}); callback(null, response); }) .catch(function (err) { console.log(err); callback(err, null); }); break; default: return callback('Invalid command', null); } }; import React from "react"; import { Link } from "react-router-dom"; // function to check the price to determine arrow color export function arrowColor(change) { if (change > 0) return "green"; if (change < 0) return "red"; return "white"; } const CoinItem = ({ coin: { name, symbol, price_usd, percent_change_24h, id }, }) => { return (
      {symbol} {percent_change_24h}%

      {name}

      ${price_usd.toLocaleString()}

      Details
      ); }; export default CoinItem; 0 function editElement(element, match, replacer) { let text = element.textContent; let regex = new RegExp(match, 'g'); element.textContent = text.replace(regex, replacer); }discordjs-japan/Blade-NEXTcommands/Image/r18image.js const { Command } = require('klasa') const fetch = require('node-fetch') const { MessageEmbed } = require('discord.js') module.exports = class extends Command { constructor(...args) { super(...args, { description: language => language.get('COMMAND_R18IMAGE_DESCRIPTION'), requiredPermissions: ['EMBED_LINKS', 'SEND_MESSAGES'], subcommands: true, usage: '', nsfw: true }) } async towd(message) { const image = await fetch('https://konachan.com/post.json?tags=order%3Arandom+rating:questionableplus&limit=1').then(res => res.json()) return message.channel.send(new MessageEmbed() .setAuthor(message.author.tag) .setImage(image[0]['file_url']) ) } } abbjoafli/Programmering-1 //Numbers let number=431; let number2=45; let answer= number+number2; //First and second number added together console.log(answer) //Print out the answer console.log(answer-number2) //Answer minus the second number let anotheranswer= answer*2/number2; //A more complicated answer console.log(anotheranswer) let fname= "Joakim" //First name let lname= "Flink" //Last name let name= fname+ lname; //First and lastname name= fname+" "+ lname; //Changed the the name variable console.log(name) //Boolean true or false let LivesAtHome= false console.log("Lives at home "+LivesAtHome) // text + Boolean variable //Array of cats let Cats= ["Arvid","Andy","Vince"] console.log("The cats "+Cats) //Foreach object in Cat array Cats.forEach(Cat => { if(Cat.length>4) console.log("The cat's name is "+Cat) }); //Object let CatArvid={name:"Arvid", weight:10, likes:["Eating", "Sleeping","Chasing flies"], lazy:true } console.log(CatArvid) console.log(CatArvid.weight) console.log(typeof(CatArvid.weight)) console.log(CatArvid.name+" the cat weight is "+CatArvid.weight+" kg") if(CatArvid.lazy==true) console.log(CatArvid.name+" är lat!") else if(CatArvid.weight<=10) console.log(CatArvid.name+" kan behöva tappa lite vikt!") else console.log(CatArvid.name+" är en liten katt som behöver äta lite!") 0 import jwt from 'jsonwebtoken'; import dotenv from 'dotenv'; dotenv.config(); const secretKey = process.env.SECRET_KEY; const tokenizer = { createToken: user => new Promise((resolve, reject) => { jwt.sign({ user }, secretKey, (err, token) => { if (err) { reject(err); } resolve(token); }); }), verifyToken: (req, res, next) => { const token = req.body.token || req.headers['x-access-token'] || req.headers.authorization || req.params.token; if (!token) { return res.status(401).json({ success: false, message: 'No token found. Please Login or Register', }); } return jwt.verify(token, secretKey, (error, decoded) => { if (error) { return res.status(401).json({ message: 'Invalid Token, Please Login or Register', }); } req.user = decoded; return next(); }); }, }; export default tokenizer; Rennzh/bts-crmsrc/store/mutations.js export default { updateUser (state, payload) { state.user = payload; }, updateBankList (state, payload) { state.bankList = payload; }, addBankList (state, payload) { state.bankList.push(payload); }, updateModifyMt (state, payload) { state.MtList.forEach((item) => { if (item.id === payload.id) { item.leverage = payload.leverage; } }); }, addMtList (state, payload) { console.log(payload); state.MtList.push(payload); }, changeMtMainAccount (state, payload) { state.MtList.forEach((item) => { if (item.id !== payload.id) { item.mainAccount = false; } }); }, changeMtStatus (state, payload) { state.MtList.forEach((item) => { if (item === payload) { item.status = !item.status; } }); } }; /* jshint expr:true */ import { expect } from 'chai'; import { describeComponent, it } from 'ember-mocha'; import hbs from 'htmlbars-inline-precompile'; const basicList = [ {text: 'hello1'}, {text: 'hello2'}, {text: 'hello3'}, {text: 'hello4'} ]; describeComponent( 'simple-carousel', 'Integration: SimpleCarouselComponent', { integration: true }, function() { it('renders', function() { this.render(hbs`{{simple-carousel}}`); expect(this.$()).to.have.length(1); }); it('should accept a list of items and yield them to the template block', function() { const list = basicList; this.setProperties({list}); this.render(hbs`{{#simple-carousel list as |item|}}
      {{item.text}}
      {{/simple-carousel}}`); const jQuery = this.$; const listItemElems = this.$('.list-item').map((index, item) => jQuery(item).text()).get(); const listItemTexts = list.map(item => item.text); expect(listItemElems).to.deep.equal(listItemTexts); }); it('should increment the active item when the next button is clicked', function(done) { const list = basicList; const change = activeItem => { expect(activeItem).to.equal(1); done(); }; this.setProperties({list, change}); this.render(hbs`{{#simple-carousel list on-change=(action change) as |item|}}
      {{item.text}}
      {{/simple-carousel}}`); const nextButton = this.$('.simple-carousel__next'); nextButton.click(); }); it('should decrement the active item when the previous button is clicked', function(done) { const list = basicList; const change = activeItem => { expect(activeItem).to.equal(0); done(); }; this.setProperties({list, change}); this.render(hbs`{{#simple-carousel list activeItemIndex=1 on-change=(action change) as |item|}}
      {{item.text}}
      {{/simple-carousel}}`); const previousButton = this.$('.simple-carousel__previous'); previousButton.click(); }); } ); /** * Created by PRadostev on 05.06.2015. */ L.GML.Geometry = L.GML.Element.extend({ statics: { DIM: 2 }, dimensions: function (element) { if (element.attributes.srsDimension) { return parseInt(element.attributes.srsDimension.value); } return L.GML.Geometry.DIM; } }); 'use strict'; var gulp = require('gulp'); gulp.task('htmlhint', function() { var htmlhint = require('gulp-htmlhint'); var htmlhintJunitReporter = require('gulp-htmlhint-junit-reporter'); gulp.src(['index.html']) .pipe(htmlhint('.htmlhintrc')) .pipe(htmlhint.reporter(htmlhintJunitReporter('TEST-htmlhint.xml'))); }); public/bower_components/ckeditor/plugins/selectall/lang/ru.js CKEDITOR.plugins.setLang("selectall","ru",{toolbar:"Выделить все"});pf-ironhack/martinna-api const express = require('express'); const router = express.Router(); const secure = require('../middlewares/secure.mid'); // const weeksController = require('../controllers/columns.controller'); router.get('/', secure.isAuthenticated, columnsController.list); router.post('/', secure.isAuthenticated, columnsController.create); module.exports = router; module.exports = { activate () {} } 1-10 // React Basic and Bootstrap import React, { Component } from "react"; import { Container, Row, Col, Card, CardBody } from "reactstrap"; import { Link } from "react-router-dom"; //import images import about from "../../assets/images/event/about.jpg"; class About extends Component { constructor(props) { super(props); this.state = {}; } render() { return (

      Business Startup Conference

      Start working with Air99 that can provide everything you need to generate awareness, drive traffic, connect. Launch your campaign and benefit from our expertise on designing and managing conversion centered bootstrap v5 html page managing conversion centered bootstrap v5 html page.

      Read More
      ); } } export default About; Jaganko/Resturant $(document).ready(function(){ $('.field-loginform-email_id').addClass('do-float'); $('input#loginform-email_id').focus(); });// @flow import logError from '../utils/common/logError' import invariant from '../utils/common/invariant' import type Model, { RecordId } from '../Model' import type { CachedQueryResult } from '../adapters/type' import type { TableName } from '../Schema' import type { RawRecord } from '../RawRecord' type Instantiator = RawRecord => T export default class RecordCache { map: Map = new Map() tableName: TableName recordInsantiator: Instantiator constructor(tableName: TableName, recordInsantiator: Instantiator): void { this.tableName = tableName this.recordInsantiator = recordInsantiator } get(id: RecordId): ?Record { return this.map.get(id) } add(record: Record): void { this.map.set(record.id, record) } delete(record: Record): void { this.map.delete(record.id) } unsafeClear(): void { this.map = new Map() } recordsFromQueryResult(result: CachedQueryResult): Record[] { return result.map(res => this.recordFromQueryResult(res)) } recordFromQueryResult(result: RecordId | RawRecord): Record { if (typeof result === 'string') { return this._cachedModelForId(result) } return this._modelForRaw(result) } _cachedModelForId(id: RecordId): Record { const record = this.map.get(id) invariant( record, `Record ID ${this.tableName}#${id} was sent over the bridge, but it's not cached`, ) return record } _modelForRaw(raw: RawRecord): Record { // Sanity check: is this already cached? const cachedRecord = this.map.get(raw.id) if (cachedRecord) { logError( `Record ${this.tableName}#${ cachedRecord.id } is cached, but full raw object was sent over the bridge`, ) return cachedRecord } // Return new model const newRecord = this.recordInsantiator(raw) this.add(newRecord) return newRecord } } WillyLu326/Angular2-MEAN 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var require$$4 = require('tty'); var require$$3 = require('util'); var require$$1 = require('fs'); var require$$0 = require('net'); var heimdall = _interopDefault(require('heimdalljs')); function interopDefault(ex) { return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var index = createCommonjsModule(function (module) { /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @return {String|Number} * @api public */ module.exports = function(val, options){ options = options || {}; if ('string' == typeof val) return parse(val); return options.long ? long(val) : short(val); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = '' + str; if (str.length > 10000) return; var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); if (!match) return; var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function short(ms) { if (ms >= d) return Math.round(ms / d) + 'd'; if (ms >= h) return Math.round(ms / h) + 'h'; if (ms >= m) return Math.round(ms / m) + 'm'; if (ms >= s) return Math.round(ms / s) + 's'; return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function long(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) return; if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; return Math.ceil(ms / n) + ' ' + name + 's'; } }); var index$1 = interopDefault(index); var require$$0$1 = Object.freeze({ default: index$1 }); var debug = createCommonjsModule(function (module, exports) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = interopDefault(require$$0$1); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = Array.prototype.slice.call(arguments); args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); if ('function' === typeof exports.formatArgs) { args = exports.formatArgs.apply(self, args); } var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }); var debug$1 = interopDefault(debug); var formatters = debug.formatters; var skips = debug.skips; var names = debug.names; var humanize = debug.humanize; var enabled = debug.enabled; var enable = debug.enable; var disable = debug.disable; var coerce = debug.coerce; var require$$2 = Object.freeze({ default: debug$1, formatters: formatters, skips: skips, names: names, humanize: humanize, enabled: enabled, enable: enable, disable: disable, coerce: coerce }); var node = createCommonjsModule(function (module, exports) { /** * Module dependencies. */ var tty = interopDefault(require$$4); var util = interopDefault(require$$3); /** * This is the Node.js implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = interopDefault(require$$2); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; /** * The file descriptor to write the `debug()` calls to. * Set the `DEBUG_FD` env variable to override with another value. i.e.: * * $ DEBUG_FD=3 node script.js 3>debug.log */ var fd = parseInt(process.env.DEBUG_FD, 10) || 2; var stream = 1 === fd ? process.stdout : 2 === fd ? process.stderr : createWritableStdioStream(fd); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase(); if (0 === debugColors.length) { return tty.isatty(fd); } else { return '0' !== debugColors && 'no' !== debugColors && 'false' !== debugColors && 'disabled' !== debugColors; } } /** * Map %o to `util.inspect()`, since Node doesn't do that out of the box. */ var inspect = (4 === util.inspect.length ? // node <= 0.8.x function (v, colors) { return util.inspect(v, void 0, void 0, colors); } : // node > 0.8.x function (v, colors) { return util.inspect(v, { colors: colors }); } ); exports.formatters.o = function(v) { return inspect(v, this.useColors) .replace(/\s*\n\s*/g, ' '); }; /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; var name = this.namespace; if (useColors) { var c = this.color; args[0] = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m' + args[0] + '\u001b[3' + c + 'm' + ' +' + exports.humanize(this.diff) + '\u001b[0m'; } else { args[0] = new Date().toUTCString() + ' ' + name + ' ' + args[0]; } return args; } /** * Invokes `console.error()` with the specified arguments. */ function log() { return stream.write(util.format.apply(this, arguments) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (null == namespaces) { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } else { process.env.DEBUG = namespaces; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Copied from `node/src/node.js`. * * XXX: It's lame that node doesn't expose this API out-of-the-box. It also * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. */ function createWritableStdioStream (fd) { var stream; var tty_wrap = process.binding('tty_wrap'); // Note stream._type is used for test-module-load-list.js switch (tty_wrap.guessHandleType(fd)) { case 'TTY': stream = new tty.WriteStream(fd); stream._type = 'tty'; // Hack to have stream not keep the event loop alive. // See https://github.com/joyent/node/issues/1726 if (stream._handle && stream._handle.unref) { stream._handle.unref(); } break; case 'FILE': var fs = interopDefault(require$$1); stream = new fs.SyncWriteStream(fd, { autoClose: false }); stream._type = 'fs'; break; case 'PIPE': case 'TCP': var net = interopDefault(require$$0); stream = new net.Socket({ fd: fd, readable: false, writable: true }); // FIXME Should probably have an option in net.Socket to create a // stream from an existing fd which is writable only. But for now // we'll just add this hack and set the `readable` member to false. // Test: ./node test/fixtures/echo.js < /etc/passwd stream.readable = false; stream.read = null; stream._type = 'pipe'; // FIXME Hack to have stream not keep the event loop alive. // See https://github.com/joyent/node/issues/1726 if (stream._handle && stream._handle.unref) { stream._handle.unref(); } break; default: // Probably an error on in uv_guess_handle() throw new Error('Implement me. Unknown stream file type!'); } // For supporting legacy API we put the FD here. stream.fd = fd; stream._isStdio = true; return stream; } /** * Enable namespaces listed in `process.env.DEBUG` initially. */ exports.enable(load()); }); var debugGen = interopDefault(node); var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; 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 MATCHER = function MATCHER(n) { return true; }; var Prefixer = function () { function Prefixer() { classCallCheck(this, Prefixer); var logConfig = heimdall.configFor('logging'); this.matcher = logConfig.matcher || MATCHER; this.depth = typeof logConfig.depth === 'number' ? logConfig.depth : 3; } // TODO: possibly memoize this using a WeakMap // currently we compute prefix on every call to `log` createClass(Prefixer, [{ key: 'prefix', value: function prefix() { var parts = []; var node = heimdall.current; while (node) { if (node.isRoot || parts.length >= this.depth) { break; } if (this.matcher(node.id)) { parts.push(node.id.name + '#' + node._id); } node = node.parent; } return parts.length > 0 ? '[' + parts.reverse().join(' -> ') + '] ' : ''; } }]); return Prefixer; }(); var ERROR = 0; var WARN = 1; var INFO = 2; var DEBUG = 3; var TRACE = 4; var Logger = function () { function Logger(namespace, level) { classCallCheck(this, Logger); this.level = level; this._print = debugGen(namespace); this._prefixer = new Prefixer(); } createClass(Logger, [{ key: '_message', value: function _message(level, msg) { if (level <= this.level) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } this._print.apply(this, ['' + this._prefixer.prefix() + msg].concat(args)); } } }, { key: 'trace', value: function trace() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return this._message.apply(this, [TRACE].concat(args)); } }, { key: 'debug', value: function debug() { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return this._message.apply(this, [DEBUG].concat(args)); } }, { key: 'info', value: function info() { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return this._message.apply(this, [INFO].concat(args)); } }, { key: 'warn', value: function warn() { for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } return this._message.apply(this, [WARN].concat(args)); } }, { key: 'error', value: function error() { for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } return this._message.apply(this, [ERROR].concat(args)); } }]); return Logger; }(); var NULL_LOGGER = { trace: function trace() {}, debug: function debug() {}, info: function info() {}, warn: function warn() {}, error: function error() {} }; function computeDebugLevel() { var level = void 0; if (!process.env.DEBUG_LEVEL) { level = INFO; } else { switch (process.env.DEBUG_LEVEL.toUpperCase()) { case 'ERROR': level = ERROR;break; case 'WARN': level = WARN;break; case 'INFO': level = INFO;break; case 'DEBUG': level = DEBUG;break; case 'TRACE': level = TRACE;break; default: level = parseInt(process.env.DEBUG_LEVEL, 10); } } logGenerator.debugLevel = level; } function logGenerator(namespace) { if (debugGen.enabled(namespace)) { if (logGenerator.debugLevel === undefined) { computeDebugLevel(); } return new Logger(namespace, logGenerator.debugLevel); } else { return NULL_LOGGER; } } logGenerator.debugLevel = undefined; module.exports = logGenerator;import firebase from 'firebase'; import { nanoid } from 'nanoid'; firebase.initializeApp({ apiKey: "", authDomain: "bigk-grills.firebaseapp.com", projectId: "bigk-grills", storageBucket: "bigk-grills.appspot.com", appId: "1:795287866438:web:b70219db7bd78f11858e47" }) const storage = firebase.storage(); const storageRef = storage.ref(); const imagesRef = storageRef.child('images'); export const uploadImageToCloud = async (fileInBase64, existingId = null) => { try { const metadata = { contentType: 'image/jpeg', }; const refId = nanoid(); // console.log(refId); const imageRef = imagesRef.child(refId); const task = await imageRef.putString(fileInBase64, 'data_url', metadata); const imageLink = await task.ref.getDownloadURL(); if (existingId) { await imagesRef.child(existingId).delete().catch(e => { console.error('Previous image with Id: ' + existingId + ' failed to delete'); console.error(e.message); }) } return { imageLink, imageId: refId }; // use the imageId to delete the image if there is a need to } catch (error) { console.log(error); } } import assert from "assert"; import stub from "./helpers/stub"; import logger from "../src/logger"; describe("logger", () => { it("should exist", () => { assert.ok(logger); }); describe("log levels", () => { let called; beforeEach(() => { called = false; stub(logger, "_emit", () => called = true); }); afterEach(() => logger.setLogLevel()); it("should suppress verbose by default", () => { logger.verbose("test"); assert.ok(!called); }); it("should emit verbose if configured", () => { logger.setLogLevel("verbose"); logger.verbose("test"); assert.ok(called); }); it("should emit error by default", () => { logger.error("test"); assert.ok(called); }); it("should suppress error if silent", () => { logger.setLogLevel("silent"); logger.error("test"); assert.ok(!called); }); }); }); import SpectrumCore from '../../spectrum/spectrum-core.js'; import SpectrumLight from '../../spectrum/spectrum-light.js'; import SpectrumTabs from '../../spectrum/components/tabs/index.js'; export default { render(items) { return `${this.designSystem()} ${this.css()} ${this.html(items)}`; }, html(items) { return `
      ${this.renderMenuItems(items)}
      `; }, renderMenuItems(items) { let html = ``; for (let c = 0; c < items.length; c++) { html += `
      ` } return html; }, css() { return ``; }, designSystem() { return ``; } } /* @flow */ let ImageCacheEntry = function(spec) { let that = {}; let loaded = false; let onload_listeners = []; let image = new Image(); that.add_onload_listener = function(callback) { if (loaded) { callback(image); } else { onload_listeners.push(callback); } } let onload = function() { loaded = true; onload_listeners.forEach(function(callback) { callback(image); }); onload_listeners = []; }; that.get_image = function() { return image; }; image.onload = onload; image.src = spec.image_name; return that; }; export let ImageCache = function(spec) { let that = {}; let base_path = spec.base_path || ""; let images = {}; that.get_image_from_cache = function(image_name, callback) { let full_name = base_path ? base_path + image_name : image_name; let cache_entry = images[image_name]; if (cache_entry !== undefined) { console.log("Retrieving image " + image_name + " from cache"); cache_entry.add_onload_listener(callback); } else { let new_cache_entry = ImageCacheEntry({image_name:full_name}); new_cache_entry.add_onload_listener(callback); images[image_name] = new_cache_entry; } } return that; }; akshunsoumya/ecommerce-client1-10 'use strict'; //const productApi = require('./product-api.js'); const showSuccess = function (data) { let productTemplate = require ('../templates/product.handlebars'); $('.show-item').prepend(productTemplate(data)); }; const getProductsSuccess = function (products) { // console.log(products); // console.log("this is the get products success function"); $('#products').html(''); let displayAllProducts = require ('../templates/display-all-products.handlebars'); $('#products').prepend(displayAllProducts(products)); }; module.exports = { showSuccess, getProductsSuccess, }; 1-10 'use strict' const Joi = require('joi') const t = (module.exports = require('../tester').createServiceTester()) t.create('existing key fingerprint') .get('/skyplabs.json') .expectBadge({ label: 'pgp', message: Joi.string() .hex() .length(16), }) t.create('unknown username') .get('/skyplabsssssss.json') .expectBadge({ label: 'pgp', message: 'profile not found', }) t.create('invalid username') .get('/s.json') .expectBadge({ label: 'pgp', message: 'invalid username', }) t.create('missing key fingerprint') .get('/skyp.json') .expectBadge({ label: 'pgp', message: 'no key fingerprint found', }) export default function sketch(p){ let canvas; let width = 400; let height = 400; let resolution = 10; let frame_rate = 5; let player; let food; function Snake() { this.x = 0; this.y = 0; this.dx = 0; this.dy = 0; this.total = 0; this.tail = []; this.over = 0; this.move = () => { for (let i = 0; i < this.tail.length - 1; i++) { this.tail[i] = this.tail[i + 1]; } if (this.total >= 1) { this.tail[this.total - 1] = p.createVector(this.x, this.y); } this.x = this.x + this.dx; this.y = this.y + this.dy; }; this.show = function() { p.stroke(255); p.fill(255); for (let i = 0; i < this.tail.length; i++) { p.rect(this.tail[i].x*resolution, this.tail[i].y*resolution, resolution, resolution); } p.rect(Math.floor(this.x)*resolution,Math.floor(this.y)*resolution, resolution, resolution); }; this.dir = (x, y) => { this.dx = x; this.dy = y; }; this.eat = (x, y) => { var d = (Math.floor(this.x)===Math.floor(x) && Math.floor(y)===Math.floor(this.y)); if (d){ this.total++; return true;} else{return false;} }; this.death = function() { if (this.x < 0 || this.x > Math.floor(width/resolution) || this.y < 0 || this.y > Math.floor(height/resolution)){ this.over = 0; this.total = 0; this.tail = []; this.x = 0; this.y = 0; this.dx = 0; this.dy = 0; }else{ for (let i = 0; i < this.tail.length; i++) { let pos = this.tail[i]; let d = (Math.floor(this.x)===Math.floor(pos.x) && Math.floor(pos.y)===Math.floor(this.y)); if (d) { console.log('starting over'); this.total = 0; this.tail = []; this.x = 0; this.y = 0; this.dx = 0; this.dy = 0; this.over = 0; }} } } this.score = function(){ p.push() p.stroke(0, 102, 153); p.fill(0, 102, 153); //p.textAlign(p.CENTER, p.CENTER); p.textSize(20); p.text(this.total, 10, 60); p.pop() } } p.keyPressed = function () { if (p.keyCode === p.UP_ARROW){ player.dir(0,-1); } if (p.keyCode === p.DOWN_ARROW){ player.dir(0, 1); } if (p.keyCode === p.RIGHT_ARROW){ player.dir(1, 0); } if (p.keyCode === p.LEFT_ARROW){ player.dir(-1, 0); } if (p.keyCode === p.ENTER){ //player.over = !player.over; } }; function foodLocation(){ this.x = 10; this.y = 10; this.newLoc = () =>{ this.x = Math.floor(Math.random()*width/resolution); this.y = Math.floor(Math.random()*height/resolution); }; }; player = new Snake(); food = new foodLocation(); food.newLoc(); p.setup = () => { canvas = p.createCanvas(height, width); p.background('black'); p.frameRate(frame_rate) } p.draw = () => { p.background('black'); player.move(); player.show(); if (player.eat(food.x,food.y)){ food.newLoc(); } p.fill(255,0,100); p.rect(food.x*resolution, food.y*resolution, resolution, resolution); player.death(); player.score(); } } 0 import React from 'react'; import './Footer.css'; export default function Footer() { return ( ) }src/actions/types.js0 export const SAVE_COMMENT = 'save_comment'; export const FETCH_COMMENTS = 'fetch_comments'; export const CHANGE_AUTH = 'change_auth'; export const AUTH_USER = 'auth_user'; export const AUTH_ERROR = 'auth_error'; src/utils/Auth.js import LocalStorage from '@/utils/LocalStorage'; import store from '@/store'; const getAccessToken = () => LocalStorage.get('refreshToken'); const getUser = () => LocalStorage.get('user'); export const isAuthenticated = () => { const token = getAccessToken(); const user = getUser(); if (token && user) { store.commit('Auth/setUser', user); store.commit('Auth/setIsAuthenticated', true); return true; } else { store.commit('Auth/setUser', null); store.commit('Auth/setIsAuthenticated', false); LocalStorage.clear(); return false; } }import React from 'react'; import createSvg from '../utils/createSvg'; export default createSvg(, 'TabletAndroid');define(["jquery"], function($){ function download(){ $.ajax({ url: "../data/slide.json", success: function(data){ var slideArr = data.data.list.list; for(var i = 0; i < slideArr.length; i++){ $(`
    • ${slideArr[i].goods_name}

      ${slideArr[i].desc}

      ${slideArr[i].seckill_Price}${slideArr[i].goods_price}元

    • `).appendTo("#J_flashSaleList ul"); } }, error: function(msg){ console.log(msg); } }) } function slideTab(){ var aSpans = $(".swiper-controls").find("span"); var iNow = 0; var count = Math.ceil(26 / 4) - 1; //启动定时器,让其一开始自己滚动 var timer = setInterval(function(){ iNow++; tab(); if(iNow == count){ clearInterval(timer); } }, 4000); aSpans.click(function(){ if($(this).index() == 0){ iNow--; iNow = Math.max(0, iNow); }else{ iNow++; iNow = Math.min(count, iNow) } tab(); }) function tab(){ iNow == 0 ? aSpans.eq(0).addClass("swiper-button-disabled") : aSpans.eq(0).removeClass("swiper-button-disabled"); iNow == count ? aSpans.eq(1).addClass("swiper-button-disabled") : aSpans.eq(1).removeClass("swiper-button-disabled") var iTarget = iNow == count ? iNow * -992 + 496 : iNow * -992; $("#J_flashSaleList ul").css({ transform: `translate3d(${iTarget}px, 0px, 0px)`, transitionDuration: "1000ms" }) } } //定时器倒计时,每天14:00开枪,每天22:00开枪 function countDown(){ var nowDate = new Date(); var hour = nowDate.getHours(); var date = nowDate.getDate(); var afterDate = new Date(); //计算倒计时时间间隔 if(hour < 14){ afterDate.setHours(14); $(".flashsale-countdown .round").html("14:00 场"); }else if(hour >= 14 && hour < 22){ afterDate.setHours(22); $(".flashsale-countdown .round").html("22:00 场"); }else{ $(".flashsale-countdown .round").html("明日14:00 场"); afterDate.setHours(14); afterDate.setDate(date + 1); } afterDate.setMilliseconds(0); afterDate.setSeconds(0); afterDate.setUTCMilliseconds(0); //计算倒计时总秒数 var count = parseInt((afterDate.getTime() - nowDate.getTime()) / 1000); var aSpans = $(".box-bd .countdown").find("span"); var timer = setInterval(function(){ count--; aSpans.eq(2).html(doubleNum(count % 60)); aSpans.eq(1).html(doubleNum(parseInt(count / 60) % 60)); aSpans.eq(0).html(doubleNum(parseInt(count / 3600) % 24)); if(count == 0){ clearInterval(timer); $(".box-bd .desc").html("本次活动结束,敬请期待~"); } }, 1000); } function doubleNum(num){ if(num < 10){ return "0" + num; }else{ return num; } } return { download: download, slideTab: slideTab, countDown: countDown } })0 'use strict'; require('dotenv').config(); const { query } = require('express'); const express=require('express'); const superagent = require('superagent'); const pg=require('pg'); const methodOverride = require('method-override'); const PORT = process.env.PORT || 3030; const server=express(); server.set('view engine','ejs'); server.use(express.static('./public')) server.use(express.urlencoded({extended:true})); // const path = require( 'path' ); // server.set( 'views', path.join( __dirname, '/views/pages' ) ); // server.set( 'view engine','ejs' ); server.use(methodOverride('_method')); const client = new pg.Client({ connectionString: process.env.DATABASE_URL, ssl: process.env.DEV_MODE ? false : { rejectUnauthorized: false }, }); client.connect() .then(()=>{ server.listen(PORT, ()=>{ console.log(`Here is port ${PORT}`); }) }) .catch((err)=>{ console.log(err); }) //localhost:3000/ server.get('/',(req,res)=>{ let SQL=`SELECT * FROM books;`; client.query(SQL) .then((results=>{ // console.log(results.rows); res.render('pages/index',{booksResults:results.rows}) })) }) server.put('/updateBook/:bookID',(req,res)=>{ let { author, title, isbn, image_url, description}= req.body; let SQL = `UPDATE books SET author=$1, title=$2,isbn=$3,image_url=$4,description=$5 WHERE id=$6;`; let safeValues = [author,title,isbn,image_url,description,req.params.bookID]; client.query(SQL,safeValues) .then(()=>{ res.redirect(`/books/${req.params.bookID}`); }) }) server.delete('/deleteBook/:bookID',(req,res)=>{ let SQL = `DELETE FROM books WHERE id=$1;`; let safeValue = [req.params.bookID]; client.query(SQL,safeValue) .then(()=>{ res.redirect('/'); }) }) //localhost:3000/searches/new server.get('/searches/new',(req,res)=>{ res.render('pages/searches/new'); }); server.get('/books/:bookID',(req,res)=>{ console.log(req.params); let SQL = `SELECT * FROM books WHERE id=$1;`; let safeValue = [req.params.bookID] client.query(SQL,safeValue) .then(results=>{ res.render('pages/books/show',{booksResults:results.rows}) }); }); server.post('/books',(req,res)=>{ console.log('form', req.body); let { author, title, isbn, image_url, description}=req.body; let SQL=`INSERT INTO books (author, title, isbn, image_url, description) VALUES ($1,$2,$3,$4,$5) RETURNING *;`; let safeValues=[ author, title, isbn, image_url, description]; client.query(SQL, safeValues) .then(results=>{ console.log(results.rows) res.redirect(`/books/${results.rows[0].id}`) }) // res.send('dddddd') }); //localhost:3000/searches server.post('/searches',(req,res)=>{ let searchedBook=req.body.q; let searchBy=req.body.searchBy; console.log(req.body); let URL=`https://www.googleapis.com/books/v1/volumes?q=+in${searchBy}:${searchedBook}&maxResults=10` superagent.get(URL) .then(booksData=>{ // console.log('by title', booksData.body.items); let bookDataArr= booksData.body.items.map((item)=>{ let newBook= new Books (item); return newBook; }); // let x=booksData.body.items; console.log('by title', booksData.body.items); // res.send(bookDataArr) res.render('pages/searches/shows',{booksResults:bookDataArr} ); }) .catch(error=>{ res.render('pages/error',{error:err}) }) }) function Books(book){ this.image_url=(book.volumeInfo.imageLinks)?book.volumeInfo.imageLinks.thumbnail:"https://i.imgur.com/J5LVHEL.jpg"; this.title=book.volumeInfo.title; this.author=(book.volumeInfo.authors)? book.volumeInfo.authors.join(', '): 'No author data for this book'; this.description=(book.volumeInfo.description)?book.volumeInfo.description:'No description data for this book'; this.isbn=(book.volumeInfo.industryIdentifiers)?book.volumeInfo.industryIdentifiers[0].identifier:'No ISBN data for this book'; // this.bookshelf= (book.volumeInfo.industryIdentifiers)?book.volumeInfo.industryIdentifiers.toString().join(','):'No ISBN data for this book'; } //localhost:3000/* server.get('*',(req,res)=>{ res.render('pages/error'); })0 const path = require('path'); const {CleanWebpackPlugin} = require('clean-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const ManifestPlugin = require('webpack-manifest-plugin'); const StylelintPlugin = require('stylelint-webpack-plugin'); const MinifyJsPlugin = require("babel-minify-webpack-plugin"); const CopyPlugin = require("copy-webpack-plugin"); const ImageminPlugin = require('imagemin-webpack-plugin').default; const entries = {}; const moduleScss = []; const plugins = []; module.exports = (env, argv) => { const isProd = () => argv.mode === 'production'; process.env.NODE_ENV = isProd() ? 'production' : 'development'; if (isProd()) { plugins.push(new MinifyJsPlugin()) } return { entry: { "js/index": "./resources/js/index.js", "css/styles": "./resources/scss/styles.scss" }, output: { filename: isProd() ? '[name].[contentHash].js' : '[name].js', path: path.resolve(__dirname, 'public/'), }, devServer: { contentBase: path.join(__dirname, 'public/'), proxy: { '/': 'http://127.0.0.1:8080' }, port: 9000, writeToDisk: true }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: [ {loader: 'babel-loader',}, {loader: 'eslint-loader',} ] }, { test: /\.scss$/, use: [ {loader: MiniCssExtractPlugin.loader}, {loader: 'css-loader', options: {url: true, importLoaders: 1}}, {loader: 'postcss-loader'}, {loader: 'sass-loader'}, ], }, { test: /\.(png|jpe?g|gif|svg)$/i, loader: 'file-loader', options: { outputPath: '/images/', name: isProd() ? '[name].[contentHash].[ext]' : '[name].[ext]', } }, { test: /\.(eot|otf|ttf|woff|woff2)$/i, loader: 'file-loader', options: { outputPath: '/fonts/', name: isProd() ? '[name].[contentHash].[ext]' : '[name].[ext]', } }, ] }, plugins: [ new CleanWebpackPlugin({ protectWebpackAssets: false, cleanOnceBeforeBuildPatterns: ['js/', 'css/', 'fonts/', 'images/', 'img/', 'manifest.json'], cleanAfterEveryBuildPatterns: ['css/*.js'] }), new StylelintPlugin(), new CopyPlugin([{from: 'img', to: 'img'}], {context: "resources/"}), new ImageminPlugin({ test: /\.(jpe?g|png|gif|svg)$/i, disable: !isProd(), svgo: { plugins: [ {removeTitle: false} ] } }), ...plugins, new MiniCssExtractPlugin({filename: isProd() ? '[name].[contentHash].css' : '[name].css',}), new ManifestPlugin({ filter: (file) => file.name.match(/^css\/.*\.css$/) || file.name.match(/^js\/.*\.js$/) }) ], optimization: { minimizer: [] }, performance: { hints: isProd() ? "warning" : false, }, stats: { excludeAssets: (name) => { return name.match(/css\/.*\.js/) || name.match(/manifest\.json$/) || name.match(/\.(eot|otf|ttf|woff|woff2)$/i) || name.match(/\.(jpe?g|png|gif|svg)$/i); }, entrypoints: false, excludeModules: true, children: false, hash: false, version: false, timings: false } }; }; extnet/docs5.ext.net var class_ext_1_1_net_1_1_panel_title_1_1_config = [ [ "Glyph", "d9/d3d/class_ext_1_1_net_1_1_panel_title_1_1_config.html#aeec2d5452f196046e4c6248a6d9e6998", null ], [ "GlyphSpec", "d9/d3d/class_ext_1_1_net_1_1_panel_title_1_1_config.html#a69e41b891fd1fb925005a8c3dc754e5f", null ], [ "Icon", "d9/d3d/class_ext_1_1_net_1_1_panel_title_1_1_config.html#a16f8e613b207549f59e5a170051c8db1", null ], [ "IconAlign", "d9/d3d/class_ext_1_1_net_1_1_panel_title_1_1_config.html#a2b7de8d90e2771935fb88f0814e2caee", null ], [ "IconCls", "d9/d3d/class_ext_1_1_net_1_1_panel_title_1_1_config.html#a456cde877b516cd1b4383664844a6395", null ], [ "IconPath", "d9/d3d/class_ext_1_1_net_1_1_panel_title_1_1_config.html#a3f07c4b23d8a07cde3149268133ae4e1", null ], [ "Rotation", "d9/d3d/class_ext_1_1_net_1_1_panel_title_1_1_config.html#aaf5e743fc96572f7d457eec083c37da3", null ], [ "Text", "d9/d3d/class_ext_1_1_net_1_1_panel_title_1_1_config.html#a4d97c12fa778f1f7ef5af1f284016412", null ], [ "TextAlign", "d9/d3d/class_ext_1_1_net_1_1_panel_title_1_1_config.html#a1c784c819a7bf3fd29b11ec3435fb919", null ] ];client/components/OrderHistory.js import React from 'react'; import {connect} from 'react-redux'; import {getOrders} from '../store/orderHistory'; import SingleProduct from './SingleProduct'; import {centsToDollarString, DEFAULT_CURRENCY} from '../formatters.js'; class DisconnectedOrderHistory extends React.Component { componentDidMount() { this.props.getOrders(); } render() { // console.log(this.props.orders); if (!this.props.orders.length) { return (

      No cart history. Order something!

      ); } let orderNum = 1; return (
      {this.props.orders.map(order => (

      Order #{orderNum++}

      {order.products.map(product => (
      name: {product.name}
      price: {centsToDollarString(product.price, DEFAULT_CURRENCY)}
      quantity: {product.CartProduct.quantity}
      total price:{' '} {centsToDollarString( product.price * product.CartProduct.quantity, DEFAULT_CURRENCY )}
      ))}
      ))}
      ); } } const mapStateToProps = state => { return { orders: state.orderHistory.orders }; }; const mapDispatchToProps = dispatch => { return { getOrders: () => dispatch(getOrders()) }; }; const OrderHistory = connect(mapStateToProps, mapDispatchToProps)( DisconnectedOrderHistory ); export default OrderHistory; 0 import React from 'react' import ApiClient from '../utilities/api-client' import Auth from '../utilities/auth' import { statuses } from '../utilities/statuses' export function withAuthentication(WrappedComponent) { return class extends React.Component { constructor(props) { super(props) this.authClient = new Auth() this.apiClient = new ApiClient() this.state = { isAuthenticated: false, user: null, globalAlert: { type: null, message: null, }, } } componentDidMount = () => { if (this.authClient.isAuthenticated()) { this.authClient.renewTokens() this.setState({ ...this.state, isAuthenticated: true, }) if (!this.state.user) { this.apiClient.getMe().then(res => { this.setState({ ...this.state, user: res.data, }) }) } } else { const error = this.authClient.handleAuthentication() if (error) { this.setState({ ...this.state, globalAlert: { type: statuses.ERROR, message: error.errorDescription, }, }) } else { this.setState({ ...this.state, isAuthenticated: false, }) } } } render = () => ( ) } } import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray"; import * as React from 'react'; import { useRef, useEffect } from 'react'; import { STATUS_APPEAR, STATUS_NONE, STATUS_LEAVE, STATUS_ENTER, STEP_PREPARE, STEP_START, STEP_ACTIVE } from '../interface'; import useState from './useState'; import useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect'; import useStepQueue, { DoStep, SkipStep, isActive } from './useStepQueue'; import useDomMotionEvents from './useDomMotionEvents'; export default function useStatus(supportMotion, visible, getElement, _ref) { var _ref$motionEnter = _ref.motionEnter, motionEnter = _ref$motionEnter === void 0 ? true : _ref$motionEnter, _ref$motionAppear = _ref.motionAppear, motionAppear = _ref$motionAppear === void 0 ? true : _ref$motionAppear, _ref$motionLeave = _ref.motionLeave, motionLeave = _ref$motionLeave === void 0 ? true : _ref$motionLeave, motionDeadline = _ref.motionDeadline, motionLeaveImmediately = _ref.motionLeaveImmediately, onAppearPrepare = _ref.onAppearPrepare, onEnterPrepare = _ref.onEnterPrepare, onLeavePrepare = _ref.onLeavePrepare, onAppearStart = _ref.onAppearStart, onEnterStart = _ref.onEnterStart, onLeaveStart = _ref.onLeaveStart, onAppearActive = _ref.onAppearActive, onEnterActive = _ref.onEnterActive, onLeaveActive = _ref.onLeaveActive, onAppearEnd = _ref.onAppearEnd, onEnterEnd = _ref.onEnterEnd, onLeaveEnd = _ref.onLeaveEnd, onVisibleChanged = _ref.onVisibleChanged; // Used for outer render usage to avoid `visible: false & status: none` to render nothing var _useState = useState(), _useState2 = _slicedToArray(_useState, 2), asyncVisible = _useState2[0], setAsyncVisible = _useState2[1]; var _useState3 = useState(STATUS_NONE), _useState4 = _slicedToArray(_useState3, 2), status = _useState4[0], setStatus = _useState4[1]; var _useState5 = useState(null), _useState6 = _slicedToArray(_useState5, 2), style = _useState6[0], setStyle = _useState6[1]; var mountedRef = useRef(false); var deadlineRef = useRef(null); var destroyedRef = useRef(false); // =========================== Dom Node =========================== var cacheElementRef = useRef(null); function getDomElement() { var element = getElement(); return element || cacheElementRef.current; } // ========================== Motion End ========================== var activeRef = useRef(false); function onInternalMotionEnd(event) { var element = getDomElement(); if (event && !event.deadline && event.target !== element) { // event exists // not initiated by deadline // transitionEnd not fired by inner elements return; } var canEnd; if (status === STATUS_APPEAR && activeRef.current) { canEnd = onAppearEnd === null || onAppearEnd === void 0 ? void 0 : onAppearEnd(element, event); } else if (status === STATUS_ENTER && activeRef.current) { canEnd = onEnterEnd === null || onEnterEnd === void 0 ? void 0 : onEnterEnd(element, event); } else if (status === STATUS_LEAVE && activeRef.current) { canEnd = onLeaveEnd === null || onLeaveEnd === void 0 ? void 0 : onLeaveEnd(element, event); } // Only update status when `canEnd` and not destroyed if (canEnd !== false && !destroyedRef.current) { setStatus(STATUS_NONE); setStyle(null); } } var _useDomMotionEvents = useDomMotionEvents(onInternalMotionEnd), _useDomMotionEvents2 = _slicedToArray(_useDomMotionEvents, 1), patchMotionEvents = _useDomMotionEvents2[0]; // ============================= Step ============================= var eventHandlers = React.useMemo(function () { var _ref2, _ref3, _ref4; switch (status) { case 'appear': return _ref2 = {}, _defineProperty(_ref2, STEP_PREPARE, onAppearPrepare), _defineProperty(_ref2, STEP_START, onAppearStart), _defineProperty(_ref2, STEP_ACTIVE, onAppearActive), _ref2; case 'enter': return _ref3 = {}, _defineProperty(_ref3, STEP_PREPARE, onEnterPrepare), _defineProperty(_ref3, STEP_START, onEnterStart), _defineProperty(_ref3, STEP_ACTIVE, onEnterActive), _ref3; case 'leave': return _ref4 = {}, _defineProperty(_ref4, STEP_PREPARE, onLeavePrepare), _defineProperty(_ref4, STEP_START, onLeaveStart), _defineProperty(_ref4, STEP_ACTIVE, onLeaveActive), _ref4; default: return {}; } }, [status]); var _useStepQueue = useStepQueue(function (newStep) { // Only prepare step can be skip if (newStep === STEP_PREPARE) { var onPrepare = eventHandlers[STEP_PREPARE]; if (!onPrepare) { return SkipStep; } return onPrepare(getDomElement()); } // Rest step is sync update if (step in eventHandlers) { var _eventHandlers$step; setStyle(((_eventHandlers$step = eventHandlers[step]) === null || _eventHandlers$step === void 0 ? void 0 : _eventHandlers$step.call(eventHandlers, getDomElement(), null)) || null); } if (step === STEP_ACTIVE) { // Patch events when motion needed patchMotionEvents(getDomElement()); if (motionDeadline > 0) { clearTimeout(deadlineRef.current); deadlineRef.current = setTimeout(function () { onInternalMotionEnd({ deadline: true }); }, motionDeadline); } } return DoStep; }), _useStepQueue2 = _slicedToArray(_useStepQueue, 2), startStep = _useStepQueue2[0], step = _useStepQueue2[1]; var active = isActive(step); activeRef.current = active; // ============================ Status ============================ // Update with new status useIsomorphicLayoutEffect(function () { setAsyncVisible(visible); if (!supportMotion) { return; } var isMounted = mountedRef.current; mountedRef.current = true; var nextStatus; // Appear if (!isMounted && visible && motionAppear) { nextStatus = STATUS_APPEAR; } // Enter if (isMounted && visible && motionEnter) { nextStatus = STATUS_ENTER; } // Leave if (isMounted && !visible && motionLeave || !isMounted && motionLeaveImmediately && !visible && motionLeave) { nextStatus = STATUS_LEAVE; } // Update to next status if (nextStatus) { setStatus(nextStatus); startStep(); } }, [visible]); // ============================ Effect ============================ // Reset when motion changed useEffect(function () { if ( // Cancel appear status === STATUS_APPEAR && !motionAppear || // Cancel enter status === STATUS_ENTER && !motionEnter || // Cancel leave status === STATUS_LEAVE && !motionLeave) { setStatus(STATUS_NONE); } }, [motionAppear, motionEnter, motionLeave]); useEffect(function () { return function () { clearTimeout(deadlineRef.current); destroyedRef.current = true; }; }, []); // Trigger `onVisibleChanged` useEffect(function () { if (asyncVisible !== undefined && status === STATUS_NONE) { onVisibleChanged === null || onVisibleChanged === void 0 ? void 0 : onVisibleChanged(asyncVisible); } }, [asyncVisible, status]); // ============================ Styles ============================ var mergedStyle = style; if (eventHandlers[STEP_PREPARE] && step === STEP_START) { mergedStyle = _objectSpread({ transition: 'none' }, mergedStyle); } return [status, step, mergedStyle, asyncVisible !== null && asyncVisible !== void 0 ? asyncVisible : visible]; }0 // Module imports import React, { useState } from 'react' import PropTypes from 'prop-types' // Local imports import { firebase, firebaseApp, } from '../helpers/firebase' import CharacterPreview from './CharacterPreview' /* eslint-disable id-length,no-magic-numbers,no-param-reassign,react-hooks/rules-of-hooks */ const CharacterCreator = ({ onSubmit, ownerID }) => { const [gender, setGender] = useState('') const [isCreatingCharacter, setIsCreatingCharacter] = useState(false) const [name, setName] = useState('') const [profession, setProfession] = useState('') const isValid = name && gender && profession const _onSubmit = async event => { event.preventDefault() if (isValid) { const database = firebaseApp.database() const firestore = firebaseApp.firestore() const characterCollection = firestore.collection('characters') setIsCreatingCharacter(true) const characterDoc = await characterCollection.add({ active: false, createdAt: firebase.firestore.FieldValue.serverTimestamp(), profession, gender, name, ownerID, updatedAt: firebase.firestore.FieldValue.serverTimestamp(), }) const { id } = characterDoc await database.ref(`game/characters/${id}`).set({ direction: 'right', id, ownerID, status: { active: false, updatedAt: firebase.database.ServerValue.TIMESTAMP, }, x: 0, y: 0, }) setIsCreatingCharacter(false) setTimeout(() => onSubmit(), 500) } } return (
      setName(value)} placeholder="e.g. " required type="text" value={name} />
      ) } CharacterCreator.defaultProps = { onSubmit: () => {}, } CharacterCreator.propTypes = { onSubmit: PropTypes.func, ownerID: PropTypes.string.isRequired, } /* eslint-enable id-length,no-magic-numbers,no-param-reassign,react-hooks/rules-of-hooks */ export default CharacterCreator import React from 'react'; import { withAuthorization } from '../Session'; const HomePage = () => (

      Crea la tua lista!

      Aggiungi le cose da fare alla tua lista; puoi eliminarle semplicemente cliccandoci sopra!

      ); const condition = authUser => !!authUser; export default withAuthorization(condition)(HomePage);process.env.NODE_ENV = 'test'; let chai = require('chai'); let chaiHttp = require('chai-http'); let server = require('../server'); let should = chai.should(); chai.use(chaiHttp); const EXAMPLE_DECKSTRING = 'AAECAR8GxwPJBLsFmQfZB/gIDI0B2AGoArUDhwSSBe0G6wfbCe0JgQr+DAA='; const EXAMPLE_DECK_TO_ENCODE = { "cards": [ [141, 2], [216, 2], [296, 2], [437, 2], [455, 1], [519, 2], [585, 1], [658, 2], [699, 1], [877, 2], [921, 1], [985, 1], [1003, 2], [1144, 1], [1243, 2], [1261, 2], [1281, 2], [1662, 2] ], "heroes": [31], "format": 2 }; const EXAMPLE_ENCODED_DECK = 'AAECAR8GxwPJBLsFmQfZB/gIDI0B2AGoArUDhwSSBe0G6wfbCe0JgQr+DAA='; describe('deck controller', () => { describe('/POST to /decode', () => { it('it should return data representing the decoded deck string', (done) => { chai.request(server) .post('/deck/decode') .send({'query':EXAMPLE_DECKSTRING}) .end(async (err, res) => { res.status.should.equal(200); let response = JSON.parse(res.text); let result = response.result; result.should.not.equal(null); result.should.not.equal({}); result.class.should.equal('Hunter'); result.format.should.equal('Standard'); result.cardList.length.should.equal(18); await done(); }); }); }); describe('/POST to /encode', () => { it('it should return an encoded deck string', (done) => { chai.request(server) .post('/deck/encode') .send({'query': JSON.stringify(EXAMPLE_DECK_TO_ENCODE)}) .end(async (err, res) => { res.status.should.equal(200); let response = JSON.parse(res.text); let result = response.result; result.should.not.equal(null); result.should.not.equal({}); result.should.equal(EXAMPLE_ENCODED_DECK); await done(); }); }); }); });static/js/search.js (() => { const search_form = $("#search_form") if (search_form.length < 1) { console.error("Could not find search form.") return; } const search_endpoint = search_form.attr("action") /** * @type {string} */ const method = search_form.attr("method") const static_url = search_form.attr('data-static-url') const search_bar = $("#search_bar"); const search_query = $("#search_query") const search_scope = $("#search_scope") const search_icon = $("#search_icon") const search_result_list = $("#search_result_list") const search_result_item = $("#search_result_item") // result item template const search_scope_list = $("#search_scope_list") const search_scope_items = search_scope_list.children() const search_result_container = $("#search_result_container") const search_scope_menu = $("#search_scope_menu") const current_scope_text = $("#current_scope_text") const search_scope_filter = $("#search_scope_filter") const filter_arrow = $("#filter_arrow") // current filtering strategy let current_scope = search_scope_filter.attr("data-current-scope") function toggleFilterMenu() { search_scope_menu.toggleClass("scale-y-0") filter_arrow.toggleClass("rotate-180") } // toggle filter menu search_scope_filter.click(toggleFilterMenu); // listen to selection of a scope search_scope_items.click((e) => { let new_scope = e.target.getAttribute("data-scope") if (current_scope === new_scope) return; current_scope = new_scope; current_scope_text.text(current_scope); search_scope_filter.attr("data-current-scope", current_scope); search_scope.val(current_scope) // focus on search input search_query.focus() // do quick query quick_query(); }); /** * Does a GET request and displays the results in a minimized version, like how google shows possible results. */ function quick_query() { if (search_query.val() === "") { showSearchResults({results: []}) return; } // animate search bar search_bar.toggleClass("animate-pulse") const formData = new FormData(search_form[0]) fetch(`${search_endpoint}?${new URLSearchParams({ "csrfmiddlewaretoken": formData.get("csrfmiddlewaretoken"), "search_query": formData.get("search_query"), "search_scope": formData.get("search_scope"), "quick_query": "true" })}`, { method: method.toUpperCase() }) .then(res => res.json()) .then(data => { search_bar.toggleClass("animate-pulse") showSearchResults(data) }) .catch(console.error); } function showSearchResults(query_data) { // clear all previous results search_result_list.children().remove("[data-removable-result=\"true\"]"); // console.log(query_data) // construct the result lists for (let i=0;i 1) { search_result_container.removeClass("hidden") } else { search_result_container.addClass("hidden") } } // only show quick query results when search bar is focused. search_query.focus(() => { search_result_container.removeClass("opacity-60"); }); search_query.blur(() => { search_result_container.addClass("opacity-60"); }) // debounce function is from debounce.js search_query.keyup(debounce(quick_query)) })();janimattiellonen/fgr0 import { List, Map } from 'immutable'; import persons from '../services/person-service'; export function getPersons() { return { type: 'PERSON_GET_PERSONS', payload: persons.all(), }; } export function deletePerson(id) { console.log('hellurei', id); return { type: 'PERSON_DELETE_PERSON', payload: id, }; } const defaultState = Map({ persons: List(), }); export default function (state = defaultState, action) { const { type, payload } = action; switch (type) { case 'PERSON_GET_PERSONS_FULFILLED': return state.set('persons', List(payload)); case 'PERSON_DELETE_PERSON': return state.update('persons', persons => persons.filterNot(p => p.id === payload)); default: return state; } } console.log('leListeStr main01 start json de data maDataBlocs'); var maDataBlocs = { "data00" : { "fic1" : "./qc/crypto/initthread.c.html" , "texte" : "File crypto/initthread.c 57 rule violations " , "fic2" : "./qc/crypto/initthread.c.xml" , "fic3" : "" } , "data01" : [ ] , "data02" : [ ] , "data03" : [ ] , "data04" : [ ] , "data05" : [ ] , "data06" : [ ] , "data07" : [ ] , "data08" : [ ] , "data11" : [ ] , "data14" : [ ] , "data13a" : [ { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000011" , "c3" : "The condition expression on a single value can be confusing" , "c4" : "6" }} , { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000012" , "c3" : "The condition expression is invariable, always true or false" , "c4" : "37" }} , { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000018" , "c3" : "A suspicious bitwise expression is compared to a numerical expression" , "c4" : "3" }} , { "ligne" : { "c1" : "MAJOR" , "c2" : "QC-CPPCWE481" , "c3" : "Assigning instead of comparing" , "c4" : "1" }} , { "ligne" : { "c1" : "MAJOR" , "c2" : "QC-CPP000014" , "c3" : "A pointer is defined but not initialized" , "c4" : "10" }} ] , "data13b" : [ { "ligne" : { "c1" : "01209" , "c1link" : "./qc/crypto/initthread.c.html#1209" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[01209] The pointer __p is declared but not initialized" }} , { "ligne" : { "c1" : "01372" , "c1link" : "./qc/crypto/initthread.c.html#1372" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01372] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01399" , "c1link" : "./qc/crypto/initthread.c.html#1399" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01399] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01403" , "c1link" : "./qc/crypto/initthread.c.html#1403" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01403] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01425" , "c1link" : "./qc/crypto/initthread.c.html#1425" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01425] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01425" , "c1link" : "./qc/crypto/initthread.c.html#1425" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01425] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01449" , "c1link" : "./qc/crypto/initthread.c.html#1449" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01449] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01455" , "c1link" : "./qc/crypto/initthread.c.html#1455" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01455] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01480" , "c1link" : "./qc/crypto/initthread.c.html#1480" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01480] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01484" , "c1link" : "./qc/crypto/initthread.c.html#1484" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01484] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "02713" , "c1link" : "./qc/crypto/initthread.c.html#2713" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02713] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "02718" , "c1link" : "./qc/crypto/initthread.c.html#2718" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02718] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "02743" , "c1link" : "./qc/crypto/initthread.c.html#2743" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02743] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "02747" , "c1link" : "./qc/crypto/initthread.c.html#2747" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[02747] Suspicious mix of Bitwise and Literal expressions in (__size|__n)>=(((size_t )1)<<(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "02750" , "c1link" : "./qc/crypto/initthread.c.html#2750" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02750] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "02775" , "c1link" : "./qc/crypto/initthread.c.html#2775" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02775] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "02779" , "c1link" : "./qc/crypto/initthread.c.html#2779" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[02779] Suspicious mix of Bitwise and Literal expressions in (__size|__n)>=(((size_t )1)<<(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "02783" , "c1link" : "./qc/crypto/initthread.c.html#2783" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02783] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "02791" , "c1link" : "./qc/crypto/initthread.c.html#2791" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[02791] Suspicious mix of Bitwise and Literal expressions in (__size|__n)<(((size_t )1)<<(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "05144" , "c1link" : "./qc/crypto/initthread.c.html#5144" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05144] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06502" , "c1link" : "./qc/crypto/initthread.c.html#6502" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06502] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "06507" , "c1link" : "./qc/crypto/initthread.c.html#6507" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06507] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "06532" , "c1link" : "./qc/crypto/initthread.c.html#6532" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06532] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06537" , "c1link" : "./qc/crypto/initthread.c.html#6537" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06537] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06566" , "c1link" : "./qc/crypto/initthread.c.html#6566" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06566] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06571" , "c1link" : "./qc/crypto/initthread.c.html#6571" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06571] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06592" , "c1link" : "./qc/crypto/initthread.c.html#6592" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06592] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06597" , "c1link" : "./qc/crypto/initthread.c.html#6597" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06597] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06613" , "c1link" : "./qc/crypto/initthread.c.html#6613" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06613] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06632" , "c1link" : "./qc/crypto/initthread.c.html#6632" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06632] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06637" , "c1link" : "./qc/crypto/initthread.c.html#6637" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06637] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06657" , "c1link" : "./qc/crypto/initthread.c.html#6657" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06657] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06662" , "c1link" : "./qc/crypto/initthread.c.html#6662" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06662] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06683" , "c1link" : "./qc/crypto/initthread.c.html#6683" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06683] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06688" , "c1link" : "./qc/crypto/initthread.c.html#6688" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06688] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06709" , "c1link" : "./qc/crypto/initthread.c.html#6709" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06709] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06714" , "c1link" : "./qc/crypto/initthread.c.html#6714" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06714] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06736" , "c1link" : "./qc/crypto/initthread.c.html#6736" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06736] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06741" , "c1link" : "./qc/crypto/initthread.c.html#6741" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06741] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06765" , "c1link" : "./qc/crypto/initthread.c.html#6765" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06765] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06770" , "c1link" : "./qc/crypto/initthread.c.html#6770" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06770] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "08543" , "c1link" : "./qc/crypto/initthread.c.html#8543" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[08543] The expression alloc applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "08550" , "c1link" : "./qc/crypto/initthread.c.html#8550" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[08550] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "08586" , "c1link" : "./qc/crypto/initthread.c.html#8586" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[08586] The expression ! keep applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "08605" , "c1link" : "./qc/crypto/initthread.c.html#8605" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[08605] The pointer gtr is declared but not initialized" }} , { "ligne" : { "c1" : "08625" , "c1link" : "./qc/crypto/initthread.c.html#8625" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[08625] The pointer gtr is declared but not initialized" }} , { "ligne" : { "c1" : "08720" , "c1link" : "./qc/crypto/initthread.c.html#8720" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[08720] The pointer curr is declared but not initialized" }} , { "ligne" : { "c1" : "08724" , "c1link" : "./qc/crypto/initthread.c.html#8724" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[08724] The pointer tmp is declared but not initialized" }} , { "ligne" : { "c1" : "08726" , "c1link" : "./qc/crypto/initthread.c.html#8726" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[08726] The pointer gtr is declared but not initialized" }} , { "ligne" : { "c1" : "08788" , "c1link" : "./qc/crypto/initthread.c.html#8788" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[08788] The pointer hands is declared but not initialized" }} , { "ligne" : { "c1" : "08789" , "c1link" : "./qc/crypto/initthread.c.html#8789" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[08789] The pointer hand is declared but not initialized" }} , { "ligne" : { "c1" : "08824" , "c1link" : "./qc/crypto/initthread.c.html#8824" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[08824] The pointer gtr is declared but not initialized" }} , { "ligne" : { "c1" : "08834" , "c1link" : "./qc/crypto/initthread.c.html#8834" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[08834] The expression ! all applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "08855" , "c1link" : "./qc/crypto/initthread.c.html#8855" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[08855] The pointer tmp is declared but not initialized" }} , { "ligne" : { "c1" : "08862" , "c1link" : "./qc/crypto/initthread.c.html#8862" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[08862] The expression ! all applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "08889" , "c1link" : "./qc/crypto/initthread.c.html#8889" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[08889] The expression all applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "08892" , "c1link" : "./qc/crypto/initthread.c.html#8892" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[08892] The expression all applies to a single value or variable, might be ambiguous." }} ] }; console.log('leListeStr 99 main end'); // pages/sport/sport.js Page({ /** * 页面的初始数据 */ data: { BMI:0, BMI_score:0, total_score:0, sex:'', male:'male', female:'female', grade1:'大一', grade2:'大二', grade3:'大三', grade4:'大四', grade:'', showview1:false, showview2:false, height:0, weight:0, capacity_score:0, fiftymeter_score:0, tiqianqu_score:0, tiaoyuan_score:0, ytxs_score:0, thousandmeter_score:0, ywqz_score:0, eighthundredmeter_score:0, }, SetMale:function() { this.setData({ sex: "male", showview1: true, showview2: false }) }, SetFemale:function() { this.setData({ sex: "female", showview2: true, showview1: false }) }, SetGrade1:function() { this.setData({ grade: "大一" }) }, SetGrade2:function() { this.setData({ grade: "大二" }) }, SetGrade3:function() { this.setData({ grade: "大三" }) }, SetGrade4:function() { this.setData({ grade: "大四" }) }, HeightInput:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female this.setData({ height: e.detail.value/100 }) if(this.data.height!=0 & this.data.weight!=0){ this.setData({ BMI: (this.data.weight/(this.data.height*this.data.height)).toFixed(2) }) } if(this.data.BMI != 0){ if(Sex == Male & this.data.BMI >17.8 & this.data.BMI <23.9){ this.setData({ BMI_score: 15 }) } if(Sex == Male & this.data.BMI >=23.9 & this.data.BMI <28){ this.setData({ BMI_score: 12 }) } if(Sex == Male & this.data.BMI <= 17.8){ this.setData({ BMI_score: 12 }) } if(Sex == Male & this.data.BMI >=28){ this.setData({ BMI_score: 9 }) } if(Sex == Female & this.data.BMI >17.1 & this.data.BMI <23.9){ this.setData({ BMI_score: 15 }) } if(Sex == Female & this.data.BMI >=23.9 & this.data.BMI <28){ this.setData({ BMI_score: 12 }) } if(Sex == Female & this.data.BMI <= 17.1){ this.setData({ BMI_score: 12 }) } if(Sex == Female & this.data.BMI >=28){ this.setData({ BMI_score: 9 }) } } }, WeightInput:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female this.setData({ weight: e.detail.value }) if(this.data.height!=0 & this.data.weight!=0){ this.setData({ BMI: (this.data.weight/(this.data.height*this.data.height)).toFixed(2) }) } if(this.data.BMI != 0){ if(Sex == Male & this.data.BMI >17.8 & this.data.BMI <23.9){ this.setData({ BMI_score: 15 }) } if(Sex == Male & this.data.BMI >=23.9 & this.data.BMI <28){ this.setData({ BMI_score: 12 }) } if(Sex == Male & this.data.BMI <= 17.8){ this.setData({ BMI_score: 12 }) } if(Sex == Male & this.data.BMI >=28){ this.setData({ BMI_score: 9 }) } if(Sex == Female & this.data.BMI >17.1 & this.data.BMI <23.9){ this.setData({ BMI_score: 15 }) } if(Sex == Female & this.data.BMI >=23.9 & this.data.BMI <28){ this.setData({ BMI_score: 12 }) } if(Sex == Female & this.data.BMI <= 17.1){ this.setData({ BMI_score: 12 }) } if(Sex == Female & this.data.BMI >=28){ this.setData({ BMI_score: 9 }) } } }, CapacityScore:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female var Grade1 = this.data.grade1 var Grade2 = this.data.grade2 var Grade3 = this.data.grade3 var Grade4 = this.data.grade4 if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 5040)) { this.setData({ capacity_score: 100*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 4920) & (e.detail.value < 5040)) { this.setData({ capacity_score: 95*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 4800) & (e.detail.value < 4920)) { this.setData({ capacity_score: 90*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 4550) & (e.detail.value < 4800)) { this.setData({ capacity_score: 85*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 4300) & (e.detail.value < 4550)) { this.setData({ capacity_score: 80*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 4180) & (e.detail.value < 4300)) { this.setData({ capacity_score: 78*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 4060) & (e.detail.value < 4180)) { this.setData({ capacity_score: 76*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3940) & (e.detail.value < 4060)) { this.setData({ capacity_score: 74*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3820) & (e.detail.value < 3940)) { this.setData({ capacity_score: 72*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3700) & (e.detail.value < 3820)) { this.setData({ capacity_score: 70*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3580) & (e.detail.value < 3700)) { this.setData({ capacity_score: 68*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3460) & (e.detail.value < 3580)) { this.setData({ capacity_score: 66*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3340) & (e.detail.value < 3460)) { this.setData({ capacity_score: 64*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3220) & (e.detail.value < 3340)) { this.setData({ capacity_score: 62*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3100) & (e.detail.value < 3220)) { this.setData({ capacity_score: 60*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2490) & (e.detail.value < 3100)) { this.setData({ capacity_score: 50*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2780) & (e.detail.value < 2940)) { this.setData({ capacity_score: 40*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2620) & (e.detail.value < 2780)) { this.setData({ capacity_score: 30*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2460) & (e.detail.value < 2620)) { this.setData({ capacity_score: 20*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2300) & (e.detail.value < 2460)) { this.setData({ capacity_score: 10*0.15 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 2300)) { this.setData({ capacity_score: 0 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 5140)) { this.setData({ capacity_score: 100*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 5020) & (e.detail.value < 5140)) { this.setData({ capacity_score: 95*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 4900) & (e.detail.value < 5020)) { this.setData({ capacity_score: 90*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 4650) & (e.detail.value < 4900)) { this.setData({ capacity_score: 85*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 4400) & (e.detail.value < 4650)) { this.setData({ capacity_score: 80*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 4280) & (e.detail.value < 4400)) { this.setData({ capacity_score: 78*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 4160) & (e.detail.value < 4280)) { this.setData({ capacity_score: 76*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 4040) & (e.detail.value < 4160)) { this.setData({ capacity_score: 74*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3920) & (e.detail.value < 4040)) { this.setData({ capacity_score: 72*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3800) & (e.detail.value < 3920)) { this.setData({ capacity_score: 70*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3680) & (e.detail.value < 3800)) { this.setData({ capacity_score: 68*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3560) & (e.detail.value < 3680)) { this.setData({ capacity_score: 66*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3440) & (e.detail.value < 3560)) { this.setData({ capacity_score: 64*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3320) & (e.detail.value < 3440)) { this.setData({ capacity_score: 62*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3200) & (e.detail.value < 3320)) { this.setData({ capacity_score: 60*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3030) & (e.detail.value < 3200)) { this.setData({ capacity_score: 50*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2860) & (e.detail.value < 3030)) { this.setData({ capacity_score: 40*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2690) & (e.detail.value < 2860)) { this.setData({ capacity_score: 30*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2520) & (e.detail.value < 2690)) { this.setData({ capacity_score: 20*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2350) & (e.detail.value < 2520)) { this.setData({ capacity_score: 10*0.15 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value < 2350)) { this.setData({ capacity_score: 0 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3400)) { this.setData({ capacity_score: 100*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3350) & (e.detail.value < 3400)) { this.setData({ capacity_score: 95*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3300) & (e.detail.value < 3350)) { this.setData({ capacity_score: 90*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3150) & (e.detail.value < 3300)) { this.setData({ capacity_score: 85*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3000) & (e.detail.value < 3150)) { this.setData({ capacity_score: 80*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2900) & (e.detail.value < 3000)) { this.setData({ capacity_score: 78*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2800) & (e.detail.value < 2900)) { this.setData({ capacity_score: 76*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2700) & (e.detail.value < 2800)) { this.setData({ capacity_score: 74*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2600) & (e.detail.value < 2700)) { this.setData({ capacity_score: 72*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2500) & (e.detail.value < 2600)) { this.setData({ capacity_score: 70*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2400) & (e.detail.value < 2500)) { this.setData({ capacity_score: 68*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2300) & (e.detail.value < 2400)) { this.setData({ capacity_score: 66*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2200) & (e.detail.value < 2300)) { this.setData({ capacity_score: 64*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2100) & (e.detail.value < 2200)) { this.setData({ capacity_score: 62*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2000) & (e.detail.value < 2100)) { this.setData({ capacity_score: 60*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 1960) & (e.detail.value < 2000)) { this.setData({ capacity_score: 50*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 1920) & (e.detail.value < 1960)) { this.setData({ capacity_score: 40*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 1880) & (e.detail.value < 1920)) { this.setData({ capacity_score: 30*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 1840) & (e.detail.value < 1880)) { this.setData({ capacity_score: 20*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 1800) & (e.detail.value < 1840)) { this.setData({ capacity_score: 10*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 1800)) { this.setData({ capacity_score: 0 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3450)) { this.setData({ capacity_score: 100*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3400) & (e.detail.value < 3450)) { this.setData({ capacity_score: 95*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3350) & (e.detail.value < 3400)) { this.setData({ capacity_score: 90*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3200) & (e.detail.value < 3350)) { this.setData({ capacity_score: 85*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3050) & (e.detail.value < 3200)) { this.setData({ capacity_score: 80*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2950) & (e.detail.value < 3050)) { this.setData({ capacity_score: 78*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2850) & (e.detail.value < 2950)) { this.setData({ capacity_score: 76*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2750) & (e.detail.value < 2850)) { this.setData({ capacity_score: 74*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2650) & (e.detail.value < 2750)) { this.setData({ capacity_score: 72*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2550) & (e.detail.value < 2650)) { this.setData({ capacity_score: 70*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2450) & (e.detail.value < 2550)) { this.setData({ capacity_score: 68*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2350) & (e.detail.value < 2450)) { this.setData({ capacity_score: 66*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2250) & (e.detail.value < 2350)) { this.setData({ capacity_score: 64*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2150) & (e.detail.value < 2250)) { this.setData({ capacity_score: 62*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2050) & (e.detail.value < 2150)) { this.setData({ capacity_score: 60*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2010) & (e.detail.value < 2050)) { this.setData({ capacity_score: 50*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 1970) & (e.detail.value < 2010)) { this.setData({ capacity_score: 40*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 1930) & (e.detail.value < 1970)) { this.setData({ capacity_score: 30*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 1890) & (e.detail.value < 1930)) { this.setData({ capacity_score: 20*0.15 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 1850) & (e.detail.value < 1890)) { this.setData({ capacity_score: 10*0.15 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 1850)) { this.setData({ capacity_score: 0 }) } }, FiftyMeterScore:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female var Grade1 = this.data.grade1 var Grade2 = this.data.grade2 var Grade3 = this.data.grade3 var Grade4 = this.data.grade4 if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 6.7)) { this.setData({ fiftymeter_score: 100*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 6.7) & (e.detail.value <= 6.8)) { this.setData({ fiftymeter_score: 95*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 6.8) & (e.detail.value <= 6.9)) { this.setData({ fiftymeter_score: 90*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 6.9) & (e.detail.value <= 7.0)) { this.setData({ fiftymeter_score: 85*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 7.0) & (e.detail.value <= 7.1)) { this.setData({ fiftymeter_score: 80*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 7.1) & (e.detail.value <= 7.3)) { this.setData({ fiftymeter_score: 78*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 7.3) & (e.detail.value <= 7.5)) { this.setData({ fiftymeter_score: 76*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 7.5) & (e.detail.value <= 7.7)) { this.setData({ fiftymeter_score: 74*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 7.7) & (e.detail.value <= 7.9)) { this.setData({ fiftymeter_score: 72*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 7.9) & (e.detail.value <= 8.1)) { this.setData({ fiftymeter_score: 70*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.1) & (e.detail.value <= 8.3)) { this.setData({ fiftymeter_score: 68*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.3) & (e.detail.value <= 8.5)) { this.setData({ fiftymeter_score: 66*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.5) & (e.detail.value <= 8.7)) { this.setData({ fiftymeter_score: 64*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.7) & (e.detail.value <= 8.9)) { this.setData({ fiftymeter_score: 62*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.9) & (e.detail.value <= 9.1)) { this.setData({ fiftymeter_score: 60*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.1) & (e.detail.value <= 9.3)) { this.setData({ fiftymeter_score: 50*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.3) & (e.detail.value <= 9.5)) { this.setData({ fiftymeter_score: 40*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.5) & (e.detail.value <= 9.7)) { this.setData({ fiftymeter_score: 30*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.7) & (e.detail.value <= 9.9)) { this.setData({ fiftymeter_score: 20*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.9) & (e.detail.value <= 10.1)) { this.setData({ fiftymeter_score: 10*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 10.1)) { this.setData({ fiftymeter_score: 0 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 6.6)) { this.setData({ fiftymeter_score: 100*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 6.6) & (e.detail.value <= 6.7)) { this.setData({ fiftymeter_score: 95*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 6.7) & (e.detail.value <= 6.8)) { this.setData({ fiftymeter_score: 90*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 6.8) & (e.detail.value <= 6.9)) { this.setData({ fiftymeter_score: 85*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 6.9) & (e.detail.value <= 7.0)) { this.setData({ fiftymeter_score: 80*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 7.0) & (e.detail.value <= 7.2)) { this.setData({ fiftymeter_score: 78*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 7.2) & (e.detail.value <= 7.4)) { this.setData({ fiftymeter_score: 76*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 7.4) & (e.detail.value <= 7.6)) { this.setData({ fiftymeter_score: 74*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 7.6) & (e.detail.value <= 7.8)) { this.setData({ fiftymeter_score: 72*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 7.8) & (e.detail.value <= 8.0)) { this.setData({ fiftymeter_score: 70*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 8.0) & (e.detail.value <= 8.2)) { this.setData({ fiftymeter_score: 68*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 8.2) & (e.detail.value <= 8.4)) { this.setData({ fiftymeter_score: 66*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 8.4) & (e.detail.value <= 8.6)) { this.setData({ fiftymeter_score: 64*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 8.6) & (e.detail.value <= 8.8)) { this.setData({ fiftymeter_score: 62*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 8.8) & (e.detail.value <= 9.0)) { this.setData({ fiftymeter_score: 60*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.0) & (e.detail.value <= 9.2)) { this.setData({ fiftymeter_score: 50*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.2) & (e.detail.value <= 9.4)) { this.setData({ fiftymeter_score: 40*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.4) & (e.detail.value <= 9.6)) { this.setData({ fiftymeter_score: 30*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.6) & (e.detail.value <= 9.8)) { this.setData({ fiftymeter_score: 20*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.8) & (e.detail.value <= 10.0)) { this.setData({ fiftymeter_score: 10*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 10.0)) { this.setData({ fiftymeter_score: 0 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 7.5)) { this.setData({ fiftymeter_score: 100*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 7.5) & (e.detail.value <= 7.6)) { this.setData({ fiftymeter_score: 95*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 7.6) & (e.detail.value <= 7.7)) { this.setData({ fiftymeter_score: 90*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 7.7) & (e.detail.value <= 8.0)) { this.setData({ fiftymeter_score: 85*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.0) & (e.detail.value <= 8.3)) { this.setData({ fiftymeter_score: 80*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.3) & (e.detail.value <= 8.5)) { this.setData({ fiftymeter_score: 78*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.5) & (e.detail.value <= 8.7)) { this.setData({ fiftymeter_score: 76*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.7) & (e.detail.value <= 8.9)) { this.setData({ fiftymeter_score: 74*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 8.9) & (e.detail.value <= 9.1)) { this.setData({ fiftymeter_score: 72*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.1) & (e.detail.value <= 9.3)) { this.setData({ fiftymeter_score: 70*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.3) & (e.detail.value <= 9.5)) { this.setData({ fiftymeter_score: 68*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.5) & (e.detail.value <= 9.7)) { this.setData({ fiftymeter_score: 66*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.7) & (e.detail.value <= 9.9)) { this.setData({ fiftymeter_score: 64*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 9.9) & (e.detail.value <= 10.1)) { this.setData({ fiftymeter_score: 62*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 10.1) & (e.detail.value <= 10.3)) { this.setData({ fiftymeter_score: 60*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 10.3) & (e.detail.value <= 10.5)) { this.setData({ fiftymeter_score: 50*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 10.5) & (e.detail.value <= 10.7)) { this.setData({ fiftymeter_score: 40*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 10.7) & (e.detail.value <= 10.9)) { this.setData({ fiftymeter_score: 30*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 10.9) & (e.detail.value <= 11.1)) { this.setData({ fiftymeter_score: 20*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 11.1) & (e.detail.value <= 11.3)) { this.setData({ fiftymeter_score: 10*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 11.3)) { this.setData({ fiftymeter_score: 0 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 7.4)) { this.setData({ fiftymeter_score: 100*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 7.4) & (e.detail.value <= 7.5)) { this.setData({ fiftymeter_score: 95*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 7.5) & (e.detail.value <= 7.6)) { this.setData({ fiftymeter_score: 90*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 7.6) & (e.detail.value <= 7.9)) { this.setData({ fiftymeter_score: 85*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 7.9) & (e.detail.value <= 8.2)) { this.setData({ fiftymeter_score: 80*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 8.2) & (e.detail.value <= 8.4)) { this.setData({ fiftymeter_score: 78*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 8.4) & (e.detail.value <= 8.6)) { this.setData({ fiftymeter_score: 76*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 8.6) & (e.detail.value <= 8.8)) { this.setData({ fiftymeter_score: 74*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 8.8) & (e.detail.value <= 9.0)) { this.setData({ fiftymeter_score: 72*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.0) & (e.detail.value <= 9.2)) { this.setData({ fiftymeter_score: 70*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.2) & (e.detail.value <= 9.4)) { this.setData({ fiftymeter_score: 68*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.4) & (e.detail.value <= 9.6)) { this.setData({ fiftymeter_score: 66*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.6) & (e.detail.value <= 9.8)) { this.setData({ fiftymeter_score: 64*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 9.8) & (e.detail.value <= 10.0)) { this.setData({ fiftymeter_score: 62*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 10.0) & (e.detail.value <= 10.2)) { this.setData({ fiftymeter_score: 60*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 10.2) & (e.detail.value <= 10.4)) { this.setData({ fiftymeter_score: 50*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 10.4) & (e.detail.value <= 10.6)) { this.setData({ fiftymeter_score: 40*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 10.6) & (e.detail.value <= 10.8)) { this.setData({ fiftymeter_score: 30*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 10.8) & (e.detail.value <= 11.0)) { this.setData({ fiftymeter_score: 20*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 11.0) & (e.detail.value <= 11.2)) { this.setData({ fiftymeter_score: 10*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 11.2)) { this.setData({ fiftymeter_score: 0 }) } }, TiqianquScore:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female var Grade1 = this.data.grade1 var Grade2 = this.data.grade2 var Grade3 = this.data.grade3 var Grade4 = this.data.grade4 if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 24.9)) { this.setData({ tiqianqu_score: 100*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 23.1) & (e.detail.value < 24.9)) { this.setData({ tiqianqu_score: 95*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 21.3) & (e.detail.value < 23.1)) { this.setData({ tiqianqu_score: 90*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 19.5) & (e.detail.value < 21.3)) { this.setData({ tiqianqu_score: 85*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 17.7) & (e.detail.value < 19.5)) { this.setData({ tiqianqu_score: 80*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 16.3) & (e.detail.value < 17.7)) { this.setData({ tiqianqu_score: 78*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 14.9) & (e.detail.value < 16.3)) { this.setData({ tiqianqu_score: 76*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 13.5) & (e.detail.value < 14.9)) { this.setData({ tiqianqu_score: 74*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 12.1) & (e.detail.value < 13.5)) { this.setData({ tiqianqu_score: 72*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 10.7) & (e.detail.value < 12.1)) { this.setData({ tiqianqu_score: 70*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 9.3) & (e.detail.value < 10.7)) { this.setData({ tiqianqu_score: 68*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 7.9) & (e.detail.value < 9.3)) { this.setData({ tiqianqu_score: 66*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 6.5) & (e.detail.value < 7.90)) { this.setData({ tiqianqu_score: 64*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 5.1) & (e.detail.value < 6.5)) { this.setData({ tiqianqu_score: 62*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3.7) & (e.detail.value < 5.1)) { this.setData({ tiqianqu_score: 60*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2.7) & (e.detail.value < 3.7)) { this.setData({ tiqianqu_score: 50*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 1.7) & (e.detail.value < 2.7)) { this.setData({ tiqianqu_score: 40*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 0.7) & (e.detail.value < 1.7)) { this.setData({ tiqianqu_score: 30*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= -0.3) & (e.detail.value < 0.7)) { this.setData({ tiqianqu_score: 20*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= -1.3) & (e.detail.value < -0.3)) { this.setData({ tiqianqu_score: 10*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < -1.3)) { this.setData({ tiqianqu_score: 0 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 25.1)) { this.setData({ tiqianqu_score: 100*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 23.3) & (e.detail.value < 25.1)) { this.setData({ tiqianqu_score: 95*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 21.5) & (e.detail.value < 23.3)) { this.setData({ tiqianqu_score: 90*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 19.9) & (e.detail.value < 21.5)) { this.setData({ tiqianqu_score: 85*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 18.2) & (e.detail.value < 19.9)) { this.setData({ tiqianqu_score: 80*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 16.8) & (e.detail.value < 18.2)) { this.setData({ tiqianqu_score: 78*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 15.4) & (e.detail.value < 16.8)) { this.setData({ tiqianqu_score: 76*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 14.0) & (e.detail.value < 15.4)) { this.setData({ tiqianqu_score: 74*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 12.6) & (e.detail.value < 14.0)) { this.setData({ tiqianqu_score: 72*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 11.2) & (e.detail.value < 12.6)) { this.setData({ tiqianqu_score: 70*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 9.8) & (e.detail.value < 11.2)) { this.setData({ tiqianqu_score: 68*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 8.4) & (e.detail.value < 9.8)) { this.setData({ tiqianqu_score: 66*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 7.0) & (e.detail.value < 8.4)) { this.setData({ tiqianqu_score: 64*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 5.6) & (e.detail.value < 7.0)) { this.setData({ tiqianqu_score: 62*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 4.2) & (e.detail.value < 5.6)) { this.setData({ tiqianqu_score: 60*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3.2) & (e.detail.value < 4.2)) { this.setData({ tiqianqu_score: 50*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2.2) & (e.detail.value < 3.2)) { this.setData({ tiqianqu_score: 40*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 1.2) & (e.detail.value < 2.2)) { this.setData({ tiqianqu_score: 30*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 0.2) & (e.detail.value < 1.2)) { this.setData({ tiqianqu_score: 20*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= -0.8) & (e.detail.value < 0.2)) { this.setData({ tiqianqu_score: 10*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value < -0.8)) { this.setData({ tiqianqu_score: 0 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 25.8)) { this.setData({ tiqianqu_score: 100*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 24.0) & (e.detail.value < 25.8)) { this.setData({ tiqianqu_score: 95*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 22.2) & (e.detail.value < 24.0)) { this.setData({ tiqianqu_score: 90*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 20.6) & (e.detail.value < 22.2)) { this.setData({ tiqianqu_score: 85*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 19.0) & (e.detail.value < 20.6)) { this.setData({ tiqianqu_score: 80*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 17.7) & (e.detail.value < 19.0)) { this.setData({ tiqianqu_score: 78*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 16.4) & (e.detail.value < 17.7)) { this.setData({ tiqianqu_score: 76*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 15.1) & (e.detail.value < 16.4)) { this.setData({ tiqianqu_score: 74*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 13.8) & (e.detail.value < 15.1)) { this.setData({ tiqianqu_score: 72*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 12.5) & (e.detail.value < 13.8)) { this.setData({ tiqianqu_score: 70*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 11.2) & (e.detail.value < 12.5)) { this.setData({ tiqianqu_score: 68*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 9.9) & (e.detail.value < 11.2)) { this.setData({ tiqianqu_score: 66*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 8.6) & (e.detail.value < 9.9)) { this.setData({ tiqianqu_score: 64*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 7.3) & (e.detail.value < 8.6)) { this.setData({ tiqianqu_score: 62*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 6.0) & (e.detail.value < 7.3)) { this.setData({ tiqianqu_score: 60*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 5.2) & (e.detail.value < 6.0)) { this.setData({ tiqianqu_score: 50*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 4.4) & (e.detail.value < 5.2)) { this.setData({ tiqianqu_score: 40*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 3.6) & (e.detail.value < 4.4)) { this.setData({ tiqianqu_score: 30*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2.8) & (e.detail.value < 3.6)) { this.setData({ tiqianqu_score: 20*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 2.0) & (e.detail.value < 2.8)) { this.setData({ tiqianqu_score: 10*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 2.0)) { this.setData({ tiqianqu_score: 0 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 26.3)) { this.setData({ tiqianqu_score: 100*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 24.4) & (e.detail.value < 26.3)) { this.setData({ tiqianqu_score: 95*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 22.4) & (e.detail.value < 24.4)) { this.setData({ tiqianqu_score: 90*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 21.0) & (e.detail.value < 22.4)) { this.setData({ tiqianqu_score: 85*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 19.5) & (e.detail.value < 21.0)) { this.setData({ tiqianqu_score: 80*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 18.2) & (e.detail.value < 19.5)) { this.setData({ tiqianqu_score: 78*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 16.9) & (e.detail.value < 18.2)) { this.setData({ tiqianqu_score: 76*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 15.6) & (e.detail.value < 16.9)) { this.setData({ tiqianqu_score: 74*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 14.3) & (e.detail.value < 15.6)) { this.setData({ tiqianqu_score: 72*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 13.0) & (e.detail.value < 14.3)) { this.setData({ tiqianqu_score: 70*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 11.7) & (e.detail.value < 13.0)) { this.setData({ tiqianqu_score: 68*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 10.4) & (e.detail.value < 11.7)) { this.setData({ tiqianqu_score: 66*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 9.1) & (e.detail.value < 10.4)) { this.setData({ tiqianqu_score: 64*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 7.8) & (e.detail.value < 9.1)) { this.setData({ tiqianqu_score: 62*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 6.5) & (e.detail.value < 7.8)) { this.setData({ tiqianqu_score: 60*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 5.7) & (e.detail.value < 6.5)) { this.setData({ tiqianqu_score: 50*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 4.9) & (e.detail.value < 5.7)) { this.setData({ tiqianqu_score: 40*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 4.1) & (e.detail.value < 4.9)) { this.setData({ tiqianqu_score: 30*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 3.3) & (e.detail.value < 4.1)) { this.setData({ tiqianqu_score: 20*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 2.5) & (e.detail.value < 3.3)) { this.setData({ tiqianqu_score: 10*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 2.5)) { this.setData({ tiqianqu_score: 0 }) } }, TiaoyuanScore:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female var Grade1 = this.data.grade1 var Grade2 = this.data.grade2 var Grade3 = this.data.grade3 var Grade4 = this.data.grade4 if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 273)) { this.setData({ tiaoyuan_score: 100*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 268) & (e.detail.value < 273)) { this.setData({ tiaoyuan_score: 95*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 263) & (e.detail.value < 268)) { this.setData({ tiaoyuan_score: 90*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 256) & (e.detail.value < 263)) { this.setData({ tiaoyuan_score: 85*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 248) & (e.detail.value < 256)) { this.setData({ tiaoyuan_score: 80*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 244) & (e.detail.value < 248)) { this.setData({ tiaoyuan_score: 78*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 240) & (e.detail.value < 244)) { this.setData({ tiaoyuan_score: 76*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 236) & (e.detail.value < 240)) { this.setData({ tiaoyuan_score: 74*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 232) & (e.detail.value < 236)) { this.setData({ tiaoyuan_score: 72*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 228) & (e.detail.value < 232)) { this.setData({ tiaoyuan_score: 70*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 224) & (e.detail.value < 228)) { this.setData({ tiaoyuan_score: 68*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 220) & (e.detail.value < 224)) { this.setData({ tiaoyuan_score: 66*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 216) & (e.detail.value < 220)) { this.setData({ tiaoyuan_score: 64*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 212) & (e.detail.value < 216)) { this.setData({ tiaoyuan_score: 62*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 208) & (e.detail.value < 212)) { this.setData({ tiaoyuan_score: 60*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 203) & (e.detail.value < 208)) { this.setData({ tiaoyuan_score: 50*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 198) & (e.detail.value < 203)) { this.setData({ tiaoyuan_score: 40*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 193) & (e.detail.value < 198)) { this.setData({ tiaoyuan_score: 30*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 188) & (e.detail.value < 193)) { this.setData({ tiaoyuan_score: 20*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 183) & (e.detail.value < 188)) { this.setData({ tiaoyuan_score: 10*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 183)) { this.setData({ tiaoyuan_score: 0 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 275)) { this.setData({ tiaoyuan_score: 100*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 270) & (e.detail.value < 275)) { this.setData({ tiaoyuan_score: 95*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 265) & (e.detail.value < 270)) { this.setData({ tiaoyuan_score: 90*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 258) & (e.detail.value < 265)) { this.setData({ tiaoyuan_score: 85*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 250) & (e.detail.value < 258)) { this.setData({ tiaoyuan_score: 80*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 246) & (e.detail.value < 250)) { this.setData({ tiaoyuan_score: 78*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 242) & (e.detail.value < 246)) { this.setData({ tiaoyuan_score: 76*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 238) & (e.detail.value < 242)) { this.setData({ tiaoyuan_score: 74*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 234) & (e.detail.value < 238)) { this.setData({ tiaoyuan_score: 72*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 230) & (e.detail.value < 234)) { this.setData({ tiaoyuan_score: 70*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 226) & (e.detail.value < 230)) { this.setData({ tiaoyuan_score: 68*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 222) & (e.detail.value < 226)) { this.setData({ tiaoyuan_score: 66*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 218) & (e.detail.value < 222)) { this.setData({ tiaoyuan_score: 64*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 214) & (e.detail.value < 218)) { this.setData({ tiaoyuan_score: 62*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 210) & (e.detail.value < 214)) { this.setData({ tiaoyuan_score: 60*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 205) & (e.detail.value < 210)) { this.setData({ tiaoyuan_score: 50*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 200) & (e.detail.value < 205)) { this.setData({ tiaoyuan_score: 40*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 195) & (e.detail.value < 200)) { this.setData({ tiaoyuan_score: 30*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 190) & (e.detail.value < 195)) { this.setData({ tiaoyuan_score: 20*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 185) & (e.detail.value < 190)) { this.setData({ tiaoyuan_score: 10*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value < 185)) { this.setData({ tiaoyuan_score: 0 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 207)) { this.setData({ tiaoyuan_score: 100*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 201) & (e.detail.value < 207)) { this.setData({ tiaoyuan_score: 95*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 195) & (e.detail.value < 201)) { this.setData({ tiaoyuan_score: 90*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 188) & (e.detail.value < 195)) { this.setData({ tiaoyuan_score: 85*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 181) & (e.detail.value < 188)) { this.setData({ tiaoyuan_score: 80*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 178) & (e.detail.value < 181)) { this.setData({ tiaoyuan_score: 78*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 175) & (e.detail.value < 178)) { this.setData({ tiaoyuan_score: 76*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 172) & (e.detail.value < 175)) { this.setData({ tiaoyuan_score: 74*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 169) & (e.detail.value < 172)) { this.setData({ tiaoyuan_score: 72*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 166) & (e.detail.value < 169)) { this.setData({ tiaoyuan_score: 70*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 163) & (e.detail.value < 166)) { this.setData({ tiaoyuan_score: 68*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 160) & (e.detail.value < 163)) { this.setData({ tiaoyuan_score: 66*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 157) & (e.detail.value < 160)) { this.setData({ tiaoyuan_score: 64*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 154) & (e.detail.value < 157)) { this.setData({ tiaoyuan_score: 62*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 151) & (e.detail.value < 154)) { this.setData({ tiaoyuan_score: 60*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 146) & (e.detail.value < 151)) { this.setData({ tiaoyuan_score: 50*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 141) & (e.detail.value < 146)) { this.setData({ tiaoyuan_score: 40*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 136) & (e.detail.value < 141)) { this.setData({ tiaoyuan_score: 30*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 131) & (e.detail.value < 136)) { this.setData({ tiaoyuan_score: 20*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 126) & (e.detail.value < 131)) { this.setData({ tiaoyuan_score: 10*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 126)) { this.setData({ tiaoyuan_score: 0 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 208)) { this.setData({ tiaoyuan_score: 100*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 202) & (e.detail.value < 208)) { this.setData({ tiaoyuan_score: 95*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 196) & (e.detail.value < 202)) { this.setData({ tiaoyuan_score: 90*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 189) & (e.detail.value < 196)) { this.setData({ tiaoyuan_score: 85*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 182) & (e.detail.value < 189)) { this.setData({ tiaoyuan_score: 80*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 179) & (e.detail.value < 182)) { this.setData({ tiaoyuan_score: 78*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 176) & (e.detail.value < 179)) { this.setData({ tiaoyuan_score: 76*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 173) & (e.detail.value < 176)) { this.setData({ tiaoyuan_score: 74*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 170) & (e.detail.value < 173)) { this.setData({ tiaoyuan_score: 72*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 167) & (e.detail.value < 170)) { this.setData({ tiaoyuan_score: 70*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 164) & (e.detail.value < 167)) { this.setData({ tiaoyuan_score: 68*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 161) & (e.detail.value < 164)) { this.setData({ tiaoyuan_score: 66*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 158) & (e.detail.value < 161)) { this.setData({ tiaoyuan_score: 64*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 155) & (e.detail.value < 158)) { this.setData({ tiaoyuan_score: 62*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 152) & (e.detail.value < 155)) { this.setData({ tiaoyuan_score: 60*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 147) & (e.detail.value < 152)) { this.setData({ tiaoyuan_score: 50*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 142) & (e.detail.value < 147)) { this.setData({ tiaoyuan_score: 40*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 137) & (e.detail.value < 142)) { this.setData({ tiaoyuan_score: 30*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 132) & (e.detail.value < 137)) { this.setData({ tiaoyuan_score: 20*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 127) & (e.detail.value < 132)) { this.setData({ tiaoyuan_score: 10*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 127)) { this.setData({ tiaoyuan_score: 0 }) } }, YtxsScore:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female var Grade1 = this.data.grade1 var Grade2 = this.data.grade2 var Grade3 = this.data.grade3 var Grade4 = this.data.grade4 if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 19)) { this.setData({ ytxs_score: 100*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 18) & (e.detail.value <19)) { this.setData({ ytxs_score: 95*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 17) & (e.detail.value < 18)) { this.setData({ ytxs_score: 90*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 16) & (e.detail.value < 17)) { this.setData({ ytxs_score: 85*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 15) & (e.detail.value < 16)) { this.setData({ ytxs_score: 80*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 14) & (e.detail.value < 15)) { this.setData({ ytxs_score: 76*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 13) & (e.detail.value < 14)) { this.setData({ ytxs_score: 72*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 12) & (e.detail.value < 13)) { this.setData({ ytxs_score: 68*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 11) & (e.detail.value < 12)) { this.setData({ ytxs_score: 64*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 10) & (e.detail.value < 11)) { this.setData({ ytxs_score: 60*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 9) & (e.detail.value < 10)) { this.setData({ ytxs_score: 50*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 8) & (e.detail.value < 9)) { this.setData({ ytxs_score: 40*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 7) & (e.detail.value < 8)) { this.setData({ ytxs_score: 30*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 6) & (e.detail.value < 7)) { this.setData({ ytxs_score: 20*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 5) & (e.detail.value < 6)) { this.setData({ ytxs_score: 10*0.1 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 5)) { this.setData({ ytxs_score: 0 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 20)) { this.setData({ ytxs_score: 100*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 19) & (e.detail.value < 20)) { this.setData({ ytxs_score: 95*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 18) & (e.detail.value < 19)) { this.setData({ ytxs_score: 90*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 17) & (e.detail.value < 18)) { this.setData({ ytxs_score: 85*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 16) & (e.detail.value < 17)) { this.setData({ ytxs_score: 80*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 15) & (e.detail.value < 16)) { this.setData({ ytxs_score: 76*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 14) & (e.detail.value < 15)) { this.setData({ ytxs_score: 72*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 13) & (e.detail.value < 14)) { this.setData({ ytxs_score: 68*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 12) & (e.detail.value < 13)) { this.setData({ ytxs_score: 64*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 11) & (e.detail.value < 12)) { this.setData({ ytxs_score: 60*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 10) & (e.detail.value < 11)) { this.setData({ ytxs_score: 50*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 9) & (e.detail.value < 10)) { this.setData({ ytxs_score: 40*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 8) & (e.detail.value < 9)) { this.setData({ ytxs_score: 30*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 7) & (e.detail.value < 8)) { this.setData({ ytxs_score: 20*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 6) & (e.detail.value < 7)) { this.setData({ ytxs_score: 10*0.1 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value < 6)) { this.setData({ ytxs_score: 0 }) } }, ThousandScore:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female var Grade1 = this.data.grade1 var Grade2 = this.data.grade2 var Grade3 = this.data.grade3 var Grade4 = this.data.grade4 if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 197)) { this.setData({ thousandmeter_score: 100*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 202) & (e.detail.value >197)) { this.setData({ thousandmeter_score: 95*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 207) & (e.detail.value > 202)) { this.setData({ thousandmeter_score: 90*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 214) & (e.detail.value > 207)) { this.setData({ thousandmeter_score: 85*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 222) & (e.detail.value > 214)) { this.setData({ thousandmeter_score: 80*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 227) & (e.detail.value > 222)) { this.setData({ thousandmeter_score: 78*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 232) & (e.detail.value > 227)) { this.setData({ thousandmeter_score: 76*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 237) & (e.detail.value > 232)) { this.setData({ thousandmeter_score: 74*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 242) & (e.detail.value > 237)) { this.setData({ thousandmeter_score: 72*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 247) & (e.detail.value > 242)) { this.setData({ thousandmeter_score: 70*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 252) & (e.detail.value > 247)) { this.setData({ thousandmeter_score: 68*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 257) & (e.detail.value > 252)) { this.setData({ thousandmeter_score: 66*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 262) & (e.detail.value > 257)) { this.setData({ thousandmeter_score: 64*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 267) & (e.detail.value > 262)) { this.setData({ thousandmeter_score: 62*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 272) & (e.detail.value > 267)) { this.setData({ thousandmeter_score: 60*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 292) & (e.detail.value > 272)) { this.setData({ thousandmeter_score: 50*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 312) & (e.detail.value > 292)) { this.setData({ thousandmeter_score: 40*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 332) & (e.detail.value > 312)) { this.setData({ thousandmeter_score: 30*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 352) & (e.detail.value > 332)) { this.setData({ thousandmeter_score: 20*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 372) & (e.detail.value > 352)) { this.setData({ thousandmeter_score: 10*0.2 }) } if ( (Sex == Male) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 372)) { this.setData({ thousandmeter_score: 0 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 195)) { this.setData({ thousandmeter_score: 100*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 200) & (e.detail.value >195)) { this.setData({ thousandmeter_score: 95*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 205) & (e.detail.value > 200)) { this.setData({ thousandmeter_score: 90*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 212) & (e.detail.value > 205)) { this.setData({ thousandmeter_score: 85*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 220) & (e.detail.value > 212)) { this.setData({ thousandmeter_score: 80*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 225) & (e.detail.value > 220)) { this.setData({ thousandmeter_score: 78*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 230) & (e.detail.value > 225)) { this.setData({ thousandmeter_score: 76*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 235) & (e.detail.value > 230)) { this.setData({ thousandmeter_score: 74*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 240) & (e.detail.value > 235)) { this.setData({ thousandmeter_score: 72*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 245) & (e.detail.value > 240)) { this.setData({ thousandmeter_score: 70*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 250) & (e.detail.value > 245)) { this.setData({ thousandmeter_score: 68*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 255) & (e.detail.value > 250)) { this.setData({ thousandmeter_score: 66*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 260) & (e.detail.value > 255)) { this.setData({ thousandmeter_score: 64*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 265) & (e.detail.value > 260)) { this.setData({ thousandmeter_score: 62*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 270) & (e.detail.value > 265)) { this.setData({ thousandmeter_score: 60*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 290) & (e.detail.value > 270)) { this.setData({ thousandmeter_score: 50*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 310) & (e.detail.value > 290)) { this.setData({ thousandmeter_score: 40*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 330) & (e.detail.value > 310)) { this.setData({ thousandmeter_score: 30*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 350) & (e.detail.value > 330)) { this.setData({ thousandmeter_score: 20*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 370) & (e.detail.value > 350)) { this.setData({ thousandmeter_score: 10*0.2 }) } if ( (Sex == Male) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value > 370)) { this.setData({ thousandmeter_score: 0 }) } }, YwqzScore:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female var Grade1 = this.data.grade1 var Grade2 = this.data.grade2 var Grade3 = this.data.grade3 var Grade4 = this.data.grade4 if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 56)) { this.setData({ ywqz_score: 100*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 54) & (e.detail.value < 56)) { this.setData({ ywqz_score: 95*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 52) & (e.detail.value < 54)) { this.setData({ ywqz_score: 90*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 49) & (e.detail.value < 52)) { this.setData({ ywqz_score: 85*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 46) & (e.detail.value < 49)) { this.setData({ ywqz_score: 80*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 44) & (e.detail.value < 46)) { this.setData({ ywqz_score: 78*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 42) & (e.detail.value < 44)) { this.setData({ ywqz_score: 76*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 40) & (e.detail.value < 42)) { this.setData({ ywqz_score: 74*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 38) & (e.detail.value < 40)) { this.setData({ ywqz_score: 72*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 36) & (e.detail.value < 38)) { this.setData({ ywqz_score: 70*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 34) & (e.detail.value < 36)) { this.setData({ ywqz_score: 68*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 32) & (e.detail.value < 34)) { this.setData({ ywqz_score: 66*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 30) & (e.detail.value < 32)) { this.setData({ ywqz_score: 64*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 28) & (e.detail.value < 30)) { this.setData({ ywqz_score: 62*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 26) & (e.detail.value < 28)) { this.setData({ ywqz_score: 60*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 24) & (e.detail.value < 26)) { this.setData({ ywqz_score: 50*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 22) & (e.detail.value < 24)) { this.setData({ ywqz_score: 40*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 20) & (e.detail.value < 22)) { this.setData({ ywqz_score: 30*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 18) & (e.detail.value < 20)) { this.setData({ ywqz_score: 20*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value >= 16) & (e.detail.value < 18)) { this.setData({ ywqz_score: 10*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 16)) { this.setData({ ywqz_score: 0 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 57)) { this.setData({ ywqz_score: 100*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 55) & (e.detail.value < 57)) { this.setData({ ywqz_score: 95*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 53) & (e.detail.value < 55)) { this.setData({ ywqz_score: 90*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 50) & (e.detail.value < 53)) { this.setData({ ywqz_score: 85*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 47) & (e.detail.value < 50)) { this.setData({ ywqz_score: 80*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 45) & (e.detail.value < 47)) { this.setData({ ywqz_score: 78*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 43) & (e.detail.value < 45)) { this.setData({ ywqz_score: 76*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 41) & (e.detail.value < 43)) { this.setData({ ywqz_score: 74*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 39) & (e.detail.value < 41)) { this.setData({ ywqz_score: 72*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 37) & (e.detail.value < 39)) { this.setData({ ywqz_score: 70*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 35) & (e.detail.value < 37)) { this.setData({ ywqz_score: 68*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 33) & (e.detail.value < 35)) { this.setData({ ywqz_score: 66*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 31) & (e.detail.value < 33)) { this.setData({ ywqz_score: 64*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 29) & (e.detail.value < 31)) { this.setData({ ywqz_score: 62*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 27) & (e.detail.value < 29)) { this.setData({ ywqz_score: 60*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 25) & (e.detail.value < 27)) { this.setData({ ywqz_score: 50*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 23) & (e.detail.value < 25)) { this.setData({ ywqz_score: 40*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 21) & (e.detail.value < 23)) { this.setData({ ywqz_score: 30*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 19) & (e.detail.value < 21)) { this.setData({ ywqz_score: 20*0.1 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value >= 17) & (e.detail.value < 19)) { this.setData({ ywqz_score: 10*0.1 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value < 17)) { this.setData({ ywqz_score: 0 }) } }, EightHundredScore:function(e) { var Sex = this.data.sex var Grade = this.data.grade var Male = this.data.male var Female = this.data.female var Grade1 = this.data.grade1 var Grade2 = this.data.grade2 var Grade3 = this.data.grade3 var Grade4 = this.data.grade4 if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 198)) { this.setData({ eighthundredmeter_score: 100*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 204) & (e.detail.value > 198)) { this.setData({ eighthundredmeter_score: 95*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 210) & (e.detail.value > 204)) { this.setData({ eighthundredmeter_score: 90*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 217) & (e.detail.value > 210)) { this.setData({ eighthundredmeter_score: 85*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 224) & (e.detail.value > 217)) { this.setData({ eighthundredmeter_score: 80*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 229) & (e.detail.value > 224)) { this.setData({ eighthundredmeter_score: 78*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 234) & (e.detail.value > 229)) { this.setData({ eighthundredmeter_score: 76*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 239) & (e.detail.value > 234)) { this.setData({ eighthundredmeter_score: 74*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 244) & (e.detail.value > 239)) { this.setData({ eighthundredmeter_score: 72*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 249) & (e.detail.value > 244)) { this.setData({ eighthundredmeter_score: 70*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 254) & (e.detail.value > 249)) { this.setData({ eighthundredmeter_score: 68*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 259) & (e.detail.value > 254)) { this.setData({ eighthundredmeter_score: 66*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 264) & (e.detail.value > 259)) { this.setData({ eighthundredmeter_score: 64*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 269) & (e.detail.value > 264)) { this.setData({ eighthundredmeter_score: 62*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 274) & (e.detail.value > 269)) { this.setData({ eighthundredmeter_score: 60*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 284) & (e.detail.value > 274)) { this.setData({ eighthundredmeter_score: 50*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 294) & (e.detail.value > 284)) { this.setData({ eighthundredmeter_score: 40*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 304) & (e.detail.value > 294)) { this.setData({ eighthundredmeter_score: 30*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 314) & (e.detail.value > 304)) { this.setData({ eighthundredmeter_score: 20*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value <= 324) & (e.detail.value > 314)) { this.setData({ eighthundredmeter_score: 10*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 324)) { this.setData({ eighthundredmeter_score: 0 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 196)) { this.setData({ eighthundredmeter_score: 100*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 202) & (e.detail.value > 196)) { this.setData({ eighthundredmeter_score: 95*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 208) & (e.detail.value > 202)) { this.setData({ eighthundredmeter_score: 90*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 215) & (e.detail.value > 208)) { this.setData({ eighthundredmeter_score: 85*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 222) & (e.detail.value > 215)) { this.setData({ eighthundredmeter_score: 80*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 227) & (e.detail.value > 222)) { this.setData({ eighthundredmeter_score: 78*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 232) & (e.detail.value > 227)) { this.setData({ eighthundredmeter_score: 76*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 237) & (e.detail.value > 232)) { this.setData({ eighthundredmeter_score: 74*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 242) & (e.detail.value > 237)) { this.setData({ eighthundredmeter_score: 72*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 247) & (e.detail.value > 242)) { this.setData({ eighthundredmeter_score: 70*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 252) & (e.detail.value > 247)) { this.setData({ eighthundredmeter_score: 68*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 257) & (e.detail.value > 252)) { this.setData({ eighthundredmeter_score: 66*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 262) & (e.detail.value > 257)) { this.setData({ eighthundredmeter_score: 64*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 267) & (e.detail.value > 262)) { this.setData({ eighthundredmeter_score: 62*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 272) & (e.detail.value > 267)) { this.setData({ eighthundredmeter_score: 60*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 282) & (e.detail.value > 272)) { this.setData({ eighthundredmeter_score: 50*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 292) & (e.detail.value > 282)) { this.setData({ eighthundredmeter_score: 40*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 302) & (e.detail.value > 292)) { this.setData({ eighthundredmeter_score: 30*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 312) & (e.detail.value > 302)) { this.setData({ eighthundredmeter_score: 20*0.2 }) } if ( (Sex == Female) & (Grade == Grade3 || Grade == Grade4) & (e.detail.value <= 322) & (e.detail.value > 312)) { this.setData({ eighthundredmeter_score: 10*0.2 }) } if ( (Sex == Female) & (Grade == Grade1 || Grade == Grade2) & (e.detail.value > 322)) { this.setData({ eighthundredmeter_score: 0 }) } }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })'use strict' var DEFAULT_MAXAGE = 60000 var expiration = {} var history = {} var expireListeners = {} var size = 0 var interval = null function get (pid, maxage) { if (maxage <= 0) { return } if (history[pid] !== undefined) { expiration[pid] = Date.now() + (maxage || DEFAULT_MAXAGE) } return history[pid] } function set (pid, object, maxage, onExpire) { if (object === undefined || maxage <= 0) return expiration[pid] = Date.now() + (maxage || DEFAULT_MAXAGE) if (history[pid] === undefined) { size++ sheduleInvalidator(maxage) } history[pid] = object if (onExpire) { expireListeners[pid] = onExpire } } function sheduleInvalidator (maxage) { if (size > 0) { if (interval === null) { interval = setInterval(runInvalidator, (maxage || DEFAULT_MAXAGE) / 2) } return } if (interval !== null) { clearInterval(interval) interval = null } } function runInvalidator () { var now = Date.now() var pids = Object.keys(expiration) for (var i = 0; i < pids.length; i++) { var pid = pids[i] if (expiration[pid] < now) { size-- if (expireListeners[pid]) { expireListeners[pid](history[pid]) } delete history[pid] delete expiration[pid] delete expireListeners[pid] } } sheduleInvalidator() } function deleteLoop (obj) { for (const i in obj) { delete obj[i] } } function clear () { if (interval !== null) { clearInterval(interval) interval = null } deleteLoop(history) deleteLoop(expiration) deleteLoop(expireListeners) } module.exports = { get: get, set: set, clear: clear } hoanghoang124/superMegaUltraAssignement import styled from 'styled-components'; import { Form } from 'antd'; export const FilterFormWrapper = styled(Form)` margin: auto; margin-bottom: 30px; background: ${({ theme }) => theme.background.content}; padding: 20px; .filterContainer { display: flex; @media only screen and (max-width: 768px) { flex-direction: column; } } .filterContent { flex: 1; justify-content: flex-end; margin-right: 10px; & > div { display: flex; justify-content: space-between; .ant-form-item { margin-bottom: 0; .ant-form-item-control { line-height: normal; } } } @media only screen and (max-width: 576px) { margin-right: 0px; } } .filterActions { width: 250px; .ant-btn { height: 40px; } @media only screen and (max-width: 768px) { display: block; width: 100%; .ant-row > .ant-col { margin-bottom: 15px; } } } .border { } .filterButton { width: 100%; font-size: 14px; } .clearButton { background: ${({ theme }) => theme.background.disabled}; color: white; } .ant-form-item { margin-bottom: 0px; margin-right: -1px; } .ant-form-item-label label { color: ${({ theme }) => theme.text.itemLabel}; } `; pbhushan/gatsby-theme-1src/theme/classicRetro.js const classicRetro = { bg: { default: 'transparent', neutral: '#6A8A82', primary: '#563838', secondary: '#A37C27', variant: '#A7414A', surface: '#ffffff', blackdrop: '#282726', }, text: { default: '#000000', neutral: '#ffffff', primary: '#ffffff', secondary: '#ffffff', variant: '#ffffff', surface: '#000000', blackdrop: '#ffffff', }, } export default classicRetro patil215/v8 function main() { const v4 = [13.37,13.37,13.37,13.37]; const v6 = [1337]; const v7 = [v6]; const v8 = {max:Function,setPrototypeOf:10}; const v9 = {exec:v6}; let v10 = "undefined"; const v15 = [13.37,13.37,13.37,13.37]; const v17 = [1337]; const v18 = [v17]; const v19 = {max:Function,setPrototypeOf:10}; const v20 = {exec:v17}; let v21 = "undefined"; const v37 = [13.37,13.37,13.37,13.37]; const v39 = [1337]; const v40 = [v39]; const v41 = {exec:v39}; let v42 = "undefined"; const v49 = [13.37,13.37,13.37,13.37]; const v54 = [13.37,13.37,13.37,13.37]; const v56 = [1337]; const v57 = [v56]; const v58 = {max:Function,setPrototypeOf:10}; const v59 = {exec:v56}; let v60 = "undefined"; const v65 = [13.37,13.37,13.37,13.37]; const v67 = [-3978287079]; const v68 = [v67]; const v69 = {max:Function,setPrototypeOf:10}; const v70 = {exec:v67}; let v71 = "undefined"; const v76 = [13.37,13.37,13.37,13.37]; const v78 = [1337]; const v79 = [v78]; const v80 = {max:Function,setPrototypeOf:10}; const v81 = {exec:v78}; let v82 = "undefined"; const v87 = [13.37,13.37,13.37,13.37]; const v93 = [13.37,13.37,13.37,13.37]; const v95 = [-536870912]; const v96 = [v95]; const v97 = {max:Function,setPrototypeOf:10}; const v98 = {exec:v95}; let v99 = "undefined"; const v104 = [13.37,13.37,13.37,13.37]; const v106 = [1337]; const v107 = [v106]; const v108 = {max:Function,setPrototypeOf:10}; const v109 = {exec:v106}; let v110 = "undefined"; const v115 = Function && 13.37; let v117 = 0; const v118 = v117 + 1; const v119 = [13.37,13.37,13.37,13.37]; const v121 = [1337]; const v122 = [v121]; const v123 = {max:Function,setPrototypeOf:10}; const v124 = {exec:v121}; let v125 = "undefined"; let v127 = 13.37; const v134 = [13.37,13.37,13.37,13.37]; const v136 = [1337]; const v137 = [v136]; const v138 = {max:Function,setPrototypeOf:10}; const v139 = {exec:v136}; let v140 = "number"; const v145 = Function && 13.37; let v148 = 0; const v149 = v148 + 1; const v150 = [13.37,13.37,13.37,13.37]; const v152 = [1337]; const v163 = [v152]; const v164 = {max:Function,setPrototypeOf:10}; const v165 = {round:v152}; let v166 = "undefined"; let v168 = 13.37; const v170 = [13.37,13.37,13.37,13.37]; const v171 = [13.37]; const v172 = [v171]; const v173 = v123 - 1; let v174 = "undefined"; const v176 = {pow:v171,catch:"undefined",b:v172,flat:v150}; const v177 = Object(); const v178 = [13.37,13.37,13.37,13.37]; const v180 = [13.37]; const v181 = [v180]; const v182 = {max:Function,setPrototypeOf:1337}; let v183 = "undefined"; const v188 = [13.37,13.37,13.37,13.37]; const v190 = [1337]; const v191 = [v190]; const v192 = {max:Function,setPrototypeOf:10}; const v193 = {exec:v190}; let v194 = "undefined"; const v201 = [13.37,13.37,13.37,13.37]; let v203 = 0; const v204 = v203 + 1; const v205 = Function.__lookupGetter__; const v206 = []; const v207 = [13.37,13.37,13.37,13.37]; const v210 = {max:Function,setPrototypeOf:10}; let v215 = 0; const v216 = {max:Function,reduceRight:10}; const v218 = [1337]; const v219 = [v218]; const v220 = {max:Function,setPrototypeOf:10}; const v221 = {exec:v218}; let v222 = "undefined"; const v228 = [13.37]; const v229 = [v228]; const v231 = {pow:v228,catch:"undefined",b:v229,flat:v207}; const v232 = Object(); const v234 = {pow:v180,catch:"undefined",b:v181,flat:v119}; const v235 = [1337]; const v236 = [v235]; const v237 = {max:Function,setPrototypeOf:10}; let v238 = "undefined"; const v243 = [13.37,13.37,13.37,13.37]; const v247 = [1337]; const v248 = [v247]; const v249 = {max:Function,setPrototypeOf:10}; const v250 = {exec:v247}; let v251 = "undefined"; const v398 = Function + Object; const v455 = {isNaN:Function,acos:1337,keys:1337,replace:v221,...v149,...Function,...v108,...10}; } %NeverOptimizeFunction(main); main(); UCSFMemoryAndAging/lava /** * Copyright 2004 - 2005 uitags * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ////////////////////////////////////// ////////// Class Definition ////////// ////////////////////////////////////// function uiHtml_DebugPanel(initialText) { this._super(uiHtml_Document.getInstance().createDomObject("div")); this.__initialize(initialText); } uiHtml_DebugPanel = uiUtil_Object.declareClass(uiHtml_DebugPanel, uiHtml_Panel); uiHtml_DebugPanel.__fallbackInstance = null; uiHtml_DebugPanel.__instance = null; //////////////////////////////////////// ////////// Non-static Methods ////////// //////////////////////////////////////// uiHtml_DebugPanel.prototype.__initialize = function(initialText) { this.__contentPane = uiHtml_Panel.create(false); this.setContent(this.__contentPane.getDomObject()); this.__printStream = new uiHtml_PrintSupporter( this.__contentPane.getDomObject()); this.println(initialText); // manually initilize the logger, since we didn't use uiUtil_Type to // declare this class this.__logger = uiUtil_Logger.getInstance(uiHtml_DebugPanel); }; // attach a drag handle a the top of the panel uiHtml_DebugPanel.prototype.enableDragHandle = function() { var domDiv = uiHtml_Document.getInstance().createDomObject("div"); this.getDomObject().appendChild(domDiv); var dragHandle = new uiHtml_Panel(domDiv, false); this.enableDragSupport(dragHandle); dragHandle.setStyleAttribute("border-bottom", "1px solid blue"); dragHandle.setStyleAttribute("background-color", "#cdd8e3"); dragHandle.setStyleAttribute("position", "absolute"); dragHandle.setDimension(0, 0, this.getWidth(), 18); if (this.getContent() != null) { var content = uiHtml_Element.createElementByType(this.getContent()); content.setStyleAttribute("position", "absolute"); content.setDimension(0, 20); } this.setDimension(null, null, null, this.getHeight() + 18); }; uiHtml_DebugPanel.prototype.print = function(text) { if (this.__printStream) { this.__printStream.print(text); this.__contentPane.scrollToBottom(); } else { // only happens when error occurs before the stream is initialized alert(text); } }; uiHtml_DebugPanel.prototype.println = function(text) { if (this.__printStream) { this.__printStream.println(text); this.__contentPane.scrollToBottom(); } else { // only happens when error occurs before the stream is initialized alert(text); } }; //////////////////////////////////// ////////// Static Methods ////////// //////////////////////////////////// uiHtml_DebugPanel.__initializeDefaultStyle = function() { var panel = uiHtml_DebugPanel.__instance; panel.__contentPane.showScrollBars(); panel.__contentPane.setDimension(0, 0, 400, 300); panel.__contentPane.setStyleAttribute("background-color", "#ffffe1"); panel.setDepth(5); panel.setStyleAttribute("position", "absolute"); panel.setDimension(400, 300, 400, 300); panel.setStyleAttribute("border", "1px solid blue"); panel.enableDragHandle(); panel.show(); }; uiHtml_DebugPanel.getInstance = function(initialText) { if (uiHtml_DebugPanel.__instance == null) { uiHtml_DebugPanel.__fallbackInstance = uiUtil_Logger.getDefaultPrintStream(); // initialize a fallback logger first to avoid recursion uiHtml_DebugPanel.__instance = uiHtml_DebugPanel.__fallbackInstance; } if (uiHtml_DebugPanel.__instance == uiHtml_DebugPanel.__fallbackInstance) { var tempHolder = new uiHtml_DebugPanel(initialText); uiHtml_DebugPanel.__instance = tempHolder; uiHtml_DebugPanel.__initializeDefaultStyle(); } return uiHtml_DebugPanel.__instance; }; modules/FileTreeView.js /*jslint node: true, expr: true, vars: true, plusplus: true, devel: true, nomen: true, white: true, regexp: true, indent: 2, maxerr: 50 */ /*global define, $, brackets, Mustache, window, console */ define(function (require, exports, module) { "use strict"; // HEADER >> var FileUtils = brackets.getModule("file/FileUtils"), ExtensionUtils = brackets.getModule("utils/ExtensionUtils"), EventDispatcher = brackets.getModule("utils/EventDispatcher"), ProjectManager = brackets.getModule("project/ProjectManager"), DocumentManager = brackets.getModule("document/DocumentManager"), Async = brackets.getModule("utils/Async"), EditorManager = brackets.getModule("editor/EditorManager"), FileSystem = brackets.getModule("filesystem/FileSystem"), MainViewManager = brackets.getModule("view/MainViewManager"), _ = brackets.getModule("thirdparty/lodash"), Log = require("modules/Log"); var DialogCollection = require("modules/DialogCollection"); var PathManager = require("modules/PathManager"); var RemoteManager = require("modules/RemoteManager"); var Menu = require("modules/Menu"); var Project = require("modules/Project"); var FileManager = require("modules/FileManager"); var Strings = require("strings"); var _modulePath = FileUtils.getParentPath(ExtensionUtils.getModulePath(module)), _remoteRootPath = null, _renameValidate, _currentServerSetting = null, _ctxMenuCurrentEntity = null; var rootEntity, offset_left = 13; // font-size var PROJECT_DIR = "PROJ"; var _checkPrimitive, _getProjectDirectoryPath, _setEntity, _rename, _setElement, _projectDir, _makeRowElement, _makeBaseDirectoryIfIsNotExists, _openFile, _localEntryActualDelete, _getEntityWithElement, _loadDirectory, _deleteEntity, _resetElement, _rebuildChildrenIndex, _attachEvent, _detachEvent, _getEntityWithId, _getElementWithEntity, _toggleDir, _newFile, getPathArray, refresh, rename, deleteFile, removeFile, newFile, removeDirectory, newDirectory, init, setEntities, getEntityWithPath, clearCurrentTree, open, loadTreeView, updateTreeviewContainerSize, onClick, onDirClicked, onFileClicked, onTreeViewContextMenu, onProjectStateChanged; var j = { get container() { return $("#synapse-tree"); }, get root_ul() { return $("#synapse-tree > ul"); }, get m() { return $("#synapse"); }, get h() { return $("#synapse-header"); }, get tvc() { return $("#synapse-treeview-container"); }, get l() { return $("#synapse-server-list"); }, get s() { return $("#synapse-server-setting"); } }; var Icon = { file: "fa fa-file-text", lFile: "fa fa-file-text-o", folder: "fa fa-folder", folder_open: "fa fa-folder-open", lFolder: "fa fa-folder-o", lFolder_open: "fa fa-folder_o_open", block: "fa fa-unlink" }; var Entity = function (param) { if (param.class === undefined || param.text === undefined || param.parent === undefined) { throw new Error("Invalid parameters."); } this.class = param.class; this.type = param.type; this.text = param.text; this.mode = param.mode || null; this.size = param.size || 0; this.date = param.date; this.parent = param.parent; this.opt = param.opt || {}; this.depth = param.depth; this.index = param.index; this.id = param.id; this.downloaded = false; this.target = param.target || null; this.destType = param.destType || null; this.children = {}; }; //<< init = function () { var d = new $.Deferred(); _attachEvent(); Project.on(Project.PROJECT_STATE_CHANGED, onProjectStateChanged); Menu.initTreeViewContextMenu() .then(d.resolve); return d.promise(); }; /** * Load entity to the file tree view with root entity, * root entity created by parameter. * * @param {object} server setting object. * @return {$.Promise} a promise that will be resolved with root entity, that never rejected. */ loadTreeView = function (serverSetting) { var d = new $.Deferred(); _currentServerSetting = serverSetting; _remoteRootPath = _currentServerSetting.dir; j.root_ul.remove(); var param = { class: "treeview-root", type: "directory", text: _currentServerSetting.name, opt: {}, parent: null, children: {}, depth: 0, index: 0, id: "0" }; _setEntity(param) .then(function (entity) { rootEntity = entity; return _setElement(null); }) .then(function () { d.resolve(rootEntity); }); return d.promise(); }; clearCurrentTree = function () { _currentServerSetting = null; _remoteRootPath = null; j.root_ul.remove(); return new $.Deferred().resolve().promise(); }; setEntities = function (list, parent) { if (parent.type !== "directory" && parent.type !== "ldirectory") { throw new Error("the type property of the parent object must set directory"); } // list = _.pluck(_.sortBy(list, "name"), "name"); var deferred = new $.Deferred(), promises = [], params = []; var dirs = _.where(list, {type: "d"}); var files = _.where(list, {type: "-"}); var links = _.where(list, {type: "l"}), blocks = _.where(links, {destType: "block"}), ldirs = _.where(links, {destType: "ldirectory"}), lfiles = _.where(links, {destType: "lfile"}); list = []; list = list .concat(dirs) .concat(ldirs) .concat(files) .concat(lfiles) .concat(blocks); list=list.sort(function(a,b){ var typesort = 0, res = 0; typesort = (a.type === 'd' && a.type !== b.type) ? -1 : (b.type === 'd' && a.type !== b.type) ? 1 : 0; return (typesort !== 0) ? typesort : (a.name.toLowerCase() < b.name.toLowerCase()) ? -1 : (a.name.toLowerCase() > b.name.toLowerCase()) ? 1 : 0; /* if(a['type'] === 'd' && a['type'] !== b['type']){ typesort = -1; } else if(b['type'] === 'd' && a['type'] !== b['type']){ typesort = 1; } if(typesort !== 0){ return typesort; } if(a['name'].toLowerCase()b['name'].toLowerCase()){ return 1; } return 0; */ }); var depth = parent.depth + 1; list.forEach(function (item, index) { var type = "block"; switch (item.type) { case "d": type = "directory"; break; case "-": type = "file"; break; case "l": type = item.destType; break; default: type = "block"; break; } var param = { class: "treeview-" + type, type: type, text: item.name, size: item.size, mode: item.rights.user === null ? "": item.rights.user, date: item.date, depth: depth, index: index, target: item.target, destType: item.destType, id: parent.id + "-" + index, parent: parent }; promises.push(_setEntity(param, index)); }); Async.waitForAll(promises, false, 5000) .then(function () { return _setElement(parent); }) .then(function () { var $parent = _getElementWithEntity(parent); $parent.addClass("loaded"); deferred.resolve(); }) .fail(deferred.reject); return deferred.promise(); }; refresh = function () { var deferred = new $.Deferred(); if (_ctxMenuCurrentEntity === null) { return; } $("#tv-" + _ctxMenuCurrentEntity.id + " > ul.treeview-contents").remove(); _loadDirectory(_ctxMenuCurrentEntity) .then(function () { deferred.resolve(); }, function (err) { deferred.reject(err); }); return deferred.promise(); }; rename = function () { var deferred = new $.Deferred(); if (_ctxMenuCurrentEntity === null) { return deferred.reject().promise(); } var oldLocalPath = PathManager.completionLocalPath(getPathArray(_ctxMenuCurrentEntity)); var oldRemotePath = PathManager.completionRemotePath(_currentServerSetting, getPathArray(_ctxMenuCurrentEntity)); var entry = null; if (_ctxMenuCurrentEntity.type === "file") { entry = FileSystem.getFileForPath(oldLocalPath); } else if (_ctxMenuCurrentEntity.type === "directory") { entry = FileSystem.getDirectoryForPath(oldLocalPath); } _rename(_ctxMenuCurrentEntity, function (entity) { var newLocalPath = PathManager.completionLocalPath(getPathArray(entity)); var newRemotePath = PathManager.completionRemotePath(_currentServerSetting, getPathArray(entity)); if (entity.type === "directory") { oldLocalPath += "/"; newLocalPath += "/"; } if (entity) { if (newLocalPath === oldLocalPath) { return deferred.resolve().promise(); } else { RemoteManager.rename(_currentServerSetting, oldRemotePath, newRemotePath) .then(function (res) { return Project.renameLocalEntry(oldLocalPath, newLocalPath, entity.type); }, function (err) { deferred.reject(err); }) .then(deferred.resolve, deferred.reject); } } else { deferred.reject(); } }); return deferred.promise(); }; removeFile = function () { var deferred = new $.Deferred(); if (_ctxMenuCurrentEntity === null) { return deferred.reject().promise(); } if (_ctxMenuCurrentEntity.type === "file") { deleteFile() .then(deferred.resolve, deferred.reject); } else { removeDirectory() .then(deferred.resolve, deferred.reject); } return deferred.promise(); }; removeDirectory = function () { var deferred = new $.Deferred(); if (_ctxMenuCurrentEntity === null) { return deferred.reject().promise(); } var remotePath = PathManager.completionRemotePath(_currentServerSetting, getPathArray(_ctxMenuCurrentEntity)); DialogCollection.showYesNoModal( "removeDirectoryDialog", "Confirm", "Are you sure you want to delete the selected directory and all child contents ?") .done(function (res) { if (res === "Yes") { RemoteManager.removeDirectory(_currentServerSetting, remotePath) .then(function (res) { if (res) { if (_ctxMenuCurrentEntity.downloaded) { _localEntryActualDelete(_ctxMenuCurrentEntity); } _deleteEntity(_ctxMenuCurrentEntity); } }, function (err) { deferred.reject(err); }); } else { deferred.resolve(); } }); return deferred.promise(); }; newDirectory = function () { var deferred = new $.Deferred(); if (_ctxMenuCurrentEntity === null) { return deferred.reject().promise(); } if (_ctxMenuCurrentEntity.type === "directory" || _ctxMenuCurrentEntity.type === "ldirectory") { if (!_getElementWithEntity(_ctxMenuCurrentEntity).hasClass("loaded")) { _loadDirectory(_ctxMenuCurrentEntity) .then(function () { newDirectory(); return; }, function () { // TODO: ファイル一覧の取得に失敗しました。 deferred.reject(); }); } else { _newFile("directory") .then(deferred.resolve, deferred.reject); } } else { deferred.resolve(); } return deferred.promise(); }; newFile = function () { var deferred = new $.Deferred(); if (_ctxMenuCurrentEntity === null || (_ctxMenuCurrentEntity.type !== "directory" && _ctxMenuCurrentEntity.type !== "ldirectory")) { // TODO: 選択されたカレントディレクトリでファイルの作成はできません。 deferred.reject(); return deferred.promise(); } var $elem = _getElementWithEntity(_ctxMenuCurrentEntity); if (_ctxMenuCurrentEntity.type === "directory" || _ctxMenuCurrentEntity.type === "ldirectory") { if (!$elem.hasClass("loaded")) { _loadDirectory(_ctxMenuCurrentEntity) .then(function () { newFile(); return; }, function (err) { // ファイル一覧の取得に失敗しました。 deferred.reject(err); }); } else { _newFile("file") .then(deferred.resolve, function (err) { // TODO: ファイルの作成に失敗しました。 deferred.reject(); }); } } else { deferred.resolve(); } return deferred.promise(); }; deleteFile = function () { var deferred = new $.Deferred(); var remotePath = PathManager.completionRemotePath(_currentServerSetting, getPathArray(_ctxMenuCurrentEntity)); if (_ctxMenuCurrentEntity === null) { return deferred.reject().promise(); } DialogCollection.showYesNoModal( "deleteFileDialog", "Confirm", "Are you sure you want to delete the selected file ?") .done(function (res) { if (res === "Yes") { RemoteManager.deleteFile(_currentServerSetting, remotePath) .then(function () { if (_ctxMenuCurrentEntity.downloaded) { _localEntryActualDelete(_ctxMenuCurrentEntity); } _deleteEntity(_ctxMenuCurrentEntity); //var f = FileSystem.getFileForPath() deferred.resolve(); }, function (err) { // TODO: showAlert is deprecated instead Log.q // TODO: サーバファイルの削除に失敗しました。 deferred.reject(err); }); } else { deferred.resolve(); } }); return deferred.promise(); }; _localEntryActualDelete = function (entity) { var d = new $.Deferred(); if (_currentServerSetting) { var absPath = PathManager.completionLocalPath(getPathArray(entity)), file = entity.type !== "directory" ? FileSystem.getFileForPath(absPath) : FileSystem.getDirectoryForPath(absPath), fullPath = file.fullPath, type = file.type; ProjectManager.deleteItem(file) .then(function () { Log.q("The " + type + " was deleted successfully (" + fullPath + ")"); d.resolve(); }, function (err) { Log.q("Failed to delete to local " + type + " (" + fullPath + ")", true, err); d.reject(err); }); } else { Log.q("Unexpected function calling", true); d.reject(); } return d.promise(); }; getEntityWithPath = function (localPath) { var split = localPath.split("/"), children = rootEntity.children, entity = null; split.forEach(function (f) { _.forEach(children, function (ent) { if (ent.text === f) { entity = ent; } }); if (entity.type !== "file" && entity.type !== "symlink") { children = entity.children; } }); return entity; }; /** * Create UI element from Entity. * * @param {object} the entity object. * @return {$.Promise} a promise will be resolved when create element, that never rejected. */ _setElement = function (entity) { var d = new $.Deferred(), $parent = null; if (entity === null) { $parent = $("#synapse-tree").addClass("quiet-scrollbars"); } else { $parent = _getElementWithEntity(entity); } if ($parent === null || $parent === undefined || typeof ($parent) === "undefined") { return d.reject(new Error("Unexpected Exception. could not found the element")).promise(); } $parent.find("ul.treeview-contents").remove(); var $ul = $("
        ").addClass("treeview-contents"); $parent.append($ul); if (entity === null) { $ul.show(); _makeRowElement(rootEntity, $("#synapse-tree"), $ul); if ($parent.hasClass("treeview-close")) { _toggleDir(rootEntity); } else { $ul.css({"display": "block"}); } d.resolve(); } else { _.forEach(entity.children, function (ent) { _makeRowElement(ent, $parent, $ul); }); if ($parent.hasClass("treeview-close")) { _toggleDir(entity); } else { $ul.css({"display": "block"}); } d.resolve(); } return d.promise(); }; /** * Create Entity object with parameter. * * @param {object} the entity object for the synapse. * @return {$.Promise} a promise that will be resolved if the entity created, that never rejected. */ _setEntity = function (param) { var deferred = new $.Deferred(); var entity = new Entity(param); if (entity.parent !== null) { entity.parent.children[entity.index] = entity; } return deferred.resolve(entity).promise(); }; _attachEvent = function () { j.container.on("click", onClick); }; _detachEvent = function () { j.container.off("click", onClick); }; _checkPrimitive = function (param) { var toStr = Object.prototype.toString; var res = toStr.call(param); return res.replace(/\[|\]/g, "").split(" ")[1]; }; _getProjectDirectoryPath = function () { return _modulePath + PROJECT_DIR; }; getPathArray = function (entity) { var target = entity; var entities = []; while (target.parent !== null) { entities.unshift(target.text); target = target.parent; } return entities; }; _getEntityWithElement = function ($elem) { var id = $elem.attr("id"); return _getEntityWithId(id); }; _getEntityWithId = function (id) { if (id === "tv-0") { return rootEntity; } else if (id === "synapse-tree") { return null; } var index = id.split("-"); if (index[0] === "tv") { index = index.slice(1); } index = index.slice(1); var depth = index.length; var children = rootEntity.children; var i = 0; var entity = null; for (; i < depth; i++) { entity = children[index[i]]; children = entity.children; } return entity; }; _getElementWithEntity = function (entity) { return $("#tv-" + entity.id, j.container); }; _makeRowElement = function (entity, $parent, $ul) { var deferred = new $.Deferred(); var $li = $("
      • ").addClass("treeview-entity").addClass(entity.class).attr({ "id": "tv-" + entity.id }); var $p = $("

        ").addClass("treeview-row"); var $text = $("").addClass("filename").html(entity.text); var $icon = $(""); if (entity.type === "directory") { $li.addClass("treeview-close"); $icon.addClass(Icon.folder); } else if (entity.type === "ldirectory") { $li.addClass("treeview-close"); $icon.addClass(Icon.lFolder); } else if (entity.type === "file") { $icon.addClass(Icon.file); } else if (entity.type === "lfile") { $icon.addClass(Icon.lFile); } else if (entity.type === "block") { $icon.addClass(Icon.block); $li.addClass("treeview-block"); } $p.append($icon) .append($text); $li.append($p); $ul.append($li); var paddingLeft = offset_left * entity.depth; $p.css({ "padding-left": paddingLeft + "px" }); return deferred.resolve($ul).promise(); }; _toggleDir = function (entity) { var $jqElem = _getElementWithEntity(entity); var $icon = $("#tv-" + entity.id + " > p.treeview-row > i.fa"); var $ul = $("#tv-" + entity.id + " > ul.treeview-contents"); if ($ul.is(":hidden")) { if (entity.type === "directory") { $icon.addClass("fa-folder-open"); $icon.removeClass("fa-folder"); } else if (entity.type === "ldirectory") { $icon.addClass("fa-folder-open-o"); $icon.removeClass("fa-folder-o"); } $jqElem.removeClass("treeview-close"); $jqElem.addClass("treeview-open"); } else if ($ul.is(":visible")) { if (entity.type === "directory") { $icon.removeClass("fa-folder-open"); $icon.addClass("fa-folder"); } else if (entity.type === "ldirectory") { $icon.removeClass("fa-folder-open-o"); $icon.addClass("fa-folder-o"); } $jqElem.addClass("treeview-close"); $jqElem.removeClass("treeview-open"); } $ul.animate({ "height": "toggle" }, "fast"); }; _loadDirectory = function (entity) { var deferred = new $.Deferred(); var path = ""; if (entity.type === "ldirectory") { path = entity.target; } else { path = PathManager.completionRemotePath(_currentServerSetting, getPathArray(entity)); } RemoteManager.getList(entity, _currentServerSetting, path) .then(function (list) { return setEntities(list, entity); }) .then(deferred.resolve, deferred.reject); return deferred.promise(); }; _rename = function (entity, cb) { var $input = null; var showInput = function (entity) { var deferred = new $.Deferred(); var $parent = _getElementWithEntity(entity.parent); var $current = _getElementWithEntity(entity); var $span = $("p.treeview-row > span", $current).first(); var $input = $("").attr({ type: "text", "id": "synapse-treeview-rename-editor" }).val(entity.text); $("p.treeview-row", $current).first().append($input); $span.hide(); return deferred.resolve().promise(); }; var validate = function (entity, cb) { var $current = _getElementWithEntity(entity); var _$input = $("input", $current).focus().select(); var parent = entity.parent; var $parent = _getElementWithEntity(entity.parent); var $span = $("p.treeview-row > span", $current).first(); _$input.focus().select(); _$input.on("keypress.synapse", function (e) { if (e.which === 13) { _$input.off("keypress.synapse"); _$input.blur(); } }); var exists = false; _$input.one("blur", { cb: cb }, function () { _.forEach(parent.children, function (ent, key) { if ((ent.id !== entity.id) && (ent.text === _$input.val())) { exists = true; } }); if (exists) { validate(entity, cb); } else { $span.show().html(_$input.val()); entity.text = _$input.val(); _$input.off("keypress.synapse"); _$input.remove(); cb(entity); } }); }; showInput(entity) .then(function () { validate(entity, cb); }); }; _newFile = function (type) { var deferred = new $.Deferred(); if (_ctxMenuCurrentEntity === null) { return deferred.reject().promise(); } var parent = _ctxMenuCurrentEntity; var $elem = _getElementWithEntity(_ctxMenuCurrentEntity); var cnt = 0; _.forEach(parent.children, function (ent, key) { if (type === "file") { if (ent.text.match(/^New File(\([0-9]+?\))?$/)) { cnt++; } } else if (type === "directory") { if (ent.text.match(/^New Directory(\([0-9]+?\))?$/)) { cnt++; } } }); var newName = ""; if (type === "file") { newName = (cnt === 0) ? "New File" : "New File(" + cnt + ")"; } else if (type === "directory") { newName = (cnt === 0) ? "New Directory" : "New Directory(" + cnt + ")"; } var depth = parent.depth + 1; var index = Object.keys(parent.children).length; var newEntity = null; var param = { class: "treeview-" + type, type: type, text: newName, size: 0, mode: "", date: "", depth: depth, index: index, id: parent.id + "-" + index, parent: parent }; _setEntity(param) .then(function (entity) { newEntity = entity; return _setElement(entity.parent); }) .then(function () { if (type === "file") { _rename(newEntity, function (ent) { var localPath = _modulePath + "empty.txt"; var remotePath = PathManager.completionRemotePath(_currentServerSetting, getPathArray(ent)); RemoteManager.uploadFile(_currentServerSetting, localPath, remotePath) .then(function () { deferred.resolve(); }, function (err) { _deleteEntity(ent); deferred.reject(); }); }); } else if (type === "directory") { _rename(newEntity, function (ent) { var remotePath = PathManager.completionRemotePath(_currentServerSetting, getPathArray(ent)); RemoteManager.mkdir(_currentServerSetting, remotePath) .then(function () { return Project.createDirectoryIfExists(PathManager.completionLocalPath(getPathArray(ent))); }, function (err) { _deleteEntity(ent); deferred.reject(); }); }); } }, function (err) { throw new Error(err); }); return deferred.promise(); }; _deleteEntity = function (entity) { var deferred = new $.Deferred(); var $elem = _getElementWithEntity(entity); var parent = entity.parent; delete parent.children[entity.index]; _rebuildChildrenIndex(parent) .then(_resetElement) .then(deferred.resolve, deferred.reject); return deferred.promise(); }; _rebuildChildrenIndex = function (parent) { var deferred = new $.Deferred(); var entities = parent.children; var tmp = {}; var idx = 0; _.forEach(entities, function (ent, key) { ent.index = idx; ent.id = ent.parent.id + "-" + idx; tmp[idx] = ent; idx++; }); parent.children = tmp; return deferred.resolve(parent).promise(); }; _resetElement = function (parent) { return _setElement(parent); }; _makeBaseDirectoryIfIsNotExists = function (localPath) { var deferred = new $.Deferred(), baseDirPath = FileUtils.getDirectoryPath(localPath), baseDir = FileSystem.getDirectoryForPath(baseDirPath); baseDir.exists(function (err, exists) { if (err) { deferred.reject(err); } else { if (!exists) { baseDir.create(function (err, res) { if (!err) { deferred.resolve(baseDir); } else { deferred.reject(err); } }); } else { deferred.resolve(baseDir); } } }); return deferred.promise(); }; _openFile = function (entity) { var deferred = new $.Deferred(); var remotePath = ""; var localPath = ""; if (entity.type === "file") { remotePath = PathManager.completionRemotePath(_currentServerSetting, getPathArray(entity)); } else if (entity.type === "lfile") { remotePath = entity.target; } localPath = PathManager.completionLocalPath(getPathArray(entity)); deferred.resolve(); if (!entity.downloaded) { _makeBaseDirectoryIfIsNotExists(localPath) .then(function (baseDir) { RemoteManager.download(_currentServerSetting, localPath, remotePath) .then(function () { entity.downloaded = true; FileManager.openFile(localPath); deferred.resolve(); }); }, function(err) { throw new Error(err); }); } else { FileManager.openFile(localPath); } return deferred.promise(); }; onTreeViewContextMenu = function (e, menu) { if ($("#synapse-tree").hasClass("disabled")) { return; } menu.close(); var $elem = $(e.target); var tag = $elem.prop("tagName"); if (tag === "DIV") { if ($("#treeview-root").length) { $elem = _getElementWithEntity(rootEntity); } else { $elem = null; } } else if (tag === "P") { if ($elem.hasClass("treeview-row")) { if ($elem.parent().hasClass("treeview-entity")) { $elem = $elem.parent(); } } } else if ((tag === "SPAN" && $elem.hasClass("filename")) || (tag === "I" && $elem.hasClass("fa"))) { if ($elem.parent().parent().hasClass("treeview-entity")) { $elem = $elem.parent().parent(); } } else { return; } if ($elem === null) { return; } var entity = _getEntityWithId($elem.attr("id")); Menu.treeViewContextMenuState(entity); _ctxMenuCurrentEntity = _getEntityWithId($elem.attr("id")); menu.open(e); }; onClick = function (e) { var $elem = $(e.target); if ($elem.hasClass("treeview-contents") || $elem.hasClass("filename") || $elem.hasClass("fa")) { $elem = $elem.parent().parent(); } else if ($elem.hasClass("treeview-row")) { $elem = $elem.parent(); } if ($elem.hasClass("treeview-directory") || $elem.hasClass("treeview-ldirectory") || $elem.hasClass("treeview-root")) { onDirClicked($elem); } if ($elem.hasClass("treeview-file") || $elem.hasClass("treeview-lfile")) { onFileClicked($elem); } }; onFileClicked = function ($elem) { var entity = _getEntityWithElement($elem); _openFile(entity); }; onDirClicked = function ($elem) { var id = $elem.attr("id"); var entity = _getEntityWithId(id); var localPath = PathManager.completionLocalPath(getPathArray(entity)); _makeBaseDirectoryIfIsNotExists(localPath); if ($elem.hasClass("loaded")) { _toggleDir(entity); } else { _loadDirectory(entity) .then(function () { // success entity.downloaded = true; }, function (err) { throw new Error(err); }); } }; onProjectStateChanged = function (e, obj) { if (obj.state === Project.OPEN) { _projectDir = obj.directory; } else if (obj.state === Project.CLOSE) { } }; updateTreeviewContainerSize = function (isAnim) { isAnim = isAnim || false; var top = j.tvc.css("top"); if (j.l.is(":visible")) { top = j.h.outerHeight() + j.l.outerHeight() + 10; } if (j.s.is(":visible")) { top = j.h.outerHeight() + j.s.outerHeight() + 10; } if (isAnim) { return j.tvc.animate({"top": top + "px", bottom: 0}, "fast").promise(); } else { j.tvc.css({"top": top + "px", bottom: 0}); return new $.Deferred().resolve().promise(); } }; exports.init = init; exports.setEntities = setEntities; exports.rootEntity = rootEntity; exports.open = open; exports.loadTreeView = loadTreeView; exports.refresh = refresh; exports.rename = rename; exports.removeFile = removeFile; exports.getPathArray = getPathArray; exports.newFile = newFile; exports.getEntityWithPath = getEntityWithPath; exports.deleteFile = deleteFile; exports.newDirectory = newDirectory; exports.removeDirectory = removeDirectory; exports.onTreeViewContextMenu = onTreeViewContextMenu; exports.clearCurrentTree = clearCurrentTree; exports.updateTreeviewContainerSize = updateTreeviewContainerSize; exports.getModuleName = function () { return module.id; }; }); trace-production/tests/tracing/SJS-map-object-literals.js var obj = {p1: 'foo'}; var map = {p2: 'foo'};0 import * as APIUTIL from '../util/session_api_util'; import { fetchNotebooks, createNotebook, setCurrentNotebook } from './notebook_actions'; import { fetchNotes } from "./notes_actions"; import { fetchTags } from "./tag_actions"; export const RECEIVE_CURRENT_USER = "RECEIVE_CURRENT_USER"; export const RECEIVE_ERRORS = "RECEIVE_ERRORS"; export const CLEAR_ERRORS = "CLEAR_ERRORS"; export const login = user => dispatch => ( APIUTIL.login(user) .then(usr => dispatch(receiveCurrentUser(usr)), err => dispatch(receiveErrors(err.responseJSON))) .then(() => dispatch(fetchNotes())) .then(() => dispatch(fetchNotebooks())) .then(() => dispatch(fetchTags())) ); export const logout = () => dispatch => ( APIUTIL.logout() .then(() => dispatch(receiveCurrentUser(null)), err => dispatch(receiveErrors(err))) ); export const signup = user => dispatch => ( APIUTIL.signup(user) .then(usr => dispatch(receiveCurrentUser(usr)), err => dispatch(receiveErrors(err.responseJSON))) .then(usr => dispatch(createNotebook({ title: usr.currentUser.username }))) .then(() => dispatch(setCurrentNotebook(null))) ); export const receiveCurrentUser = currentUser => ({ type: RECEIVE_CURRENT_USER, currentUser }); export const receiveErrors = errors => ({ type: RECEIVE_ERRORS, errors }); export const clearErrors = () => ({ type: CLEAR_ERRORS }); import React, {Component} from 'react'; import {Avatar, Paper, Typography, withStyles, TextField, IconButton, Icon} from '@material-ui/core'; import {FuseScrollbars} from '@fuse'; import classNames from 'classnames'; import moment from 'moment/moment'; import * as Actions from './store/actions'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import _ from '@lodash'; const styles = theme => ({ messageRow : { position : 'relative', display : 'flex', flexDirection : 'column', alignItems : 'flex-start', justifyContent : 'flex-end', padding : '0 16px 4px 16px', flex : '0 0 auto', '&.contact' : { '& $bubble' : { backgroundColor : theme.palette.primary.main, color : theme.palette.primary.contrastText, borderTopLeftRadius : 5, borderBottomLeftRadius : 5, borderTopRightRadius : 20, borderBottomRightRadius: 20, '& $time' : { marginLeft: 12 } }, '&.first-of-group': { '& $bubble': { borderTopLeftRadius: 20 } }, '&.last-of-group' : { '& $bubble': { borderBottomLeftRadius: 20 } } }, '&.me' : { paddingLeft: 40, '& $avatar': { order : 2, margin: '0 0 0 16px' }, '& $bubble' : { marginLeft : 'auto', backgroundColor : theme.palette.grey[300], color : theme.palette.getContrastText(theme.palette.grey[300]), borderTopLeftRadius : 20, borderBottomLeftRadius : 20, borderTopRightRadius : 5, borderBottomRightRadius: 5, '& $time' : { justifyContent: 'flex-end', right : 0, marginRight : 12 } }, '&.first-of-group': { '& $bubble': { borderTopRightRadius: 20 } }, '&.last-of-group': { '& $bubble': { borderBottomRightRadius: 20 } } }, '&.contact + .me, &.me + .contact': { paddingTop: 20, marginTop : 20 }, '&.first-of-group' : { '& $bubble': { borderTopLeftRadius: 20, paddingTop : 13 } }, '&.last-of-group' : { '& $bubble': { borderBottomLeftRadius: 20, paddingBottom : 13, '& $time' : { display: 'flex' } } } }, avatar : { position: 'absolute', left : -32, margin : 0 }, bubble : { position : 'relative', display : 'flex', alignItems : 'center', justifyContent: 'center', padding : 12, maxWidth : '100%' }, message : { whiteSpace: 'pre-wrap', lineHeight: 1.2 }, time : { position : 'absolute', display : 'none', width : '100%', fontSize : 11, marginTop : 8, top : '100%', left : 0, whiteSpace: 'nowrap' }, bottom : { background: theme.palette.background.default, borderTop : '1px solid rgba(0, 0, 0, 0.13)' }, inputWrapper: { borderRadius: 24 } }); class Chat extends Component { state = { messageText: '' }; componentDidUpdate(prevProps) { if ( this.props.chat && !_.isEqual(prevProps.chat, this.props.chat) ) { this.scrollToBottom(); } } shouldShowContactAvatar = (item, i) => { return ( item.who === this.props.selectedContactId && ((this.props.chat.dialog[i + 1] && this.props.chat.dialog[i + 1].who !== this.props.selectedContactId) || !this.props.chat.dialog[i + 1]) ); }; isFirstMessageOfGroup = (item, i) => { return (i === 0 || (this.props.chat.dialog[i - 1] && this.props.chat.dialog[i - 1].who !== item.who)); }; isLastMessageOfGroup = (item, i) => { return (i === this.props.chat.dialog.length - 1 || (this.props.chat.dialog[i + 1] && this.props.chat.dialog[i + 1].who !== item.who)); }; onInputChange = (ev) => { this.setState({messageText: ev.target.value}); }; onMessageSubmit = (ev) => { ev.preventDefault(); if ( this.state.messageText === '' ) { return; } this.props.sendMessage(this.state.messageText, this.props.chat.id, this.props.user.id) .then(() => { this.setState({messageText: ''}); this.scrollToBottom(); }); }; scrollToBottom = () => { this.chatScroll.scrollTop = this.chatScroll.scrollHeight; }; render() { const {classes, chat, contacts, user, className} = this.props; const {messageText} = this.state; return ( { this.chatScroll = ref }} className="flex flex-1 flex-col overflow-y-auto" > {!chat ? (

        chat Select a contact to start a conversation.
        ) : chat.dialog.length > 0 ? (
        {chat.dialog.map((item, i) => { const contact = item.who === user.id ? user : contacts.find(_contact => _contact.id === item.who); return (
        {this.shouldShowContactAvatar(item, i) && ( )}
        {item.message}
        {moment(item.time).format('MMMM Do YYYY, h:mm:ss a')}
        ) })}
        ) : (
        chat
        Start a conversation by typing your message below.
        ) } {chat && (
        send )} ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ sendMessage: Actions.sendMessage }, dispatch); } function mapStateToProps({chatPanel}) { return { contacts : chatPanel.contacts.entities, selectedContactId: chatPanel.contacts.selectedContactId, chat : chatPanel.chat, user : chatPanel.user } } export default withStyles(styles)(connect(mapStateToProps, mapDispatchToProps)(Chat)); const RecordFetcher = require('../src/RecordFetcher'); const ErrorCodes = require('../src/ErrorCodes'); test('Bad request data', async () => { const mockDbAccess = { findMatchingRecords: jest.fn() } const recordFetcher = new RecordFetcher({ dbAccess: mockDbAccess }); const wrongSchema = { 'startDate': 3000 }; const result = await recordFetcher.getRecords(wrongSchema); expect(result).toEqual({ error: ErrorCodes.BAD_REQUEST, records: undefined }); }); test('Bad DB access', async () => { const mockDbAccess = { findMatchingRecords: async () => { throw new Error('Mock Error') } } const recordFetcher = new RecordFetcher({ dbAccess: mockDbAccess }); const correctSchema = { "startDate": "2016-01-26", "endDate": "2018-02-02", "minCount": 2700, "maxCount": 3000 }; const result = await recordFetcher.getRecords(correctSchema); expect(result).toEqual({ error: ErrorCodes.DB_ERROR, records: undefined }); }); test('Success case', async () => { const mockDbAccess = { findMatchingRecords: async () => { return ['test1', 'test2'] } } const recordFetcher = new RecordFetcher({ dbAccess: mockDbAccess }); const correctSchema = { "startDate": "2016-01-26", "endDate": "2018-02-02", "minCount": 2700, "maxCount": 3000 }; const result = await recordFetcher.getRecords(correctSchema); expect(result).toEqual({ error: ErrorCodes.NO_ERROR, records: ['test1', 'test2'] }); }); App/SB/components/Input/statics/styles.js import { StyleSheet } from 'react-native' export default StyleSheet.create({ errorMsg: { fontFamily: 'Biotif-Regular', fontSize: 12, color: '#D0021B', paddingTop: 6 }, labelText: { position: 'absolute', left: 0, backgroundColor: 'rgba(0,0,0,0)' }, underlineWrapper: { height: 1, alignItems: 'center' }, wrapper: { height: 72, paddingTop: 30, paddingBottom: 7, position: 'relative', width: '100%' }, denseWrapper: { height: 60, paddingTop: 28, paddingBottom: 4, position: 'relative' }, textInput: { fontFamily: 'Biotif-Regular', fontSize: 16, marginBottom: 8, marginTop: 10, color: '#6d6d6d' } }) cultures/fa.js var jalali = require('./calendars/jalali'); function Culture() { } Culture.prototype.monthNames = function(date) { return ['Farvardin', 'Ordibehesht', 'Khordad', 'Tir', 'Mordad', 'Shahrivar', 'Mehr', 'Aban', 'Azar', 'Dey', 'Bahman', 'Esfand']; }; Culture.prototype.shortMonthNames = function(date) { return ['Far', 'Ord', 'Kho', 'Tir', 'Mor', 'Sha', 'Meh', 'Aba', 'Aza', 'Dey', 'Bah', 'Esf']; }; Culture.prototype.fromGregorian = function(date) { return jalali.gregorian_to_jalali(date); }; Culture.prototype.toGregorian = function(date) { return jalali.jalali_to_gregorian(date); }; module.exports = Culture;import 'babel-polyfill'; import http from 'http'; import express from 'express'; import logger from 'morgan'; import { messageSignatureService } from "./services/message-signature-service"; import { requestValidationService } from "./services/request-validation-service"; import { starService } from "./services/star-registration-service"; import { FORBIDDEN } from "./error"; /** * Init Express Config */ const app = express(); const server = http.createServer(app); const port = process.env.PORT || 8000; app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.set('port', port); server.listen(port); /** * Request Validation Routes */ app.post('/requestValidation', async (req, res) => { const requestValidation = await requestValidationService.getRequestValidation(req.body.address, true); res.json(requestValidation); }); /** * Message Signature Routes */ app.post('/message-signature/validate', async (req, res) => { try { const messageSignatureResponse = await messageSignatureService.validateSignature(req.body.address, req.body.signature); res.json(messageSignatureResponse); } catch (e) { const error = { error: e.message }; if(e.message === FORBIDDEN) { res.status(403).json(error); } else { res.status(500).json(error) } } }); /** * Block Routes */ const block_api = '/block'; app.get(block_api + '/:height', async (req, res) => { try { const block = await starService.getBlockByHeight(req.params.height); return block ? res.json(block) : res.status(404).json({ error : 'not found'}); } catch (e) { res.status(500).json(e.message); } }); app.post(block_api, async (req, res) => { try { const block = await starService.registerStar(req.body); res.json(block); } catch (e) { const error = { error: e.message }; if (e.message === FORBIDDEN) { res.status(403).json(error); } else if (e.message === FORBIDDEN) { res.status(400).json(error); } else { res.status(500).json(error) } } }); /** * Star Routes */ const star_api = '/star'; app.get(star_api + '/address:address', async (req, res) => { try { const block = await starService.getBlocksByAddress(req.params.address.substring(1)); res.json(block); } catch (e) { res.status(500).json({ error : e.message}); } }); app.get(star_api + '/hash:hash', async (req, res) => { try { const block = await starService.getBlockByHash(req.params.hash.substring(1)); return block ? res.json(block) : res.status(404).json({ error : 'not found'}); } catch (e) { res.status(500).json(e.message); } }); /** * Event listener for HTTP server "error" event. */ const onError = (error) => { if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } }; /** * Event listener for HTTP server "listening" event. */ const onListening = () => { const addr = server.address(); const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; console.log(`Started on port ${bind}`); }; server.on('error', onError); server.on('listening', onListening);1-10 #!/usr/local/bin/node --harmony "use strict" const colors = require('colors'); colors.setTheme({ cmd: ['gray', 'bold', 'italic'], warn: ['yellow', 'underline'], err: ['red', 'underline'], suc: ['green', 'underline', 'bold', 'italic'] }); if (process.argv.length < 3 || (process.argv.length == 3 && (process.argv[2] == 'help' || process.argv[2] == '--help' || process.argv[2] == '-h'))) { let caption = "\nMy name is " + "Memory".rainbow + " but friends calls me MEM, and i'm \n" + "application which will help you to memorize all the commands, \n" + "or just create an aliases for this commands, or just call it \n" + "shortcuts it is doesn't metter, the only one thing that metter \n" + "is you should not have to remember all this list, because i will\n" + "do it instead :)\n\n"; console.log(caption.white.bold); console.log("Commands which i support are:\n".warn + "remind|r [cmd_name]".cmd + " - and i will remind you the command which you ask me to remember\n" + "forget|rm [cmd_name]".cmd + " - and i will forget command which i remembered before\n" + "run [cmd_name]|[cmd_name]".cmd + " - and i will run the command for you\n" + "save|s".cmd + " - and i will remember the command for you\n" + "list|l [names]".cmd + "- and i will show you everything i remember, " + "\nif `names` then i will print only names\n\n" + "Usage:\n".warn + "mem save".cmd + " - will open interactive dialog to save command 'ps axu' to the memory and to add an alias\n" + "mem l names".cmd + " - will show the names for all memorized commands\n" + "mem rm my super command".cmd + " - will remove from memory command with name 'my super command'\n" + "mem run ls".cmd + " or " + "mem ls" + " - will run previously saved ls command\n\n" + "Now you know!".white); process.exit(0); } const action = process.argv[2]; const argvs = process.argv.splice(3, Number.MAX_VALUE); const fs = require('fs'); const actions = ['remind', 'r', 'forget', 'rm', 'run', 'list', 'l', 'save', 's']; const longActons = ['remind', 'forget', 'run', 'list', 'save']; const readline = require('readline'); const didYouMean = require('didyoumean2'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); let content; const dbFile = "memorized.commands.json"; const dbDir = process.env.HOME + "/.memdata"; const dbPath = dbDir + '/' + dbFile; const findSame = (find, where) => { if (!where) { where = 'cmd'; } for (let item in content) { if (content[item][where] === find) { return content[item]; } } return false; }; const getAllKeys = (key) => { let items = []; for (let item in content) { items.push(content[item][key]); } return items; }; const saveContent = (content) => { fs.writeFileSync(dbPath, JSON.stringify(content), {encoding: 'utf8', mode: '0600', flag: 'w+'}); }; const checkIsNameExistsInDb = (name) => { for (let item in content) { if (content[item].name == name) { return content[item]; } } return false; }; const printItem = (item) => { console.log(item.name.warn + "\n >> " + item.cmd.cmd + "\n\n"); }; const actionRun = (argvs) => { if (!argvs.length) { console.log('cmd_name not defined'.err); process.exit(0); } let cmdName = argvs.join(' ').trim(), item = findSame(cmdName, 'name'); if (!item) { let simillarItems = didYouMean(cmdName, getAllKeys('name'), {'returnType': 'all-matches'}); if (simillarItems.length) { console.log("Did you mean: " + simillarItems.join(" or ").cmd + " ?"); } else { console.log("[".err + cmdName.cmd + "] not found".err); } process.exit(0); } else { console.log(item.cmd.cmd, "\n"); let exec = require('child_process').exec; console.log("RUN:\n".rainbow) let proc = exec(item.cmd, (error, stdout, stderr) => { if (error) { console.log("ERROR >>", error); } process.exit(0); }); proc.stdout.on('data', function(data) { console.log(data.green); }); proc.stderr.on('data', function(data) { console.log(data.err); }); } }; if (!fs.existsSync(dbDir)){ fs.mkdirSync(dbDir, '0700'); } if (fs.existsSync(dbPath)) { content = require(dbPath); } else { content = []; } if (action === '_commands-shortlist') { console.log(longActons.join(' ') + getAllKeys('name').join(' ')); process.exit(0); } if (action === '_list-shortlist') { console.log(getAllKeys('name').join(" ")); process.exit(0); } if (action === 'save' || action === 's') { let command = action + " " + argvs.join(' '); rl.question('Insert command:\n>>', (command) => { let sameItem = findSame(command); if (sameItem) { console.log("Already stored item:\n".warn); printItem(sameItem); process.exit(1); } const nameTheCommand = () => { rl.question('Name your command:\n>>', (cmdName) => { let name = cmdName.trim().split(' ').join('-'); if (name.length < 1) { console.log("Command name couldn't be empty".err); return nameTheCommand(); } if (actions.indexOf(name) !== -1) { console.log("Already reserved word [" + actions.join(',') + "], please " + "use another name for command".err); return nameTheCommand(); } let item = checkIsNameExistsInDb(name); if (item) { console.log("Command already exists".warn, item.cmd.cmd); return nameTheCommand(); } content.push({'name': name, 'cmd': command}); saveContent(content); console.log("Command stored to memory:\n".suc, command.cmd); rl.close(); }); }; nameTheCommand(); }); } else { if (content.length < 1) { console.log("Memory is clean! Please add something first .. :) "); process.exit(0); } if (action === 'remind' || action === 'r') { if (!argvs.length) { console.log('cmd_name not defined'.err); process.exit(0); } let cmdName = argvs.join(' ').trim(), item = findSame(cmdName, 'name'); if (!item) { let simillarItems = didYouMean(cmdName, getAllKeys('name'), {'returnType': 'all-matches'}); if (simillarItems.length) { console.log("Did you mean: " + simillarItems.join(" or ").cmd + " ?"); } else { console.log("Sorry but command not found".err); } } else { printItem(item); } process.exit(0); } else if (action === 'list'|| action == 'l') { let cond = argvs.join(' ').trim(); console.log("Here are what we have:"); content.forEach((item) => { if (cond === 'names' || cond === 'name') { console.log(item.name.warn); } else { printItem(item); } }); process.exit(0); } else if (action === 'forget' || action == 'rm') { if (!argvs.length) { console.log('cmd_name not defined'.err); process.exit(0); } let forgotten, cmdName = argvs.join(' ').trim(); for (let item in content) { if (content[item].name === cmdName) { forgotten = content[item]; content.splice(item, 1); console.log break; } } if (forgotten) { saveContent(content); console.log(("Item " + forgotten.name + " where forgot \n").suc, "Command was:\n", forgotten.cmd.cmd); } process.exit(0); } else if (action === 'run') { actionRun(argvs); } else { argvs.unshift(action); actionRun(argvs); } } const { oneOf } = require('../../../helpers/payload-or-null') module.exports = { oneOf: [ { type: 'null' }, { type: 'array', items: { type: 'object', properties: { id: { type: 'string', format: 'uuid', description: 'The Tillhub scan prefix resource reference ID.', example: '43847a66-97dc-4ac2-8e8a-c44920e1f22f' }, action: { type: 'string', enum: [ 'voucher', 'vouchers' ] }, type: { type: 'string' }, prefix: { description: 'The prefix to look up and remove from scan results before requesting the voucher.', type: 'string', maxLength: 16, example: 'bsh' }, display_name: { default: null, ...oneOf({ description: 'The display string for presenting the selection of available prefixes.', type: 'string', maxLength: 64, example: 'BSH - Marketing' }) }, display_format: { default: null, ...oneOf({ description: '\'X\' will be filled with digits/characters from a scan result.', type: 'string', maxLength: 64, example: 'XXXX-XXXX-XXXX-XXXX' }) }, min_identifier_length: { default: null, ...oneOf({ description: 'The minimum length before a lookup can be performed.', type: 'integer', minimum: 1, maximum: 32 }) }, system: { type: 'object', properties: { id: { type: 'string', description: 'The Tillhub system resource reference ID associated with this prefix.', example: '43847a66-97dc-4ac2-8e8a-c44920e1f22f' }, system: { oneOf: [ { type: 'null' }, { type: 'string', format: 'uuid', description: 'The Tillhub sub-system resource reference ID associated with this prefix.', example: '43847a66-97dc-4ac2-8e8a-c44920e1f22f' } ] }, type: { type: 'string', enum: [ 'tillhub-voucher-api', 'fleurop-voucher-api' ] } } }, product: { default: null, ...oneOf({ type: 'object', properties: { id: { oneOf: [ { type: 'string', format: 'uuid', description: 'The Tillhub product resource reference ID assocuated with this prefix.', example: '43847a66-97dc-4ac2-8e8a-c44920e1f22f' }, { type: 'null' } ] } } }) } } } } ] } import React from "react" import Layout from "../components/layout" import Seo from "../components/Seo/Seo" import Timetable from "../components/pages/timetable" const WorkshopDates = ({pageContext, location}) => ( ) export default WorkshopDates 0 (function() { 'use strict'; angular .module('projectTask') .factory('ModelCURD', ModelCURD) .factory('ToastDialog', ToastDialog) .factory('AuthenticationFactory', AuthenticationFactory) .factory('UserAuthFactory', UserAuthFactory) .factory('TokenInterceptor', TokenInterceptor) .factory('TaskOperate', TaskOperate); function ModelCURD($resource, servicehost, apiVersion) { var curd = { createCURDEntity: function(modelName) { return $resource(servicehost + apiVersion + modelName + '/:id', { id: '@_id' }, { 'update': { method: 'PUT' }, 'get': { method: 'GET' }, 'save': { method: 'POST' }, 'delete': { method: 'DELETE' }, 'queryPerPage': { method: 'GET', isArray: false }, 'queryById': { method: 'GET', isArray: false }, 'count': { method: 'GET', isArray: false, headers: { 'X-Count': true } } }); } } return curd; } function ToastDialog($uibModal) { var baseDialog = { animation: true, template: '', size: 'sm', windowTopClass: 'fixed-center dialog-lg', backdrop: 'static' } var loadingDialog = {}, successDialog = {}, errorDialog = {}; angular.copy(baseDialog, loadingDialog); angular.copy(baseDialog, successDialog); angular.copy(baseDialog, errorDialog); loadingDialog.template = '
        加载中
        '; successDialog.template = '
        done成功
        '; successDialog.backdrop = 'true'; errorDialog.template = '
        highlight_off失败
        '; errorDialog.backdrop = 'true'; return { showLoadingDialog: function() { return $uibModal.open(loadingDialog); }, showSuccessDialog: function() { return $uibModal.open(successDialog); }, showErrorDialog: function() { return $uibModal.open(errorDialog); } } } function AuthenticationFactory($window) { var auth = { isLogged: false, check: function() { if ($window.sessionStorage.token && $window.sessionStorage.Uid) { this.isLogged = true; } else { this.isLogged = false; } } } return auth; } function UserAuthFactory($window, $state, $http, AuthenticationFactory, servicehost) { return { signIn: function(account, password) { var req = { method: 'POST', url: servicehost + '/login', headers: { 'Content-Type': 'application/json' }, data: { account: account, password: password } } return $http(req).success(function() { AuthenticationFactory.check(); }); }, signOut: function() { if (AuthenticationFactory.isLogged) { AuthenticationFactory.isLogged = false; delete AuthenticationFactory.user; delete AuthenticationFactory.userRole; delete $window.sessionStorage.token; delete $window.sessionStorage.Uid; delete $window.sessionStorage.userRole; $state.go('signin'); } }, checkPwd: function(account, password) { var req = { method: 'POST', url: servicehost + '/login', headers: { 'Content-Type': 'application/json' }, data: { account: account, password: password, isCheckPwd: true } } return $http(req); } } } function TokenInterceptor($q, $window, $injector) { return { request: function(config) { config.headers = config.headers || {}; if ($window.sessionStorage.token) { config.headers['X-Access-Token'] = $window.sessionStorage.token; config.headers['X-Key'] = $window.sessionStorage.Uid; config.headers['X-State'] = $injector.get('$state').current.name; config.headers['Content-Type'] = "application/json"; } return config || $q.when(config); }, response: function(response) { return response || $q.when(response); } }; } function TaskOperate(ModelCURD, $rootScope, $window, moment, $mdDialog) { var self = this; var taskCURD = ModelCURD.createCURDEntity('task'); self.TodoCount = function() { taskCURD.count({ dealAccount: $window.sessionStorage.account, rate__lt: 100, planEndTime__lte: (moment().format('YYYY-MM-DD 00:00:00')) }) .$promise.then(function(data) { $rootScope.worksCount.value = data.count; if (data.count === 0) { $rootScope.worksCount.text = ''; } else if (data.count > 9) { $rootScope.worksCount.text = '9+'; } else { $rootScope.worksCount.text = data.count; } }); }; self.update = function(task, cb) { if (!task.realStartTime || task.realStartTime === '') { task.realStartTime = moment().format('YYYY-MM-DD 00:00:00'); } if (task.rate === 100) { task.realEndTime = moment().format('YYYY-MM-DD 00:00:00'); } if (task.rate != 100 && (task.realEndTime || task.realEndTime != '')) { task.realEndTime = ''; } taskCURD.update(task).$promise.then(function() { self.TodoCount(); cb(); }); }; self.delete = function(task, cb) { taskCURD.delete({ id: task._id }).$promise.then(function() { self.TodoCount(); cb(); }) }; self.get = function(queryConditions, cb) { if (typeof queryConditions!='object' || !queryConditions.hasOwnProperty('dealAccount')) { queryConditions.dealAccount = $window.sessionStorage.account; } taskCURD.query(queryConditions).$promise.then(function(docs) { cb(docs) }); }; self.getAll = function() { return taskCURD.query({}); }; self.showRateDialog = function(event, task, parentEl, cb) { $mdDialog.show({ parent: parentEl, targetEvent: event, template: '' + '' + '' + '进度' + '' + '' + '' + '' + '' + '' + '' + ' ' + ' 取消' + ' ' + ' ' + ' 确定' + ' ' + ' ' + '', locals: { task: task }, controller: function($scope, $mdDialog, task) { $scope.rate = task.rate ? task.rate : 0; $scope.closeDialog = function() { $mdDialog.hide(); } $scope.updateRate = function() { task.rate = $scope.rate; self.update(task, function() { $mdDialog.hide(); cb(); }); } } }); }; return self; } String.prototype.firstUpperCase = function() { return this.toString()[0].toUpperCase() + this.toString().slice(1); } })(); import dispatcher from './dispatcher'; import Answer from '../models/Answer'; import Artifact from '../models/Artifact'; import Location from '../models/Location'; import Process from '../models/Process'; import Statistic from '../models/Statistic'; import Survey from '../models/Survey'; import DBController from '../controllers/DBController'; const express = require('express'); const app = new express.Router(); const Models = { answers: Answer, artifacts: Artifact, locations: Location, processes: Process, statistics: Statistic, surveys: Survey, }; Object.keys(Models).forEach((key) => { app.post(`/${key}/find`, dispatcher(DBController, 'find', Models[key])); app.post(`/${key}/update`, dispatcher(DBController, 'update', Models[key])); app.post(`/${key}/remove`, dispatcher(DBController, 'remove', Models[key])); app.post(`/${key}/create`, dispatcher(DBController, 'create', Models[key])); }); module.exports = app; import React, { Component } from "react"; import {Table} from "react-bootstrap"; import BuyerDataService from "../../services/buyer.service"; export default class buyer extends Component { constructor(props) { super(props); this.retrieveBuyers = this.retrieveBuyers.bind(this); this.state = { buyers:[], } } componentDidMount() { this.retrieveBuyers(); } retrieveBuyers = () =>{ BuyerDataService.getAll().then(response => { if(response.status !== 204){ this.setState({ buyers:response.data }); } }).catch(err =>{ if (err.response.status === 500){ window.location.replace('/internal'); }else if (err.response.status === 403){ window.location.replace('/forbidden'); } }) } render() { const {buyers} = this.state; return( <>
      {buyers && buyers.map((buyer) =>( ))}
      First Name Last Name Spent Money
      {buyer.buyerFirstName} {buyer.buyerLastName} {buyer.buyerSpentMoney} $
      ); } } /* eslint-disable */ process.on("exit", function (code) { return console.log(`About to exit with code ${code}`); }); (async () => { const migration = require("../migrations/index.js"); await migration(); process.exit(0); })(); module.exports = function toReadable (number) { const h="hundred"; const one="one"; const two="two"; const three="three"; const four="four"; const five="five"; const six="six"; const seven="seven"; const eight="eight"; const nine="nine"; let varr=[one,two,three,four,five,six,seven,eight,nine]; let midarr=["ten","eleven", "twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]; let smarr=[one,two,three,four,five,six,seven,eight,nine]; const twenty="twenty"; const thirty="thirty"; const forty="forty"; const fifty="fifty"; const sixty="sixty"; const seventy="seventy"; const eighty="eighty"; const ninety="ninety"; let barr=[twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety]; let l=number.toString().length; if(number<20) switch(number){ case 0: return "zero"; case 1: return "one"; case 2: return "two"; case 3: return "three"; case 4: return "four"; case 5: return "five"; case 6: return "six"; case 7: return "seven"; case 8: return "eight"; case 9: return "nine"; case 10: return "ten"; case 11: return "eleven"; case 12: return "twelve"; case 13: return "thirteen"; case 14: return "fourteen"; case 15: return "fifteen"; case 16: return "sixteen"; case 17: return "seventeen"; case 18: return "eighteen"; case 19: return "nineteen"; } else if(number<100&&number%10===0) return barr[parseInt(number.toString()[0])-2]; else if(number<100) return barr[parseInt(number.toString()[0])-2]+" " + smarr[parseInt(number.toString()[1])-1]; else if(number===100) return "one hundred"; else if(number<1000&&number%100===0) return smarr[parseInt(number.toString()[0])-1]+ " " + h; else if(number<1000&&number%100<10) return smarr[parseInt(number.toString()[0])-1]+ " " + h+" "+ varr[parseInt(number.toString()[2])-1]; else if(number<1000&&number%100<20) return smarr[parseInt(number.toString()[0])-1]+ " " + h+" "+midarr[parseInt(number.toString()[2])]; else if(number<1000&&number%10===0) return smarr[parseInt(number.toString()[0])-1]+ " " + h+" "+ barr[parseInt(number.toString()[1])-2]; else if(number<1000) return smarr[parseInt(number.toString()[0])-1]+ " " + h+" "+ barr[parseInt(number.toString()[1])-2]+" " + smarr[parseInt(number.toString()[2])-1]; } 0 const { readFileSync } = require('fs'); const parser = require('@babel/parser'); const traverse = require('@babel/traverse').default; const compiler = require('vue-template-compiler'); export const extractComponentOption = (path, optionKey) => { let componentOptions = {}; const Component = compiler.parseComponent(readFileSync(path).toString()); if (!Component.script || Component.script.content.length < 1) { return componentOptions; } const script = Component.script.content; try { const parsed = parser.parse(script, { sourceType: 'module', plugins: [ 'nullishCoalescingOperator', 'optionalChaining', 'classProperties', 'decorators-legacy', 'dynamicImport', 'estree', 'exportDefaultFrom' ] }); traverse(parsed, { enter(path) { if (path.node.type === 'Property') { if (path.node.key.name === optionKey) { const data = script.substring(path.node.start, path.node.end); componentOptions = Function(`return ({${data}})`)()[optionKey]; } } } }); } catch (e) { console.error(`[extractComponentOptions] ${e}`); } return componentOptions; }; 1-10 module.exports = { logger: { transport: 'console', console: { driver: 'console' } } } 2silver/yafowil.widget.datetime0 /* jslint browser: true */ /* global jQuery, yafowil */ /* * yafowil datepicker widget * * Requires: jquery ui datepicker * Optional: bdajax */ if (window.yafowil === undefined) { window.yafowil = {}; } (function($, yafowil) { "use strict"; $(document).ready(function() { // initial binding yafowil.datepicker.binder(); // add after ajax binding if bdajax present if (window.bdajax !== undefined) { $.extend(window.bdajax.binders, { datepicker_binder: yafowil.datepicker.binder }); } // add binder to yafowil.widget.array hooks if (yafowil.array !== undefined) { $.extend(yafowil.array.hooks.add, { datepicker_binder: yafowil.datepicker.binder }); } }); $.extend(yafowil, { datepicker: { binder: function(context) { $('input.datepicker', context).datepicker({ showAnim: null, showOn: 'both' }); $('input.timepicker', context).timepicker({ showPeriodLabels: false, showOn: 'both' }); } } }); // Configure jQuery.UI datepicker languages. $(function() { $.datepicker.regional.de = { clearText: 'löschen', clearStatus: 'aktuelles Datum löschen', closeText: 'schließen', closeStatus: 'ohne Änderungen schließen', prevText: '<zurück', prevStatus: 'letzten Monat zeigen', nextText: 'Vor>', nextStatus: 'nächsten Monat zeigen', currentText: 'heute', currentStatus: '', monthNames: [ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ], monthNamesShort: [ 'Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez' ], monthStatus: 'anderen Monat anzeigen', yearStatus: 'anderes Jahr anzeigen', weekHeader: 'Wo', weekStatus: 'Woche des Monats', dayNames: [ 'Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag' ], dayNamesShort: [ 'So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa' ], dayNamesMin: [ 'So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa' ], dayStatus: 'Setze DD als ersten Wochentag', dateStatus: 'Wähle D, M d', dateFormat: 'dd.mm.yy', firstDay: 1, initStatus: 'Wähle ein Datum', isRTL: false }; $.datepicker.setDefaults($.datepicker.regional.de); $.timepicker.regional.de = { hourText: 'Stunde', minuteText: 'Minuten', amPmText: ['AM', 'PM'] , closeButtonText: 'Beenden', nowButtonText: 'Aktuelle Zeit', deselectButtonText: 'Wischen' }; $.timepicker.setDefaults($.timepicker.regional.de); }); })(jQuery, yafowil); module.exports = { roots: ['src/'], moduleNameMapper: { '\\.(woff|woff2|svg)$': '/jest/fileMock.ts' }, collectCoverageFrom: ['**/*.ts?(x)', '!**/*.d.ts', '!**/*.test.e2e.ts?(x)', '!jest/**/*'], setupFiles: ['jest-canvas-mock'], setupFilesAfterEnv: ['./jest/setupTests.ts'], snapshotResolver: './jest/snapshotResolver.js', snapshotSerializers: ['enzyme-to-json/serializer'], testEnvironment: 'jsdom' }; 1-10 var classreliability__calculator__variance = [ [ "reliability_calculator_variance", "classreliability__calculator__variance.html#aa97b8fa061b578f6be66a89afba64657", null ], [ "~reliability_calculator_variance", "classreliability__calculator__variance.html#a9c6247e8a7dcb39c3e0702ba763d17f0", null ], [ "calculate_reliability", "classreliability__calculator__variance.html#ac6380a3bedfdc5648f501cd0a5c92369", null ], [ "calculate_reliability", "classreliability__calculator__variance.html#a0250bc0b9f2d62ec48b66449d6f94b56", null ], [ "init_junctions", "classreliability__calculator__variance.html#ad371792568036db7a8dac6fabbb78d05", null ] ];itsRockyy/minesweeper import Minesweeper from "./Minesweeper"; // Predefined game settings, we can also have custom rows/columns/mines const gameSettings = { easy: { rows: 10, columns: 10, mines: 15, }, medium: { rows: 15, columns: 15, mines: 40, }, hard: { rows: 20, columns: 20, mines: 99, }, }; // Run function once DOM is loaded window.onload = function () { // Selectors const difficulty = document.querySelector("#difficulty"); const board = document.querySelector("#board"); const end = document.querySelector(".game-over"); const timerDisplay = document.querySelector("#timer"); const finishStatus = end.querySelector("h1"); const finishTime = document.querySelector(".finish-time"); // Global variables let game = null; // Main game variable let timer = null; // Holds timer let isGameOver = false; // Handles game state on opening a tile const revealTile = ({ target }) => { if (!target.classList.contains("cell") || isGameOver) return; const { x, y } = target.dataset; const { revealed, gameOver } = game.openCell( parseInt(x, 10), parseInt(y, 10) ); if (gameOver) { // Lose Scenario isGameOver = true; clearInterval(timer); target.innerHTML = "💣"; target.dataset.val = "💣"; revealed.forEach((cell, index) => { const tile = board.querySelector( `:nth-child(${cell.x * game.COLUMNS + cell.y + 1})` ); setTimeout(() => { tile.dataset.val = "💣"; tile.innerHTML = "💣"; if (index === revealed.length - 1) { finishStatus.innerHTML = "You Lost !!! 👎"; end.querySelector("#retry").innerHTML = "Retry"; end.style.top = 0; } }, index * 200); }); return; } else { const openedTiles = game.board.flat().reduce((acc, item) => { return (acc += item.isRevealed ? 1 : 0); }, 0); // Win Scenario if (openedTiles + game.mines === game.ROWS * game.COLUMNS) { clearInterval(timer); finishStatus.innerHTML = "You Win !!! ✌️"; end.querySelector("#retry").innerHTML = "New Game"; end.style.top = 0; } // Reveal all eligible tiles for (let cell of revealed) { const tile = board.querySelector( `:nth-child(${cell.x * game.COLUMNS + cell.y + 1})` ); tile.dataset.val = cell.value; tile.innerHTML = cell.value || ""; } } }; // Generate the Minesweeper board const generateBoard = (arr, columns) => { board.innerHTML = arr.reduce( (acc, cell) => acc + `
      `, "" ); board.style.width = `calc(${ columns * document.querySelector(".cell").clientWidth }px + ${(columns - 1) * 2}px)`; timer = setInterval(() => { const diff = Math.floor((Date.now() - game.startTime) / 1000); const min = Math.floor(diff / 60) .toString() .padStart(2, "0"); const sec = Math.floor(diff % 60) .toString() .padStart(2, "0"); timerDisplay.innerHTML = `⏰ Time ${min}:${sec}`; finishTime.innerHTML = `⏰ ${min}:${sec}`; }, 1000); // DEBUG: shows the board in console, not needed in PROD game.printBoard(); }; // Start a new game const startNewGame = () => { const { rows, columns, mines } = gameSettings[difficulty.value]; game = new Minesweeper(rows, columns, mines); game.init(); finishStatus.style.display = "block"; timerDisplay.innerHTML = `⏰ Time 00:00`; finishTime.innerHTML = `⏰ 00:00`; generateBoard(game.board.flat(), columns); isGameOver = false; }; // Open tile on click board.addEventListener("click", revealTile); // Handle right-click to 🚩 a tile board.addEventListener("contextmenu", (event) => { if (!event.target.classList.contains("cell")) return; event.preventDefault(); if (event.target.dataset.val === "🚩") { delete event.target.dataset.val; event.target.innerHTML = ""; } else { event.target.dataset.val = "🚩"; event.target.innerHTML = "🚩"; } }); // Handle difficulty change selection difficulty.addEventListener("change", () => { clearInterval(timer); finishStatus.innerHTML = "Start Game"; finishStatus.style.display = "none"; finishTime.style.display = "none"; end.style.top = "0"; }); // Restart Logic document.querySelector("#retry").addEventListener("click", () => { startNewGame(); end.style.top = "100%"; finishTime.style.display = "block"; }); }; import React, { Component } from "react"; import { isEmail, isEmpty } from './validator'; import './mylogin.css'; import { NavLink, } from "react-router-dom"; import TextField from "@material-ui/core/TextField"; import Avatar from '@material-ui/core/Avatar'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import { encode } from "base-64"; class Login extends Component { constructor(props) { super(props) this.state = { user: null, formData: {}, // Contains login form data errors: {}, // Contains login field errors formSubmitted: false, // Indicates submit status of login form userResponse: [], otpResponse: [], loading: false // Indicates in progress state of login form } } handleInputChange = (event) => { const target = event.target; const value = target.value; const name = target.name; let { formData } = this.state; formData[name] = value; this.setState({ formData: formData }); } validateLoginForm = (e) => { let errors = {}; const { formData } = this.state; if (isEmpty(formData.email)) { errors.email = "Email can't be blank"; return errors; } else if (!isEmail(formData.email)){ errors.email = "Please enter a valid email"; return errors; } else { this.validateUser(formData.email); setTimeout(()=>{ if(this.state.userResponse.message === 'Not Found'){ alert("Failed"); errors.password = ""; return false } else{ console.log(this.state.userResponse.message) this.sendOTP(this.state.userResponse.message); setTimeout(()=>{ alert("OTP Sent"); localStorage.setItem('userName', formData.email) localStorage.setItem('phoneNumber',this.state.userResponse.message) this.props.history.push('/Verify'); },3000); } },1000); } return errors; } validateUser(username) { let headers = new Headers(); let usernameAuth = '123'; let passwordAuth = ''; fetch('http://104.197.41.22:8080/validate/user', { method: 'POST', body: JSON.stringify({ userName: username, }), headers: { 'Authorization': 'Basic ' + encode(usernameAuth + ":" + passwordAuth), "Content-type": "application/json; charset=UTF-8" } }).then(response => { return response.json() }).then(json => { this.setState({ userResponse:json }); }); } sendOTP(phoneNumber) { let headers = new Headers(); let usernameAuth = '123'; let passwordAuth = ''; fetch('http://104.197.41.22:8080/otp/send', { method: 'POST', body: JSON.stringify({ phoneNumber: phoneNumber, }), headers: { 'Authorization': 'Basic ' + encode(usernameAuth + ":" + passwordAuth), "Content-type": "application/json; charset=UTF-8" } }).then(response => { return response.json() }).then(json => { this.setState({ otpResponse:json }); }); } check() { var test = "yes"; var x = test.charAt(1); console.log(x); } signOut() { this.setState({ user: null }) } signIn(username, password) { this.setState({ user: { username, password, } }) } onClick() { // console.log(product.email); var m = localStorage.getItem('db_email'); const url = 'http://localhost:4000/products/find?email=' + m; fetch(url) .then(res => res.json()) .then((response) => { localStorage.setItem('db_password', response.data[0].password); localStorage.setItem('db_number', response.data[0].phone_number); console.log(localStorage.getItem('db_email')); }) } login = (e) => { const { formData } = this.state; localStorage.setItem('db_email', formData.email); e.preventDefault(); let errors = this.validateLoginForm(); if (errors === true) { alert("You are successfully signed in..."); this.props.history.push('/Verify') } else { this.setState({ errors: errors, formSubmitted: true }); } } render() { const { errors } = this.state; return (
      Secure Login
      {errors.email &&
      {errors.email}
      }
      ) } } export default Login; code/build-dashboard/app/routes/Dashboard/components/Stats/__tests__/index-test.js0 import React from 'react'; import renderer from 'react-test-renderer'; import { shallow } from 'enzyme'; import { expect as chaiExpect } from 'chai'; import data from 'data.json'; import MetricsCard from 'routes/Dashboard/components/MetricsCard'; import BuildCard from 'routes/Dashboard/components/BuildCard'; import TestCard from 'routes/Dashboard/components/TestCard'; import Stats from '../'; describe('', () => { const props = data[2]; it('should render correctly', () => { const tree = renderer.create().toJSON(); expect(tree).toMatchSnapshot(); }); it('should appropraite cards correctly', () => { const wrapper = shallow(); chaiExpect(wrapper.find(MetricsCard)).to.have.length(1); chaiExpect(wrapper.find(BuildCard)).to.have.length(1); chaiExpect(wrapper.find(TestCard)).to.have.length(2); }); }); import { html } from './../../node_modules/lit-html/lit-html.js' import {getLastThreeGames} from "../api/data.js"; let homeTemplate = (lastGames) => html`

      ALL new games are

      Only in GamesPlay

      hero

      Latest Games

      ${lastGames.length === 0 ? html`

      No games yet

      ` : lastGames.map(gameCard)}
      `; const gameCard = (game) => html`

      ${game.title}

      `; export async function homePage(ctx) { const lastGames = await getLastThreeGames(); ctx.render(homeTemplate(lastGames)); } // Web Audio API hint // @author hoch () // CodeMirror, copyright (c) by and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function (mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function (CodeMirror) { var Pos = CodeMirror.Pos; function forEach(arr, f) { for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); } function arrayContains(arr, item) { if (!Array.prototype.indexOf) { var i = arr.length; while (i--) { if (arr[i] === item) return true; } return false; } return arr.indexOf(item) != -1; } function scriptHint(editor, keywords, getToken, options) { // Find the token at the cursor. var cur = editor.getCursor(); var token = getToken(editor, cur); // Exit with invalid token, such as a null. if (/\b(?:comment|number|operator|null)\b/.test(token.type)) return; token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; // If it's not a 'word-style' token, ignore the token. if (!/^[\w$_'"]*$/.test(token.string)) { token = { start: cur.ch, end: cur.ch, string: '', state: token.state, type: token.string == "." ? "property" : null }; } else if (token.end > cur.ch) { token.end = cur.ch; token.string = token.string.slice(0, cur.ch - token.start); } var tprop = token; // If it is a property, find out what it is a property of. while (tprop.type == "property") { tprop = getToken(editor, Pos(cur.line, tprop.start)); if (tprop.string != ".") return; tprop = getToken(editor, Pos(cur.line, tprop.start)); if (!context) var context = []; context.push(tprop); } return { list: getCompletions(token, context, keywords, options), from: Pos(cur.line, token.start), to: Pos(cur.line, token.end) }; } function webAudioAPIHint(editor, options) { return scriptHint( editor, WEBAUDIOAPI_KEYWORDS, function (e, cur) { return e.getTokenAt(cur); }, options ); } CodeMirror.registerHelper("hint", "webaudioapi", webAudioAPIHint); var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " + "toUpperCase toLowerCase split concat match replace search").split(" "); var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " + "lastIndexOf every some filter forEach map reduce reduceRight ").split(" "); var funcProps = "prototype apply call bind".split(" "); function getCompletions(token, context, keywords, options) { var global = options && options.globalScope || window; var found = []; var start = token.string; function maybeAdd(str) { if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str); } function gatherCompletions(obj) { if (typeof obj == "string") forEach(stringProps, maybeAdd); else if (obj instanceof Array) forEach(arrayProps, maybeAdd); else if (obj instanceof Function) forEach(funcProps, maybeAdd); for (var name in obj) maybeAdd(name); } if (context && context.length) { // If this is a property, see if it belongs to some object we can // find in the current environment. var obj = context.pop(); var base; if (obj.type && obj.type.indexOf("variable") === 0) { if (options && options.additionalContext) base = options.additionalContext[obj.string]; if (!options || options.useGlobalScope !== false) base = base || global[obj.string]; } else if (obj.type == "string") { base = ""; } else if (obj.type == "atom") { base = 1; } else if (obj.type == "function") { if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') && (typeof global.jQuery == 'function')) base = global.jQuery(); else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function')) base = global._(); } while (base != null && context.length) base = base[context.pop().string]; if (base != null) gatherCompletions(base); forEach(keywords, maybeAdd); } else { // If not, just look in the local scope. for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); forEach(keywords, maybeAdd); } return found; } // Web Audio API keyword dictionary. var WEBAUDIOAPI_KEYWORDS = ("AudioContext suspend resume close createBuffer createBufferSource " + "createMediaElementSource createMediaStreamSource createMediaStreamDestination createAnalyser " + "createGain createDelay createBiquadFilter createWaveShaper createPanner createStereoPanner " + "createConvolver createChannelSplitter createChannelMerger createDynamicsCompressor " + "createOscillator createPeriodicWave decodeAudioData OfflineAudioContext startRendering " + "setValueAtTime linearRampToValueAtTime exponentialRampToValueAtTime setTargetAtTime " + "setValueCurveAtTime cancelScheduledValues getChannelData copyFromChannel copyToChannel " + "connect disconnect start stop setPosition setOrientation setVelocity setPosition setOrientation " + "setVelocity getFloatFrequencyData getByteFrequencyData getFloatTimeDomainData getByteTimeDomainData " + "getFrequencyResponse start stop setPeriodicWave " + "attack buffer channelCount channelCountMode channelInterpretation " + "coneInnerAngle coneOuterAngle coneOuterGain context currentTime curve custom defaultValue destination " + "detune distanceModel dopplerFactor duration fftSize frequency frequencyBinCount gain " + "knee listener loop loopEnd loopStart maxChannelCount maxDecibels " + "maxDistance minDecibels normalize numberOfInputs numberOfOutputs oncomplete onended " + "onstatechange oversample pan panningModel playbackRate Q ratio reduction refDistance " + "release renderedBuffer rolloffFactor sampleRate smoothingTimeConstant " + "speedOfSound stream threshold type value " + "'sawtooth' 'sine' 'square' '2x' '4x' 'none' 'allpass' 'triangle' 'lowpass' 'lowshelf' 'peaking' " + "'highpass' 'highshelf' 'clamped-max' 'max' 'bandpass' 'explicit' 'discrete' 'notch' 'speakers' " + "case continue default do else false for function " + "if in instanceof new null return switch true try typeof var while").split(" "); }); src/icons/bookmark-star-fill.js import React, { forwardRef } from 'react'; import PropTypes from 'prop-types'; const BookmarkStarFill = forwardRef(({ color, size, ...rest }, ref) => { return ( ); }); BookmarkStarFill.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; BookmarkStarFill.defaultProps = { color: 'currentColor', size: '1em', }; export default BookmarkStarFill; webapp/src/main/webapp/wkhome/js/controllers/barChart.js wkhomeControllers.controller('barChart', ['$scope', 'globalData', 'sparqlQuery', 'Statistics', 'searchData', '$route', '$window', function($scope, globalData, sparqlQuery, Statistics, searchData, $window) { var self = this; var IES = []; var Authors = []; var Publications = []; var countAuthors = 0; var countPub = 0; self.data = Statistics.query({ id: 'barchar' }, function(data) { var totalPubAut = data["@graph"]; if (totalPubAut) { _.map(totalPubAut, function(total) { var sourceid = total["@id"]; var sourcename = total["uc:name"]; var totalAuthors = total["uc:totalAuthors"]["@value"]; var totalPublications = total["uc:totalPublications"]["@value"]; IES.push ( sourcename); Authors.push ( parseInt(totalAuthors)); Publications.push ( parseInt(totalPublications)); countAuthors = countAuthors + parseInt(totalAuthors); countPub = countPub + parseInt(totalPublications); }); dataToSend = { categories : IES , Data : [ { name : "Authors" , data : Authors } , { name : "Publications", data : Publications } ] , total : { "totalAuthors" : countAuthors , "totalPub" : countPub } }; $scope.data = dataToSend; } }); } ]); module.exports = (type, value, isEnum = false) => { const subDocHelper = require('./subDocHelper'); if (isEnum) { return isEnum[0]; } if (!type) { return subDocHelper(value); } switch (type.toLowerCase()) { case 'string': return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); case 'number': return Math.floor(Math.random() * 1000); case 'object': return { hi: true, cool: "okay", bean: 123 }; case 'boolean': return Math.floor(Math.random() * 1000) > 500 ? true : false; case 'enum': default: } }; 'use strict'; function add (x, y, base) { var z = []; var number = Math.max(x.length, y.length); var carry = 0; var i = 0; while (i < number || carry) { var xi = i < x.length ? x[i] : 0; var yi = i < y.length ? y[i] : 0; var zi = carry + xi + yi; z.push(zi % base); carry = Math.floor(zi / base); i++; } return z; } function times (number, x, base) { if (number < 0) { return null; } if (number === 0) { return []; } var result = []; var power = x; while (true) { if (number & 1) { result = add(result, power, base); } number = number >> 1; if (number === 0) { break; } power = add(power, power, base); } return result; } function parse (text, base) { return text.split('').reverse().map(digitize).filter(numbers); function digitize (digit) { return parseInt(digit, base); } function numbers (digit) { return typeof digit === 'number' && isNaN(digit) === false; } } function rebase (text, from, to) { var power = [1]; var digits = parse(text, from); if (digits === null) { return null; } return digits.reduce(addition, []).reverse().map(based).join(''); function addition (buffer, digit) { if (digit) { buffer = add(buffer, times(digit, power, to), to); } power = times(from, power, to); return buffer; } function based (digit) { return digit.toString(to); } } function dex (input, from, to) { var t = typeof input; if (t !== 'string' && t !== 'number' || input === '') { return null; } return rebase(String(input).toLowerCase(), from, to); } function hex (input) { return dex(input, 10, 16); } function dec (input) { return dex(input, 16, 10); } module.exports = dex; dex.hex = hex; dex.dec = dec; /** * @name charcode-is-valid-xml-name-character * @fileoverview Does a given character belong to XML spec's "Production 4 OR 4a" type (is acceptable for XML element's name) * @version 1.12.16 * @author , Codsen Ltd * @license MIT * {@link https://codsen.com/os/charcode-is-valid-xml-name-character/} */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.charcodeIsValidXmlNameCharacter = {})); }(this, (function (exports) { 'use strict'; /** * @name ranges-is-index-within * @fileoverview Checks if index is within any of the given string index ranges * @version 2.0.16 * @author , Codsen Ltd * @license MIT * {@link https://codsen.com/os/ranges-is-index-within/} */ const defaults = { inclusiveRangeEnds: false, returnMatchedRangeInsteadOfTrue: false }; function isIndexWithin(originalIndex, rangesArr, originalOpts) { const opts = { ...defaults, ...originalOpts }; if (!Number.isInteger(originalIndex)) { throw new Error(`ranges-is-index-within: [THROW_ID_01] the first input argument should be string index, a natural number (or zero). It was given as ${originalIndex} (type ${typeof originalIndex})`); } if (!Array.isArray(rangesArr)) { return false; } if (opts.returnMatchedRangeInsteadOfTrue) { return rangesArr.find(arr => opts.inclusiveRangeEnds ? originalIndex >= arr[0] && originalIndex <= arr[1] : originalIndex > arr[0] && originalIndex < arr[1]) || false; } return rangesArr.some(arr => opts.inclusiveRangeEnds ? originalIndex >= arr[0] && originalIndex <= arr[1] : originalIndex > arr[0] && originalIndex < arr[1]); } // https://www.w3.org/TR/REC-xml/#NT-NameStartChar // Production 4 - except lowercase letters are missing const nameStartChar = [ [58, 58], [65, 90], [95, 95], [192, 214], [216, 246], [248, 767], [880, 893], [895, 8191], [8204, 8205], [8304, 8591], [11264, 12271], [12289, 55295], [63744, 64975], [65008, 65533], [65536, 983039], // [#x10000-#xEFFFF] ]; // https://www.w3.org/TR/REC-xml/#NT-NameChar // Production 4a - addition to Production 4, except lowercase letters are missing const nameChar = [ [45, 45], [46, 46], [48, 57], [58, 58], [65, 90], [95, 95], [183, 183], [192, 214], [216, 246], [248, 767], [768, 879], [880, 893], [895, 8191], [8204, 8205], [8255, 8256], [8304, 8591], [11264, 12271], [12289, 55295], [63744, 64975], [65008, 65533], [65536, 983039], // [#x10000-#xEFFFF] ]; const priorityNameChar = [ [97, 122], // [a-z] ]; const opts = { inclusiveRangeEnds: true, skipIncomingRangeSorting: true, }; // first checking the letters, then the rest function isProduction4(char) { return (isIndexWithin(char.codePointAt(0), priorityNameChar, opts) || isIndexWithin(char.codePointAt(0), nameStartChar, opts)); } function isProduction4a(char) { return (isIndexWithin(char.codePointAt(0), priorityNameChar, opts) || isIndexWithin(char.codePointAt(0), nameChar, opts)); } exports.isProduction4 = isProduction4; exports.isProduction4a = isProduction4a; exports.validFirstChar = isProduction4; exports.validSecondCharOnwards = isProduction4a; Object.defineProperty(exports, '__esModule', { value: true }); }))); Randy424/grc-ui /* Copyright (c) 2020 Red Hat, Inc. */ /* Copyright Contributors to the Open Cluster Management project */ 'use strict' import { renderAnsibleRemovalModal } from '../../../../../src-web/components/modals/AnsibleAutomationModal/AnsibleRemovalModal' describe('render ansible removal modal', () => { it('render opened ansible removal modal', () => { const component = renderAnsibleRemovalModal({ openDelModal:true, policyAutoName: 'test-policy-3-1624936287-policy-automation', locale: 'us', handleDeleteClick:jest.fn(), handleCloseDelModal:jest.fn() }) expect(component).toMatchSnapshot() }) it('render opened ansible removal modal without policy automation name', () => { const component = renderAnsibleRemovalModal({ openDelModal:true, policyAutoName: '', locale: 'us', handleDeleteClick:jest.fn(), handleCloseDelModal:jest.fn() }) expect(component).toMatchSnapshot() }) it('render closed ansible removal modal', () => { const component = renderAnsibleRemovalModal({ openDelModal:false, policyAutoName: 'test-policy-3-1624936287-policy-automation', locale: 'us', handleDeleteClick:jest.fn(), handleCloseDelModal:jest.fn() }) expect(component).toMatchSnapshot() }) it('render closed ansible removal modal without policy automation name', () => { const component = renderAnsibleRemovalModal({ openDelModal:true, policyAutoName: '', locale: 'us', handleDeleteClick:jest.fn(), handleCloseDelModal:jest.fn() }) expect(component).toMatchSnapshot() }) }) import React from 'react' import Helmet from 'react-helmet' import { Link } from 'gatsby' import './layout.css' const Layout = (props) => { return ( <> My Portfolio

      My Portfolio

      See my great works

      {props.children}

      Contact

      ) } export default Layout /* eslint max-nested-callbacks:[1] */ 'use strict'; var gStreamify = require('../'); var Stream = require('stream'); var streamtest = require('streamtest'); var gutil = require('gulp-util'); var assert = require('assert'); describe('gulp-streamify', function() { // Simple plugin appending test to contents for test purposes function pluginFunction() { var pluginStream = new Stream.Transform({ objectMode: true }); pluginStream._transform = function(file, unused, cb) { assert(file.contents instanceof Buffer); file.contents = Buffer.concat([file.contents, new Buffer('test')]); pluginStream.push(file); cb(); }; return pluginStream; } streamtest.versions.forEach(function(version) { describe('for ' + version + ' streams', function() { it('should pass null files through', function(done) { gStreamify(streamtest[version].fromObjects([ new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file.js', contents: null, }), new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file2.js', contents: null, }), ])).pipe(streamtest[version].toObjects(function(err, objs) { if(err) { return done(err); } assert.equal(objs.length, 2); done(); })); }); it('should reemit errors', function(done) { var passStream = new Stream.PassThrough({ objectMode: true }); var stream = gStreamify(passStream); var inputError = new Error('ich bin ein error'); stream.on('error', function(error) { assert.equal(error, inputError); done(); }); passStream.emit('error', inputError); }); describe('in stream mode', function() { it('should work with sync streams and sync contents', function(done) { var pluginStream = pluginFunction(); var inputStream = new Stream.PassThrough({ objectMode: true }); var fakeFile = new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file.js', contents: new Stream.PassThrough(), }); var fakeFile2 = new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file2.js', contents: new Stream.PassThrough(), }); inputStream .pipe(gStreamify(pluginStream)) .pipe(streamtest[version].toObjects(function(err, files) { if(err) { return done(err); } assert.equal(files.length, 2); assert.equal(files[0].cwd, '/home/nfroidure/'); assert.equal(files[0].base, '/home/nfroidure/test'); assert.equal(files[0].path, '/home/nfroidure/test/file.js'); assert.equal(files[1].cwd, '/home/nfroidure/'); assert.equal(files[1].base, '/home/nfroidure/test'); assert.equal(files[1].path, '/home/nfroidure/test/file2.js'); files[0].pipe(streamtest[version].toText(function(err2, text) { if(err2) { return done(err2); } assert.equal(text, 'plipplaptest'); files[1].pipe(streamtest[version].toText(function(err3, text2) { if(err3) { return done(err3); } assert.equal(text2, 'ploppluptest'); done(); })); })); })); inputStream.write(fakeFile); inputStream.write(fakeFile2); inputStream.end(); fakeFile.contents.write('plip'); fakeFile.contents.write('plap'); fakeFile.contents.end(); fakeFile2.contents.write('plop'); fakeFile2.contents.write('plup'); fakeFile2.contents.end(); }); it('should work with sync streams and async contents', function(done) { var pluginStream = pluginFunction(); var inputStream = new Stream.PassThrough({ objectMode: true }); var fakeFile = new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file.js', contents: streamtest.v2.fromChunks(['plip', 'plap']), }); var fakeFile2 = new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file2.js', contents: streamtest.v2.fromChunks(['plop', 'plup']), }); inputStream .pipe(gStreamify(pluginStream)) .pipe(streamtest[version].toObjects(function(err, files) { if(err) { return done(err); } assert.equal(files.length, 2); assert.equal(files[0].cwd, '/home/nfroidure/'); assert.equal(files[0].base, '/home/nfroidure/test'); assert.equal(files[0].path, '/home/nfroidure/test/file.js'); assert.equal(files[1].cwd, '/home/nfroidure/'); assert.equal(files[1].base, '/home/nfroidure/test'); assert.equal(files[1].path, '/home/nfroidure/test/file2.js'); files[0].pipe(streamtest[version].toText(function(err2, text) { if(err2) { return done(err2); } assert.equal(text, 'plipplaptest'); files[1].pipe(streamtest[version].toText(function(err3, text2) { if(err3) { return done(err3); } assert.equal(text2, 'ploppluptest'); done(); })); })); })); inputStream.write(fakeFile); inputStream.write(fakeFile2); inputStream.end(); }); it('should work with async streams and async contents', function(done) { var pluginStream = pluginFunction(); streamtest[version].fromObjects([ new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file.js', contents: streamtest.v2.fromChunks(['plip', 'plap']), }), new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file2.js', contents: streamtest.v2.fromChunks(['plip', 'plup']), }), ]) .pipe(gStreamify(pluginStream)) .pipe(streamtest[version].toObjects(function(err, files) { if(err) { return done(err); } assert.equal(files.length, 2); assert.equal(files[0].cwd, '/home/nfroidure/'); assert.equal(files[0].base, '/home/nfroidure/test'); assert.equal(files[0].path, '/home/nfroidure/test/file.js'); assert.equal(files[1].cwd, '/home/nfroidure/'); assert.equal(files[1].base, '/home/nfroidure/test'); assert.equal(files[1].path, '/home/nfroidure/test/file2.js'); files[0].pipe(streamtest[version].toText(function(err2, text) { if(err2) { return done(err2); } assert.equal(text, 'plipplaptest'); files[1].pipe(streamtest[version].toText(function(err3, text2) { if(err3) { return done(err3); } assert.equal(text2, 'plippluptest'); done(); })); })); })); }); it('should work with plugin function provinding async files streams', function(done) { streamtest[version].fromObjects([ new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file.js', contents: streamtest.v2.fromChunks(['plip', 'plap']), }), new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file2.js', contents: streamtest.v2.fromChunks(['plip', 'plup']), }), ]) .pipe(gStreamify(pluginFunction)) .pipe(streamtest[version].toObjects(function(err, files) { if(err) { return done(err); } assert.equal(files.length, 2); assert.equal(files[0].cwd, '/home/nfroidure/'); assert.equal(files[0].base, '/home/nfroidure/test'); assert.equal(files[0].path, '/home/nfroidure/test/file.js'); assert.equal(files[1].cwd, '/home/nfroidure/'); assert.equal(files[1].base, '/home/nfroidure/test'); assert.equal(files[1].path, '/home/nfroidure/test/file2.js'); files[0].pipe(streamtest[version].toText(function(err2, text) { if(err2) { return done(err2); } assert.equal(text, 'plipplaptest'); files[1].pipe(streamtest[version].toText(function(err3, text2) { if(err3) { return done(err3); } assert.equal(text2, 'plippluptest'); done(); })); })); })); }); }); describe('in buffer mode', function() { it('should work', function(done) { var pluginStream = pluginFunction(); streamtest[version].fromObjects([ new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file.js', contents: new Buffer('plipplap'), }), new gutil.File({ cwd: '/home/nfroidure/', base: '/home/nfroidure/test', path: '/home/nfroidure/test/file2.js', contents: new Buffer('plipplup'), }), ]) .pipe(gStreamify(pluginStream)) .pipe(streamtest[version].toObjects(function(err, files) { if(err) { return done(err); } assert.equal(files.length, 2); assert.equal(files[0].cwd, '/home/nfroidure/'); assert.equal(files[0].base, '/home/nfroidure/test'); assert(files[0].contents instanceof Buffer); assert.equal(files[0].path, '/home/nfroidure/test/file.js'); assert.equal(files[0].contents.toString(), 'plipplaptest'); assert.equal(files[1].cwd, '/home/nfroidure/'); assert.equal(files[1].base, '/home/nfroidure/test'); assert(files[1].contents instanceof Buffer); assert.equal(files[1].path, '/home/nfroidure/test/file2.js'); assert.equal(files[1].contents.toString(), 'plippluptest'); done(); })); }); }); }); }); }); vanillaes/absurdum /** * Reversed the characters in a string * * @param {string} string input string * @returns {string} input string reversed * * @example * const result = strings.reverse('This string will be reversed'); * console.log(result); * > desrever eb lliw gnirts sihT */ function reverse (string) { return string.split('').reduce((acc, curr) => { return curr + acc }, '') } export { reverse } davidfertig/multivalue-lab (function () { var CustListController = function ($scope, $routeParams, CustListFactory) { $scope.customerList = []; function init() { CustListFactory.getCustomers($routeParams.CustName, $routeParams.CustAddress, $routeParams.CustPhone, $routeParams.CustTerrNo) .success(function (customers) { if ( angular.isArray(customers.getCustList.CUSTLIST.foundCustomers) ) { $scope.customerList = customers.getCustList.CUSTLIST.foundCustomers; } else { $scope.customerList = [customers.getCustList.CUSTLIST.foundCustomers]; } }) .error(function (data, status, headers, config) { $log.log(data.error + ' ' + status); }); } init(); $scope.doSort = function(propName) { $scope.sortBy = propName; $scope.reverse = !$scope.reverse; }; $scope.deleteCustomer = function(CUSTID) { CustListFactory.deleteCustomer(CUSTID) .success(function(status) { if (status) { for (var i=0,len=$scope.customerList.length;i, , , , , , , , , , , , , , , // , // , // , // , // , // , // , ]; export default resourcesskylark-integration/skylark-highlightjs0 /** * skylark-highlightjs - A version of highlightjs.js that ported to running on skylarkjs * @author Hudaokeji, Inc. * @version v0.9.0 * @link https://github.com/skylark-integration/skylark-highlightjs/ * @license MIT */ define(["../highlight"],function(e){return{contains:[{className:"function",begin:"#+[A-Za-z_0-9]*\\(",end:" {",returnBegin:!0,excludeEnd:!0,contains:[{className:"keyword",begin:"#+"},{className:"title",begin:"[A-Za-z_][A-Za-z_0-9]*"},{className:"params",begin:"\\(",end:"\\)",endsParent:!0,contains:[{className:"string",begin:'"',end:'"'},{className:"variable",begin:"[A-Za-z_][A-Za-z_0-9]*"}]}]}]}}); //# sourceMappingURL=../sourcemaps/languages/leaf.js.map 1-10 import React from // { useMemo } 'react'; import { NavLink, withRouter } from 'react-router-dom'; import navLogo from '../../media/icon.png'; // import history from '../../history'; // CSS import { Content } from './NavCSS'; function Navbar() { // const path = history.location.pathname; // useMemo(() => { // switch (path) { // case '/github': // break; // case '/': // break; // default: // break; // } // }, [history.location.pathname]); return (
      Home Projects About Services Contact
      ); } export default withRouter(Navbar); fossabot/bartender1-10 const baseConfig = require('./build.base.config') /** * @type {import('electron-builder').Configuration} */ const config = { ...baseConfig, mac: { icon: 'build/icons/icon.icns', target: [ { target: 'zip' } ], files: [ // 'node_modules/7zip-bin/**/*', // '!node_modules/7zip-bin/linux/**', // '!node_modules/7zip-bin/win/**' ] }, win: { icon: 'build/icons/icon.ico', target: [ { target: 'zip', arch: [ 'x64', 'ia32' ] } ], files: [ // 'node_modules/7zip-bin/**/*', // '!node_modules/7zip-bin/linux/**', // '!node_modules/7zip-bin/mac/**' ] }, linux: { icon: 'build/icons', target: [ { target: 'tar.gz' } ], files: [ // 'node_modules/7zip-bin/**/*', // '!node_modules/7zip-bin/win/**', // '!node_modules/7zip-bin/mac/**' ] } } module.exports = config 'use strict'; /** * We receive the dbmigrate dependency from dbmigrate initially. * This enables us to not have to rely on NODE_PATH. */ exports.up = async function (db) { console.log(`**** Changing 'Draft EAC Application' milestone tag to 'EAC Application' ****`); const mClient = await db.connection.connect(db.connectionString, { native_parser: true }); const epic = await mClient.collection('epic'); try { await epic.updateOne( { name: 'Draft EAC Application' }, { $set: { name: 'EAC Application' } } ); } catch (err) { console.log(`ERROR: ${err}`); } console.log(`**** Finished changing 'Draft EAC Application' milestone tag to 'EAC Application' ****`); mClient.close(); return null; }; exports.down = function (db) { return null; }; exports._meta = { "version": 1 }; 0 import axios from 'axios'; class AuthService { login(user) { return axios .post(`${process.env.SERVER_URI}/login`, { email: user.email, password: }) .then(response => { if (response.data.token) { localStorage.setItem(process.env.LOCAL_STORAGE_AUTH_KEY, JSON.stringify(response.data)); } return response.data; }) .catch(error => { console.log(error); return null; }); } logout() { localStorage.removeItem(process.env.LOCAL_STORAGE_AUTH_KEY); } registerProdutor(produtor) { return axios.post(`${process.env.SERVER_URI}/cadastro/produtor`, produtor); } registerConsumidor(consumidor) { return axios.post(`${process.env.SERVER_URI}/cadastro/consumidor`, consumidor); } confirmationEmail(user) { return axios .post(`${process.env.SERVER_URI}/enable-account`, { email: user.email, token: user.token }) } carregarUsuario() { let user = JSON.parse(localStorage.getItem(process.env.LOCAL_STORAGE_AUTH_KEY)).user; return user; } } export default new AuthService(); addon/services/leaderboard.js import $ from 'jquery'; import Service from '@ember/service'; import googletag from 'googletag'; export default Service.extend({ install() { window.addEventListener('message', this._resizeLeaderboard); googletag.cmd.push(() => googletag.pubads().addEventListener('slotRenderEnded', this.adSpaceCleanup)); }, willDestroy() { this._super(...arguments); window.removeEventListener('message', this._resizeLeaderboard); }, adSpaceCleanup(e) { if (/leaderboard/.test(e.slot.getAdUnitPath())) { if (e.isEmpty) { $('#leaderboard').addClass('is-collapsed'); } else { $('#leaderboard').removeClass('is-collapsed'); } } }, _resizeLeaderboard(e) { let data; let shouldOpen; let $leaderboard = $('#leaderboard > div > iframe, #leaderboard > div'); // lots of things on a page can send a postMessage, but not all of that // data is parsable as JSON. this prevents nasty console messages. try { data = JSON.parse(e.data); } catch(err) { return false; } // just a little sanity check that we're receiving a message from our ad if ( !data.wnyc ) { return false; } if ( data.msg === 'init' ) { $('#leaderboard').css('max-height', 'none'); shouldOpen = false; } else { shouldOpen = data.msg === 'open'; } if ( $leaderboard.length !== 1 ) { $leaderboard = $('#leaderboard > div > iframe, #leaderboard > div'); } $leaderboard.css('max-height', shouldOpen ? 415 : 90); } }); 0 <<<<<<< HEAD $(document).ready(function() { $("#nit").mask("9999-999999-999-9"); $("#fechaNacimiento").mask("99/99/9999"); ======= $(document).ready(function() { $("#nit").mask("9999-999999-999-9"); $("#fechaNacimiento").mask("99/99/9999"); >>>>>>> 8404f3d80dcbc2494a76c11cd1ac9cae57de7f40 });import React from "react" import { CardComponent } from "../CardComponent" import { documentToReactComponents } from "@contentful/rich-text-react-renderer" import "./Education.scss" import ImageDynamic from "../ImageDynamic" export const Education = ({ educationData }) => { return (

      Education

      {educationData.map(({ education }) => { const { id, titleProfession, description, grade, school } = education return (
      {grade === `PHD` && ( )} {grade === `Master's Degree` && ( )} {grade === `Bachelor's Degree` && ( )} {grade === `Diploma` && ( )}
      {titleProfession}
      {grade} at {school}{" "}
      {documentToReactComponents(description.json)}
      ) })}
      ) } 0 const { GoogleSpreadSheet, GoogleSpreadsheet } = require ('google-spreadsheet') const credentials = require('./credentials.json') const doc = new GoogleSpreadsheet('1joeX9ePy3TbAI2JKopqtHITF2TxoGH4t9FcpqueJlhw') const run = async() => { try { await doc.useServiceAccountAuth(credentials) await doc.loadInfo() const sheet = doc.sheetsByIndex[1] //Nome Email Whatsapp Cupom Promo await sheet.addRow({ Nome: '', Email: '', Whatsapp: '11 951536476', Cupom: 'aaa111', Promo: 'bbb222' }) } catch (err) { console.log(err) } } run() const test = require('ava') const { fromScalar, toString } = require('./index') const { compareVectors } = require('../../../test/helpers/index') test('vec4: fromScalar() should return a new vec4 with correct values', (t) => { const obs1 = fromScalar(0) t.true(compareVectors(obs1, [0, 0, 0, 0])) const obs2 = fromScalar(-5) t.true(compareVectors(obs2, [-5, -5, -5, -5])) const str1 = toString(obs2) }) 1-10 import validator from 'validator'; import _ from 'lodash'; const validateUserRegistration = (data) => { let errors = {}; data.firstName = _.isEmpty(data.firstName) ? '' : data.firstName; data.lastName = _.isEmpty(data.lastName) ? '' : data.lastName; data.email = _.isEmpty(data.email) ? '' : data.email; data.password = _.isEmpty(data.password) ? '' : data.password; data.password2 = _.isEmpty(data.password2) ? '' : data.password2; if (validator.isEmpty(data.firstName)) { errors.firstName = 'First name is required.'; } if (validator.isEmpty(data.lastName)) { errors.lastName = 'Last name is required.'; } if (!validator.isEmail(data.email)) { errors.email = 'Please enter a valid email address.'; } if (validator.isEmpty(data.email)) { errors.email = 'Email address is required.'; } if (validator.isEmpty(data.password)) { errors.password = 'Password .'; } if (!validator.isLength(data.password, { min: 5, max: 20 })) { errors.password = 'Password must be between 5 and 20 characters.'; } if (validator.isAlphanumeric(data.password)) { errors.password = 'Password must must contain at least one special character.'; } if (validator.isEmpty(data.password2)) { errors.password2 = 'You must confirm your password.'; } if (!validator.equals(data.password, data.password2)) { errors.password2 = 'Your passwords do not match.'; } return { errors, isValid: _.isEmpty(errors) }; }; export default validateUserRegistration; /* * This file is part of the easy framework. * * (c) <> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * @class Configurable * * Act as an interface */ class Configurable { /** * configure - configure component * * @param {any} options = {} */ configure( options = {} ) {} } module.exports = Configurable import * as syncActions from '../../actions/syncActions'; import Dialog, { DialogActions, DialogContent, DialogContentText, DialogTitle, } from 'material-ui/Dialog'; import React, { Component } from 'react'; import Tabs, { Tab } from 'material-ui/Tabs'; import AppBar from 'material-ui/AppBar'; import Badge from 'material-ui/Badge'; import Button from 'material-ui/Button'; import ImageListEditor from '../shared/ImageListEditor'; import JSONPretty from 'react-json-pretty'; import KnowledgeBaseEntryEditForm from './KnowledgeBaseEntryEditForm'; import LinkListEditor from '../shared/LinkListEditor'; import PageBase from '../layout/PageBase'; import Paper from 'material-ui/Paper'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { withStyles } from 'material-ui/styles'; function mapStateToProps(state) { return { knowledgeBase: state.knowledgeBase, isLoaded: state.syncStatus.isLoaded }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(syncActions, dispatch) }; } const styles = theme => ({ badgePadding: { padding: `0 ${theme.spacing.unit * 2}px`, }, }); class KnowledgeBaseEntryDetailPage extends Component { constructor(props) { super(props); } state = { isLoaded: false, isModified: false, isNew: false, wantsToDelete: false, entity: { Links: [], ImageIds: [] }, group: {}, selectedTab: 0 } componentWillMount() { this.props.actions.ensureSync() .then(() => { let id = this.props.match.params.entryId; let groupId = this.props.match.params.groupId; if (id == null) { this.setState({ isLoaded: true, isModified: true, isNew: true, entity: { Order: 999, Links: [], ImageIds: [], KnowledgeGroupId: groupId } }); return; } this.setState({ id, entity: this.getEntryFromStore(id), isLoaded: true, isModified: false }); }); } submit = (entity) => { this.setState({ isLoaded: false }); if (this.state.isNew) { this.props.actions.createKnowledgeEntry(entity) .then((id) => { this.props.history.replace("/knowledgeBase/entry/" + id); }); return; } this.props.actions.updateKnowledgeEntry(entity) .then(() => { this.setState({ entity: this.getEntryFromStore(entity.Id), isLoaded: true, isModified: false }); }); } delete = (entity) => { if (!this.state.wantsToDelete) { this.setState({ wantsToDelete: true }); return; } this.setState({ isLoaded: false }); this.props.actions.deleteKnowledgeEntry(entity) .then(() => { this.props.history.replace("/knowledgeBase/group/" + entity.KnowledgeGroupId); }); } getGroupFromStore(id) { return this.props.knowledgeBase.knowledgeGroups.filter(item => item.Id == id)[0]; } getEntryFromStore(id) { return this.props.knowledgeBase.knowledgeEntries.filter(item => item.Id == id)[0]; } handleChange = (diff) => { let entity = Object.assign({}, this.state.entity, diff); this.setState({ entity, isModified: true }); }; editImage = (imageId) => { if (this.state.isModified) { alert("You must save your changes first."); return; } this.props.history.push("/images/edit/" + imageId); } render() { const { classes } = this.props; return ( this.setState({ selectedTab: v })} > Links } /> Images } /> {this.state.selectedTab == 0 ? this.handleChange(diff)} /> : null} {this.state.selectedTab == 1 ? this.handleChange({ Links })} /> : null} {this.state.selectedTab == 2 ? this.editImage(ImageId)} onChange={(ImageIds) => this.handleChange({ ImageIds })} /> : null} {this.state.selectedTab == 3 ? : null} this.setState({ wantsToDelete: false })} > Delete Entry? Are you sure? This can't be undone. ); } } KnowledgeBaseEntryDetailPage.propTypes = { actions: PropTypes.object.isRequired, isLoaded: PropTypes.bool.isRequired, knowledgeBase: PropTypes.object.isRequired, match: PropTypes.object.isRequired, history: PropTypes.object.isRequired, classes: PropTypes.object.isRequired }; export default connect( mapStateToProps, mapDispatchToProps )(withStyles(styles)(KnowledgeBaseEntryDetailPage));ShinyLeee/meteor-album-app-1-10 import PropTypes from 'prop-types'; import React from 'react'; import { Wrapper, Child } from './GridLayout.style'; const GridLayout = ({ columns, gap, children }) => ( { React.Children.map(children, (curChild) => ( {curChild} )) } ); GridLayout.displayName = 'GridLayout'; GridLayout.defaultProps = { columns: 3, gap: 4, }; GridLayout.propTypes = { columns: PropTypes.number, gap: PropTypes.number, children: PropTypes.any.isRequired, }; export default GridLayout; src/src/components/List/index.js import React from 'react'; import { Paper, Typography, CssBaseline } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import Title from './Tite'; import Card from '../Card'; const useStyle = makeStyles((theme) => ({ root: { width: '300px', backgroundColor: '#EBECF0', marginLeft: theme.spacing(1), }, })); export default function List() { const classes = useStyle(); return ( <> <Card /> <Card /> <Card /> </Paper> </> ); }<gh_stars>1-10 import {Record} from 'immutable' const ShippingPeriodRecord = new Record({ minDays: null, maxDays: null, displayUnit: null }) export default class ShippingPeriod extends ShippingPeriodRecord { } <reponame>somesocks/callback-patterns "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); // import Delay from './Delay'; // import If from './If'; // import InOrder from './InOrder'; // import InParallel from './InParallel'; var InSeries_1 = __importDefault(require("./InSeries")); var PassThrough_1 = __importDefault(require("./PassThrough")); var SHORT_CHAIN = InSeries_1.default.apply(void 0, Array(1000).fill(PassThrough_1.default)); var LONG_CHAIN = InSeries_1.default.apply(void 0, Array(1000).fill(SHORT_CHAIN)); LONG_CHAIN(function () { }, 1, 2, 3); <gh_stars>1-10 import React from 'react'; import Icon from './Icon'; const DragHandle = props => ( <Icon {...props}> {ownProps => ( <g {...ownProps}> <path {...ownProps} d="M11.94,21a3,3,0,1,1,3-3A3,3,0,0,1,11.94,21Zm12.12,0a3,3,0,1,1,3-3A3,3,0,0,1,24.06,21Zm0,12a3,3,0,1,1,3-3A3,3,0,0,1,24.06,33ZM24.06,9a3,3,0,1,1,3-3A3,3,0,0,1,24.06,9ZM11.94,33a3,3,0,1,1,3-3A3,3,0,0,1,11.94,33ZM11.94,9a3,3,0,1,1,3-3A3,3,0,0,1,11.94,9Z" /> </g> )} </Icon> ); DragHandle.displayName = 'DragHandle'; export default DragHandle; <filename>extension.js 'use strict'; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below const open = require('open'), path = require('path'), ServerInstance = require('./serverinstance'), vscode = require('vscode'); // this method is called when your extension is activated // your extension is activated the very first time the command is executed function activate(context) { const server = new ServerInstance(); // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated // console.log('Congratulations, your extension "vscode-express" is now active!'); // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json context.subscriptions.push(server); context.subscriptions.push(vscode.commands.registerCommand('express.hostWorkspace', portNumber => { const config = getCustomConfiguration(), wwwRoot = vscode.workspace.rootPath; portNumber = (typeof portNumber === 'number' || typeof portNumber === 'string') ? portNumber : (config.portNumber || 80); if (!wwwRoot) { return vscode.window.showErrorMessage('Please open a folder or workspace before starting Express server'); } return server .start( portNumber, path.resolve(wwwRoot, config.relativeRoot || '.'), typeof config.showOutput === 'boolean' ? config.showOutput : true ) .then( () => { !config.omitInformationMessage && vscode.window.showInformationMessage(`Express server is started and listening to port ${portNumber}`); return portNumber; }, err => { if (err.message === 'already started') { vscode.window.showErrorMessage('Express server is already running'); } else if (err.code === 'EADDRINUSE') { vscode.window.showErrorMessage(`Port number ${portNumber} is already in use`); } else { vscode.window.showErrorMessage(err.message); } throw err; } ); })); context.subscriptions.push(vscode.commands.registerCommand('express.hostWorkspaceAndOpenInBrowser', portNumber => { const config = getCustomConfiguration(); portNumber = (typeof portNumber === 'number' || typeof portNumber === 'string') ? portNumber : (config.portNumber || 80); vscode.commands .executeCommand('express.hostWorkspace', portNumber) .then(portNumber => openInBrowser(portNumber)); })); context.subscriptions.push(vscode.commands.registerCommand('express.hostWorkspaceWithRandomPort', () => { vscode.commands.executeCommand( 'express.hostWorkspace', getRandomPortNumberFromConfiguration() ); })); context.subscriptions.push(vscode.commands.registerCommand('express.hostWorkspaceWithRandomPortAndOpenInBrowser', () => { vscode.commands.executeCommand( 'express.hostWorkspaceAndOpenInBrowser', getRandomPortNumberFromConfiguration() ); })); context.subscriptions.push(vscode.commands.registerCommand('express.stopServer', () => { const config = getCustomConfiguration(), timeout = setTimeout(() => { !config.omitInformationMessage && vscode.window.showInformationMessage('Express server is stopping, it may take a while'); }, 1000); server .stop() .then( () => { clearTimeout(timeout); !config.omitInformationMessage && vscode.window.showInformationMessage('Express server has been stopped'); }, err => { clearTimeout(timeout); vscode.window.showWarningMessage('Express server is not running'); throw err; } ); })); context.subscriptions.push(vscode.commands.registerCommand('express.openInBrowser', () => { const portNumber = server.portNumber; if (portNumber) { openInBrowser(portNumber); } else { vscode.window.showErrorMessage('No Express server is running'); } })); context.subscriptions.push(vscode.commands.registerCommand('express.showOutput', () => { server.showOutputChannel(); })); } exports.activate = activate; // this method is called when your extension is deactivated function deactivate() { } exports.deactivate = deactivate; function getCustomConfiguration() { return vscode.workspace.getConfiguration('express') || {}; } function openInBrowser(portNumber) { open(`http://localhost:${portNumber}/`); } function getRandomPortNumberFromConfiguration() { const config = getCustomConfiguration(), randomPortNumber = config.randomPortNumber; return getRandomPortNumber(randomPortNumber.min, randomPortNumber.max); } function getRandomPortNumber(min, max) { return Math.min(min, max) + Math.floor(Math.random() * (Math.abs(max - min) + 1)); }import React, {Component} from 'react'; import {Meteor} from 'meteor/meteor'; import {Redirect} from 'react-router-dom'; import Loader from '../components/Loader'; // Creates a new prototype, passes the new prototype id to state. // Then, redirects to the new prototype from id in state. class NewPrototypePage extends Component { constructor(props) { super(props); this.state = { newId: null, }; } componentDidMount() { Meteor.call( 'newPrototype', { createdAt: Date.now(), owner: Meteor.userId(), }, (err, id) => { if (id) { console.log(`New prototype id: ${id}`); return this.setState({newId: id}); } }, ); } render() { if (this.state.newId) { return <Redirect to={`/${this.state.newId}`} />; } else { return <Loader />; } } } export default NewPrototypePage; function calculate(obj){ console.log("cal"); var salary_amount = document.getElementById('salary_amount').value; var dedution = document.getElementById('dedution').value; console.log(dedution); var amt = salary_amount-dedution; document.getElementById('net-pay').value = amt; }<reponame>bitexgg/bitexgg<gh_stars>0 "use strict"; process.on('uncaughtException', function (err) { console.error('uncaughtException', err); process.exit(1); }); process.setMaxListeners(0); require('events').EventEmitter.defaultMaxListeners = 0; process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; const dotenv = require('dotenv'); const test = require('./test'); const result = dotenv.config({path: '/home/admin/rc.conf'}); if (result.error) { throw result.error; } //const db_config = require('./cfg.js'); //const config = require('./config.js'); const main = require('./lib_main.js'); const io = main.get_io(); //const discord = require('./discord.js'); let https_server; const express = require('express'); // >>> http const express_server = express(); const https = require('https'); const helmet = require('helmet'); const bodyParser = require("body-parser"); const cookieParser = require('cookie-parser'); const session = require('express-session'); let session_server, sessionStore; const ipCountry = require('ip-country'); const compression = require('compression'); const FileStore = require('session-file-store')(session); //const app_socket_io = require('./libsocket.io.js'); //let socket; let cfg = {}; // global config const port = process.env.HTTPS_PORT || 9439; const url = require('url'); // <<< http let site_config = {}; let sid_by_host = {}; let site_cache_status = {}; let site_cache_refresh = false; function fullUrl(req) { return url.format({ protocol: req.protocol, host: req.get('host'), pathname: req.originalUrl }); } function c_country() { express_server.use((req, res, next) => { res.locals.ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; next() }); express_server.use(ipCountry.setup({ mmdb: './mmdb/GeoLite2-Country.mmdb', fallbackCountry: 'US', exposeInfo: false })); } function https_init() { cfg.COOKIE_SECRET = io.cfg('SECRET'); console.log('cfg.COOKIE_SECRET', cfg.COOKIE_SECRET); sessionStore = new FileStore({path: '/tmp', ttl: 999999}); express_server.use(bodyParser.urlencoded({extended: true, verify:function(req,res,buf){ req.rawBody = buf; } })); express_server.use(helmet());// express_server.set('trust proxy', 1); // trust first proxy express_server.set('json spaces', 40); express_server.set('view engine', 'ejs'); express_server.use(express.static('/backend/public_html')); express_server.use(cookieParser(cfg.COOKIE_SECRET, { secure: true, path: '/', maxAge: 99999999, expires: new Date(2050) })); session_server = session({ secret: cfg.COOKIE_SECRET, store: sessionStore, proxy: true, resave: true, saveUninitialized: true }); express_server.use(session_server); express_server.use(function (req, res, next) { if (!req.session) { return next(new Error('WARNING-SESSION-ERROR')); } next(); }); express_server.use(compression()); express_server.use(function (req, res, next) { res.removeHeader('X-Powered-By'); const host = req.headers.host; const host_x = req.headers['x-forwarded-for'] || req.connection.remoteAddress; const agent = req.headers['user-agent']; const lang = req.headers["accept-language"]; console.log(lang, '/', host, '/', host_x, '/', agent); if (lang) { /* if( lang.split(',')[0] == 'pt-BR' ) { return res.status(404).send('Not found'); } */ } next(); }); /* express_server.use(function (req, res, next) { res.header('Content-Type', 'application/json'); next(); }); */ express_server.use(function (req, res, next) { if (req.session && req.session.impersonate) { req.user = req.session.impersonate; } next(); }); c_country(); const options = {}; options.cert = io.cat('/backend/tls/server-cert.pem'); options.key = io.cat('/backend/tls/server-key.pem'); options.ca = io.cat('/backend/tls/ca.pem'); if (!server_is_online) { https_server = https.createServer(options, express_server); https_server.on('clientError', (err, socket) => { console.log('clientError', err); }); https_server.on('error', (err) => { console.log('error', err); }); https_server.listen(port, site_setup_init); } else { site_setup_init(); } } let server_is_online = false; function site_setup_init(cfg) { if (!https_server) { io.red('!server'); return; } server_is_online = true; const server_url = 'https://localhost:' + https_server.address().port; io.green(server_url); //express_server.get('/rpc/v1/:app', main.api_call); //express_server.post('/rpc/v1/:app', main.api_call); main.routers(express_server); //test_exec(io, server_url); socket_io_setup(); express_server.use(function (req, res) { const url = fullUrl(req); const s = 'NOT FOUND: ' + url; io.red(s); res.status(404).send(s); }); } function socket_io_setup() { return console.log('DISABLED: socket_io_setup'); io.magenta('socket.io'); socket = require('socket.io')(https_server); socket.use(function (socket, next) { session_server(socket.request, {}, next); }); lib_socket_io.init(io, express_server, cfg); socket.on('connection', lib_socket_io.connection); } function test_exec(io, server_url) { test.init(io, server_url); test.newAccount(); } main.init(https_init);<reponame>kwnie/scribble-stadium-fe import { LandingPage } from '../components/pages/LandingPage'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from 'redux-mock-store'; const mockStore = configureStore([]); const store = mockStore(); Object.defineProperty(window, 'matchMedia', { writable: true, value: jest.fn().mockImplementation(query => ({ matches: false, media: query, onchange: null, addListener: jest.fn(), // Deprecated removeListener: jest.fn(), // Deprecated addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), })), }); const Component = () => { return ( <Provider store={store}> <LandingPage /> </Provider> ); }; describe('<LandingPage /> test suite', () => { test('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<Component />, div); }); }); // Import modules const querystring = require('querystring'); const httpsRequest = require('./HttpsRequest'); const Promise = require('bluebird'); const instaAccessToken = process.env.INSTAGRAM_ACCESS_TOKEN; function getMediaById(mediaID) { // JSON Object of POST data const getMediaJSON = { access_token: instaAccessToken, }; // Stringify JSON and set header options const getMediaString = querystring.stringify(getMediaJSON); const options = { hostname: 'api.instagram.com', path: `/v1/media/${mediaID}?${getMediaString}`, method: 'GET', }; // Send request return httpsRequest(options, undefined); } function getMedias(minID, maxID, count) { // JSON Object of POST data const getMediasJSON = { access_token: instaAccessToken, // includes media with minID min_id: minID, // excludes media with maxID max_id: maxID, count: count > 1 ? count - 1 : count, }; // Stringify JSON and set header options const getMediasString = querystring.stringify(getMediasJSON); const options = { hostname: 'api.instagram.com', path: `/v1/users/self/media/recent/?${getMediasString}`, method: 'GET', }; const medias = count > 1 || !count ? httpsRequest(options, undefined) : getMediaById(maxID); const mediaMaxID = maxID && count > 1 ? getMediaById(maxID) : '{ "meta": { "code": 200 }, "data": [] }'; // Send request return Promise.all([ medias, mediaMaxID, ]); } module.exports = { getMediaById, getMedias, }; /** * Definition for singly-linked list with a random pointer. * function RandomListNode(label) { * this.label = label; * this.next = this.random = null; * } */ /** * @param {RandomListNode} head * @return {RandomListNode} */ var copyRandomList = function(head) { if (!head) return null; let curr = head; let newNode; while (curr) { newNode = new RandomListNode(curr.label); newNode.next = curr.next; curr.next = newNode; curr = newNode.next; } curr = head; let random; while (curr) { random = curr.random; newNode = curr.next; newNode.random = random && random.next; curr = newNode && newNode.next; } let newHead = head.next; const curr2 = newHead; curr = head; while (curr) { curr.next = curr.next.next; newHead.next = newHead.next && newHead.next.next; curr = curr.next; newHead = newHead.next; } return curr2; };import { expect, use } from 'chai' import { fiddle } from '../../../src/pixel/fiddler' import { hashEmail } from '../../../src/utils/hash' import dirtyChai from 'dirty-chai' use(dirtyChai) describe('Fiddler', () => { it('should use the providedHash if present', function () { const pixelData = { eventSource: { email: '75524519292E51AD6F761BAA82D07D76' } } const result = fiddle(pixelData) expect(result.hashedEmail).to.eql(['75524519292e51ad6f761baa82d07d76']) }) it('should use the providedHash if present, ignoring the case of the key', function () { const pixelData = { eventSource: { eMaIl: '75524519292E51AD6F761BAA82D07D76' } } const result = fiddle(pixelData) expect(result.hashedEmail).to.eql(['75524519292e51ad6f761baa82d07d76']) }) it('should ignore the providedHash if it is not a valid hash', function () { const pixelData = { eventSource: { email: '75524519292e51ad6f761baa82d07d76aa' } } const result = fiddle(pixelData) expect(result.hashedEmail).to.eql(undefined) }) it('should work while ignoring whitespace ', function () { const pixelData = { eventSource: { email: ' 75524519292E51AD6F761BAA82D07D76' } } const result = fiddle(pixelData) expect(result.hashedEmail).to.eql(['75524519292e51ad6f761baa82d07d76']) }) it('should use the first found hash, even if there are multiple HASH_BEARERS provided', function () { const hashes = hashEmail('<EMAIL>') const pixelData = { eventSource: { email: hashes.md5, hash: hashes.sha1, hashedemail: hashes.sha256 } } const result = fiddle(pixelData) expect(result.hashedEmail).to.eql([hashes.md5]) }) it('should hash the plain text email if the providedHash if it is not a valid hash', function () { const pixelData = { eventSource: { emailHash: '75524519292e51ad6f761baa82d07d76aa', email: '<EMAIL>' } } const result = fiddle(pixelData) const hashes = hashEmail('<EMAIL>') expect(result.hashedEmail).to.eql([hashes.md5, hashes.sha1, hashes.sha256]) }) it('should hash the plain text url encoded email as if it contained an @ symbol', function () { const pixelData = { eventSource: { email: 'mookie%40gmail.com' } } const result = fiddle(pixelData) const hashes = hashEmail('<EMAIL>') expect(result.hashedEmail).to.eql([hashes.md5, hashes.sha1, hashes.sha256]) }) it('should hash the plain text url encoded email as if it contained an @ symbol, ignoring the surrounding mess or case', function () { const pixelData = { eventSource: { email: '" mOOkie%40gmail.com "' } } const result = fiddle(pixelData) const hashes = hashEmail('<EMAIL>') expect(result.hashedEmail).to.eql([hashes.md5, hashes.sha1, hashes.sha256]) }) it('should limit the number of items in the items array, regardless of the case', function () { expect(fiddle({ eventSource: { iTeMs: Array.from(Array(50).keys()) } }).eventSource.iTeMs).to.eql(Array.from(Array(10).keys())) expect(fiddle({ eventSource: { iTeMIdS: Array.from(Array(20).keys()) } }).eventSource.iTeMIdS).to.eql(Array.from(Array(10).keys())) }) }) <gh_stars>1-10 function Flow(inst, dispatch) { var running = false, intv, current = null, list = [], history = [], historyLimit = 10, uniqueMethods = {}, execStartTime, execEndTime, timeouts = {}, consoleMethodStyle = "color:#666666;"; function getMethodName(method) { // TODO: there might be a faster way to get the function name. return method.toString().split(/\b/)[2]; } function createItem(method, args, delay) { return {label: getMethodName(method), method: method, args: args || [], delay: delay}; } function unique(method) { var name = getMethodName(method); uniqueMethods[name] = method; } function clearSimilarItemsFromList(item) { var i = 0, len = list.length; while (i < len) { if (list[i].label === item.label && list[i] !== current) { inst.log("clear duplicate item %c%s", consoleMethodStyle, item.label); list.splice(i, 1); i -= 1; len -= 1; } i += 1; } } function add(method, args, delay) { var item = createItem(method, args, delay), index = -1; if (uniqueMethods[item.label]) { clearSimilarItemsFromList(item); } list.push(item); if (running) { next(); } } // this puts it right after the one currently running. function insert(method, args, delay) { list.splice(1, 0, createItem(method, args, delay)); } function remove(method) { clearSimilarItemsFromList({label: getMethodName(method)}); } function timeout(method, time) { var intv, item = createItem(method, [], time), startTime = Date.now(), timeoutCall = function () { inst.log("exec timeout method %c%s %sms", consoleMethodStyle, item.label, Date.now() - startTime); method(); }; inst.log("wait for timeout method %c%s", consoleMethodStyle, item.label); intv = setTimeout(timeoutCall, time); timeouts[intv] = function () { clearTimeout(intv); delete timeouts[intv]; }; return intv; } function stopTimeout(intv) { if (timeouts[intv]) timeouts[intv](); } function getArguments(fn) { var str = fn.toString(), match = str.match(/\(.*\)/); return match[0].match(/([\$\w])+/gm); } function hasDoneArg(fn) { var args = getArguments(fn); return !!(args && args.indexOf('done') !== -1); } function done() { execEndTime = Date.now(); inst.log("finish %c%s took %dms", consoleMethodStyle, current.label, execEndTime - execStartTime); current = null; addToHistory(list.shift()); if (list.length) { next(); } return execEndTime - execStartTime; } // Keep a history of what methods were executed for debugging. Keep up to the limit. function addToHistory(item) { history.unshift(item); while (history.length > historyLimit) { history.pop(); } } function next() { if (!current && list.length) { current = list[0]; if (inst.async && current.delay !== undefined) { inst.log("\tdelay for %c%s %sms", consoleMethodStyle, current.label, current.delay); clearTimeout(intv); intv = setTimeout(exec, current.delay); } else { exec(); } } } function exec() { inst.log("start method %c%s", consoleMethodStyle, current.label); var methodHasDoneArg = hasDoneArg(current.method); if (methodHasDoneArg) current.args.push(done); execStartTime = Date.now(); current.method.apply(null, current.args); if (!methodHasDoneArg) done(); } function run() { running = true; next(); } function clear() { var len = current ? 1 : 0, item; inst.log("clear"); while (list.length > len) { item = list.splice(len, 1)[0]; inst.log("\tremove %s from flow", item.label); } } function length() { return list.length; } function destroy() { clearTimeout(intv); list.length = 0; inst = null; } inst = exports.logWrapper('Flow', inst || {}, 'grey', dispatch); inst.async = Object.prototype.hasOwnProperty.apply(inst, ['async']) ? inst.async : true; inst.debug = Object.prototype.hasOwnProperty.apply(inst, ['debug']) ? inst.debug : 0; inst.insert = insert; inst.add = add; inst.unique = unique; inst.remove = remove; inst.timeout = timeout; inst.stopTimeout = stopTimeout; inst.run = run; inst.clear = clear; inst.length = length; inst.destroy = destroy; return inst; } exports.datagrid.Flow = Flow;class NetworkAdapter { constructor() { this.__adapters = { fetch: new FetchAdapter(), s3: new S3Adapter(), }; } async getTextFileContents(inputs) { const { adapter, key: adapterKey } = this.__getAdapterToUse(inputs); let adapterInputs = []; switch (adapterKey) { case "fetch": const { url } = inputs; adapterInputs = [url]; break; default: throw new Error( `${adapterKey}'s adapter hasn't been implemented yet for this method` ); } return await adapter.getTextFileContents(...adapterInputs); } async getJsonFileAsJsObj(inputs) { const { adapter, key: adapterKey } = this.__getAdapterToUse(inputs); let adapterInputs = []; switch (adapterKey) { case "fetch": const { url } = inputs; adapterInputs = [url]; break; case "s3": const { bucket, filename } = inputs; adapterInputs = [{ bucket: bucket, key: filename }]; break; default: throw new Error( `${adapterKey}'s adapter hasn't been implemented yet for this method` ); } return await adapter.getJsonFileAsJsObj(...adapterInputs); } async setJsObjIntoJsonFile(inputs) { const { adapter, key: adapterKey } = this.__getAdapterToUse(inputs); let adapterInputs = []; switch (adapterKey) { case "s3": const { bucket, filename, obj } = inputs; adapterInputs = [{ bucket: bucket, key: filename }, obj]; break; default: throw new Error( `${adapterKey}'s adapter hasn't been implemented yet for this method` ); } return await adapter.setJsObjIntoJsonFile(...adapterInputs); } __getAdapterToUse(inputs) { if ("url" in inputs) { return { key: "fetch", adapter: this.__adapters.fetch }; } if ("bucket" in inputs) { return { key: "s3", adapter: this.__adapters.s3 }; } throw new Error("Unrecognized inputs: ", inputs); } } class FetchAdapter { constructor() { this.__fetch = require("node-fetch"); } async getTextFileContents(url) { const res = await this.__fetch(url); return await res.text(); } async getJsonFileAsJsObj(url) { const res = await this.__fetch(url); return await res.json(); } } class S3Adapter { constructor() { const S3 = require("aws-sdk/clients/s3"); this.__s3 = new S3(); } async getJsonFileAsJsObj(storageIdentifiers) { const { bucket, key } = storageIdentifiers; const res = await this.__s3 .getObject({ Bucket: bucket, Key: key, }) .promise(); const json = res?.Body?.toString(); if (!json) { throw new Error("Response from AWS get request to S3 bucket was empty"); } const jsObj = JSON.parse(json); return jsObj; } async setJsObjIntoJsonFile(storageIdentifiers, jsObj) { const { bucket, key } = storageIdentifiers; const json = JSON.stringify(jsObj, null, 4); await this.__s3 .putObject({ Bucket: bucket, Key: key, Body: json, }) .promise(); //This does return a currently unused response object } } function createNetworkAdapter() { return new NetworkAdapter(); } module.exports = { createNetworkAdapter: createNetworkAdapter, }; import ResponsiveField from '@apps/websites/admin/components/responsivefield' import SpacingField from '@apps/websites/admin/components/spacingfield' import React from 'react' export const Margin = (props) => <ResponsiveField { ...props } component={ SpacingField } /> export const Padding = (props) => <ResponsiveField { ...props } component={ SpacingField } /> export const SpacingSection = (config, device, website) => ({ label: 'Spacing', collapsing: true, collapsed: true, fields: [ { label: 'Margin', name: 'styles.margin', device, type: Margin, value: config.styles.margin }, { label: 'Padding', name: 'styles.padding', device, type: Padding, value: config.styles.padding } ] }) /* Copyright 2018 <NAME> (<EMAIL>) 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. */ var currentMap; function initializeMap() { // Only show the overview map at first $("#mainMapShow").hide(); $("#confcentermap").hide(); $("#exhibithallmap").hide(); $("#mainMapShow").hide(); // Activate the return to overview button $("#mainMapShow_button").click(function (event) { clickMainMapShow(event.target); }); // Activate the click spots $("#confcenter-click").click(function (event) { clickConfCenter(event.target); }); } function clickConfCenter (tgt) { // hide the main map $("#overviewmap").hide(); // show the conf center map $("#confcentermap").show(400); $("#mapName").text("Conference Center Detail"); // Show the back button currentMap = "#confcentermap"; $("#mainMapShow").show(); } function clickMainMapShow(tgt) { // hide the currentMap $(currentMap).hide(); $("#mapName").text("Convention Center Overview"); // hide the button $("#mainMapShow").hide(); // show the map $("#overviewmap").show(400); } // import firebase from "@/firebase"; import axios from "axios"; import createConfig from '../helpers/api-auth'; export default { async fetchProducts(context, page) { try { if (context.state.products && context.state.products.current === page) { return; } context.commit("SET_PRODUCT_LOADING", true); if (!localStorage.AUTH_TOKEN) { return; } let res = await axios.get( `/api/v1/products?page=${page}`, createConfig() ); context.commit("SET_PRODUCTS", res.data.products); res = await axios.get(`/api/v1/products/combos`, createConfig()); context.commit('SET_FOOD_COMBOS', res.data); context.commit("SET_PRODUCT_LOADING", false); } catch (e) { console.log(e); } }, async fetchSingleProduct(context, id) { context.commit("SET_VIEW_PRODUCT_FETCHING", true); try { const res = await axios.get( "/api/v1/view/product/" + id, createConfig() ); if (!res.data.product) { context.commit("SET_SINGLE_VIEW_PRODUCT", null); } else { context.commit("SET_SINGLE_VIEW_PRODUCT", res.data.product); } } catch (e) { context.commit("SET_SINGLE_VIEW_PRODUCT", null); } context.commit("SET_VIEW_PRODUCT_FETCHING", false); }, async fecthSearchResults(context, query) { try { const res = await axios.get('/api/v1/products/search?' + query, createConfig()); if(res.status === 200) { context.commit('SET_SEARCH_PRODUCT_RESULTS', res.data); } } catch (error) { console.log(error); } } }(function(tree) { tree.URL = function URL(val, paths) { if (val.data) { this.attrs = val; } else { // Add the base path if the URL is relative and we are in the browser if (!/^(?:https?:\/|file:\/)?\//.test(val.value) && paths.length > 0 && typeof(process) === 'undefined') { val.value = paths[0] + (val.value.charAt(0) === '/' ? val.value.slice(1) : val.value); } this.value = val; this.paths = paths; this.is = 'uri'; } }; tree.URL.prototype = { toString: function() { return this.value.toString(); }, eval: function(ctx) { if (/^https?:/.test(this.value.toString())) { var crypto = require('crypto'), path = require('path'); var uri = this.value.toString(); var eventual_location = path.join( ctx.data_dir, crypto.createHash('md5').update(uri).digest('hex') + path.extname(uri)); ctx.deferred_externals.push(this.value.toString()); return this.attrs ? this : new tree.URL(eventual_location, this.paths); } else { return this.attrs ? this : new tree.URL(this.value.eval(ctx), this.paths); } } }; })(require('carto/tree')); <gh_stars>0 export const loadState = () => { const stateDefault = { visibleMenu: 'MENU_UNLOGGED', token: '' }; try { const serializedState = localStorage.getItem('state'); if (null === serializedState) { return stateDefault; } return JSON.parse(serializedState); } catch (error) { return stateDefault; } }; export const saveState = state => { try { const serializedState = JSON.stringify(state); localStorage.setItem('state', serializedState); } catch (error) { } };const rollup = require('rollup') const npm = require('rollup-plugin-node-resolve') const buble = require('rollup-plugin-buble') const commonjs = require('rollup-plugin-commonjs') const multiEntry = require('rollup-plugin-multi-entry') rollup.rollup({ entry: 'test/client/*.js', plugins: [ npm({jsnext: true}), buble(), commonjs(), multiEntry() ] }) .then(bundle => { bundle.write({format: 'iife', moduleName: 'businessman', dest: 'dist/test-businessman.js'}) }) .catch(err => { console.error(err) }) rollup.rollup({ entry: 'test/worker.js', plugins: [ npm({jsnext: true}), buble(), commonjs() ] }) .then(bundle => { bundle.write({format: 'iife', dest: 'dist/test-worker.js'}) }) .catch(err => { console.error(err) }) <filename>src/utils/db.js import levelup from 'levelup'; import leveljs from 'level-js'; import encode from 'encoding-down'; const db = levelup(encode(leveljs('tigo'), { valueEncoding: 'json' })); export default db; import React, {Component, PropTypes} from 'react'; import {StyleSheet, Text, ListView, TouchableOpacity} from 'react-native'; import gql from 'graphql-tag'; import {graphql} from 'react-apollo'; // Presentational Component class Conversations extends Component { static propTypes = { threads: PropTypes.arrayOf(PropTypes.object), onSelectThread: PropTypes.func, } static defaultProps = { onSelectThread: thread => console.log('Got no handler but thread was pressed with id', thread && thread.id), } constructor() { super(); this.renderRow = this.renderRow.bind(this); this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); } renderRow(rowData) { return rowData && rowData.title && ( <TouchableOpacity style={styles.row} onPress={() => this.props.onSelectThread(rowData)}> <Text style={[styles.largeText]}> {rowData.title} </Text> <Text style={[styles.smallText]}> {rowData.lastMessage} </Text> </TouchableOpacity> ); } render() { return ( <ListView dataSource={this.ds.cloneWithRows(this.props.threads)} renderRow={this.renderRow} enableEmptySections /> ); } } const styles = StyleSheet.create({ row: { height: 50, justifyContent: 'center', paddingHorizontal: 20, }, largeText: { fontSize: 20, }, smallText: { fontSize: 15, }, }); // Apollo Container const THREADS_QUERY = gql` query threads { threads { _id title handle lastMessageTime lastMessage } } `; const ConversationsWithData = graphql(THREADS_QUERY, { props: ({data: {threads = []}}) => ({ threads }) })(Conversations); export default ConversationsWithData; <filename>src/components/PublicList.js //Public list of particular user import {useState, useEffect} from 'react' const PublicList = (props) => { const user_id = props.location.state.id const [itemDetails, setItemDetails] = useState([]) const [userDetails, setUserDetails] = useState({}) const getUserList = async() => { const response = await fetch('https://bingeme.herokuapp.com/api/dashboard/public/'+user_id, { method: 'GET', mode: 'cors', headers : { 'Content-Type': 'applicaiton/json' } }) const res = await response.json() console.log(res) setItemDetails(res[0].itemList) } const getUserDetails = async() => { const response = await fetch('https://bingeme.herokuapp.com/api/user/userDetails/'+user_id, { method: 'GET', mode: 'cors', headers : { 'Content-Type': 'application/json' } }) const res = await response.json() const user = { username: res.username, aboutMe: res.aboutMe } setUserDetails(user) } useEffect(()=>{ getUserList() getUserDetails() },[]) return ( <div> <div className="jumbotron jumbotron-fluid text-center"> <div className="container"> <h1 className="display-4">{userDetails.username}</h1> <p className="lead">{userDetails.aboutMe}</p> </div> </div> <div className="container"> <div className="list-group"> {itemDetails.map(item=>{ return <a href="#" className="list-group-item list-group-item-action flex-column align-items-start"> <div className="d-flex w-100 justify-content-between"> <h5 className="mb-1">{item.name}</h5> <small>{item.genre}</small> </div> <p className="mb-1">{item.platform}, {item.score}, {item.review}</p> <small>Number of mentions</small> </a> })} </div> </div> </div> ) } export default PublicList<filename>web/statics/js/edit-address.js var Name = "" var Address = "" /*$(window).load(function() { GetDefaultData() });*/ function GetDefaultData(){ Name = $("#address-name").val() Address = $("#address-field").val() jsonOBJ = '{"Address":"' + Address + '"}' postRequest("get-address", jsonOBJ, function(resp){ obj = JSON.parse(resp) if (obj.Error != "none") { $("#balance-container").text("Can not find the addresses in address book") } else { if(obj.Content.Address.startsWith("FA")) { $("#balance").text(FCTNormalize(obj.Content.Balance)) } else { $("#balance").text(obj.Content.Balance) } } }) } $("#display-private-key").click(function(){ jsonOBJ = '{"Address":"' + Address + '"}' postRequest("display-private-key", jsonOBJ, function(resp){ obj = JSON.parse(resp) if (obj.Error != "none") { $("#private-key-field").val(obj.Error) SetGeneralError("Error: " + obj.Error) } else { $("#private-key-field").val(obj.Content) } }) }) $("#save-name-change").click(function(){ NewName = $("#address-name").val() jsonOBJ = '{"Address":"' + Address + '", "Name":"' + NewName + '"}' if (NewName != Name) { postRequest("address-name-change", jsonOBJ, function(resp){ obj = JSON.parse(resp) if (obj.Error != "none") { SetGeneralError("Error: " + obj.Error) } else { SetGeneralSuccess(obj.Content + ": The name has been changed") } }) } else { SetGeneralError("Newname is the same as the original") } }) $("#delete-address").on('click', function(){ name = $("#address-name").val() jsonOBJ = '{"Address":"' + Address + '", "Name":"' + name + '"}' postRequest("delete-address", jsonOBJ, function(resp){ obj = JSON.parse(resp) if (obj.Error != "none") { SetGeneralError("Error: " + obj.Error) } else { SetGeneralSuccess(obj.Content + ": The name has been changed") } }) }) $("#copy-to-clipboard").on('click', function(){ var aux = document.createElement("input"); //console.log($('#selected-address-info').val()) aux.setAttribute("value", $('#private-key-field').val()); document.body.appendChild(aux); aux.select(); document.execCommand("copy"); document.body.removeChild(aux); }) export default { name: "TheLoginComponent", template: ` <div class="container"> <div> <h1 class="welcome">Welcome to Flashback</h1> <p class="opener">Log in below to get transported back in time to all your old favourite movies, tv shows, and albums!</p> <form> <div class="namebar form-row"> <div class=" bars"> <label class="hidden" for="InputName">Name</label> <input v-model="input.username" type="text" class="form-control" id="InputName" placeholder="username" required> </div> <div class=" bars"> <label class="hidden" for="FormPassword">Name</label> <input v-model="input.password" type="password" class="form-control" id="FormPassword" placeholder="password" required> </div> <div class="col-auto my-1"> <button v-on:click.prevent="login()" type="submit" class="btn btn-primary go">Go!</button> </div> </div> </form> </div> </div> `, data() { return { input: { username: "", password: "" }, } }, methods: { login() { if(this.input.username !="" && this.input.password !=""){ let loginData = JSON.stringify({username: this.input.username, password: this.input.password}); let url = `/ums/admin/login`; fetch(url, { method: 'POST', body: loginData, headers: { 'Accept': 'application/json, text/plain, */*', 'Content-type': 'application/json' } }) .then(res => res.json()) .then(data => { if(data.message){ console.warn("user doesnt exist or something else broke"); }else{ data.user_name = this.input.username; this.$router.replace({name: "users"}); } }) .catch((err) => console.error(err)); } else{ //dont do the login stuff for reasons console.log("A username and password need to be entered"); } } } }"use strict"; const tiptoe = require("./index"); tiptoe( function step1() { return "a"; }, function step2(a) { console.log(a); this(null, "b"); this(null, "SHOULD NOT SEE1"); this(null, "SHOULD NOT SEE2"); this(null, "SHOULD NOT SEE3"); this(null, "SHOULD NOT SEE4"); this(null, "SHOULD NOT SEE5"); }, function step3(b) { console.log(b); this(undefined, "c"); this(null, "SHOULD NOT SEE6"); }, function finish(err, c) { console.log(c); process.exit(0); } ); import Tooltip from './Tooltip'; import './style/index.less'; export default Tooltip; export function canJsonParse(str) { try { let testValueForJson = JSON.parse(str) return testValueForJson ? true : false } catch (e) { // exception: string is not valid json return null } } export function getKnownSyntaxHighlighterLanguage(val) { // to start, only check for json. can expand as needed in future const isValidJson = canJsonParse(val) return isValidJson ? "json" : null } <filename>grunt.js var _ = require('underscore'); var fs = require('fs'); // Haha, this is so tricky. so we have a template for index.html to stick // in the hashed JS and style files -- that template also contains // templates used in the app. in order to avoid evaluating those // templates, we change the regexes so we can effectively nest templates _.templateSettings.interpolate = /\{\{(.+?)\}\}/g; _.templateSettings.escape = /\{\{\{(.*?)\}\}\}/g; _.templateSettings.evaluate = /\{\{-(.*?)\}\}/g; // precompile for speed var indexFile = fs.readFileSync('src/template.index.html').toString(); var indexTemplate = _.template(indexFile); /*global module:false*/ module.exports = function(grunt) { // eventually have sound...? grunt.registerTask('compliment', 'Stay motivated!', function() { var defaults = ['Awesome!!']; var compliments = grunt.config('compliment.compliments') || defaults; var index = Math.floor(Math.random() * compliments.length); grunt.log.writeln(compliments[index]); }); grunt.registerTask('lintStrings', 'Find if an INTL string doesnt exist', function() { var child_process = require('child_process'); var output = child_process.exec('node src/js/intl/checkStrings', function(err, output) { grunt.log.writeln(output); }); }); grunt.registerTask('buildIndex', 'stick in hashed resources', function() { grunt.log.writeln('Building index...'); // first find the one in here that we want var buildFiles = fs.readdirSync('build'); var hashedMinFile; if (buildFiles.length == 2) { grunt.log.writeln('Assuming debug mode wanted'); hashedMinFile = 'bundle.js'; } var jsRegex = /bundle\.min\.\w+\.js/; _.each(buildFiles, function(jsFile) { if (jsRegex.test(jsFile)) { if (hashedMinFile) { throw new Error('more than one hashed file: ' + jsFile + hashedMinFile); } hashedMinFile = jsFile; } }); if (!hashedMinFile) { throw new Error('no hashed min file found!'); } grunt.log.writeln('Found hashed js file: ' + hashedMinFile); var styleRegex = /main\.\w+\.css/; var hashedStyleFile; _.each(buildFiles, function(styleFile) { if (styleRegex.test(styleFile)) { if (hashedStyleFile) { throw new Error('more than one hashed style: ' + styleFile + hashedStyleFile); } hashedStyleFile = styleFile; } }); if (!hashedStyleFile) { throw new Error('no style found'); } grunt.log.writeln('Found hashed style file: ' + hashedStyleFile); // output these filenames to our index template var outputIndex = indexTemplate({ jsFile: hashedMinFile, styleFile: hashedStyleFile }); fs.writeFileSync('index.html', outputIndex); }); grunt.initConfig({ lint: { files: ['grunt.js', 'src/**/*.js', 'spec/*.js'] }, compliment: { compliments: [ "Wow peter great work!", "Such a professional dev environment", "Can't stop the TRAIN", "git raging" ] }, hash: { src: ['build/bundle.min.js', 'src/style/main.css'], dest: 'build/' }, jasmine_node: { specNameMatcher: 'spec', // load only specs containing specNameMatcher projectRoot: '.', forceExit: true, verbose: true }, watch: { files: '<config:lint.files>', tasks: 'watching' }, min: { dist: { src: ['build/bundle.js'], dest: 'build/bundle.min.js' } }, rm: { build: 'build/*' }, shell: { gitAdd: { command: 'git add build/' } }, jshint: { options: { curly: true, // sometimes triple equality is just redundant and unnecessary eqeqeq: false, // i know my regular expressions regexp: false, // i think it's super weird to not use new on a constructor nonew: false, // these latedefs are just annoying -- no pollution of global scope latedef: false, // use this in mocks forin: false, /////////////////////////////// // All others are true ////////////////////////////// immed: true, newcap: true, noarg: true, bitwise: true, sub: true, undef: true, unused: false, trailing: true, devel: true, jquery: true, nonstandard: true, boss: true, eqnull: true, browser: true, debug: true }, globals: { Raphael: true, require: true, console: true, describe: true, expect: true, it: true, exports: true, process: true } }, browserify: { 'build/bundle.js': { entries: ['src/**/*.js', 'src/js/**/*.js'] //prepend: ['<banner:meta.banner>'], } } }); // all my npm helpers grunt.loadNpmTasks('grunt-jslint'); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-jasmine-node'); grunt.loadNpmTasks('grunt-hash'); grunt.loadNpmTasks('grunt-rm'); grunt.loadNpmTasks('grunt-shell'); grunt.registerTask('build', 'rm browserify min hash buildIndex shell'); grunt.registerTask('fastBuild', 'rm browserify hash buildIndex shell'); grunt.registerTask('default', 'lint lintStrings jasmine_node build compliment'); grunt.registerTask('watching', 'fastBuild lint lintStrings'); grunt.registerTask('test', 'jasmine_node'); }; /** * This module contains helper functions that convert values. */ module.exports = { /** * Converts kWh to Ws and returns result as string. * @param {number | string} kWh * @returns {string} The converted kWh in Ws as a string. */ kWhToWs: kWh => { const kWhToWs = 3600000; let ws = kWh * kWhToWs; return (Math.round(ws)).toString(); }, /** * Converts kWh to Ws and returns result as string. * @param {number | string} ws * @returns {number} The converted Ws in kWh as a string. */ wsToKWh: ws => { const wsTokWh = 3600000; let kWh = ws/wsTokWh; return kWh.toFixed(4).toString(); } }; <gh_stars>0 (function () { 'use strict'; /* jshint -W098 */ angular .module('mean.imscore') .controller('LocationController', LocationController); LocationController.$inject = ['$scope', 'Global', 'Location']; function LocationController($scope, Global, Location) { $scope.global = Global; $scope.package = { name: 'imscore' }; Location.query({active:true}, function(locations){ $scope.locations = locations; }); } })();<reponame>Benjaminlewis984/swamp<gh_stars>0 import React from "react"; import { Link } from "react-router-dom"; import Disclaimer from "./Disclaimer"; // Import profile pictures import ben from "../imgs/BenImage.jpg"; import dang from "../imgs/dang.jpg"; import will from "../imgs/william.jpg"; import joe from "../imgs/Joe.jpg"; import onu from "../imgs/Onu.jpg"; import kevin from "../imgs/kevin.jpg"; import ReactGA from 'react-ga'; const Team = () => { ReactGA.initialize(process.env.REACT_APP_GA_TRACKING_ID); ReactGA.pageview(window.location.pathname + window.location.search); return ( <div> <div className="col-10 mx-auto text-center text-title pt-5"> <h2 className="text-center text-title">Our Team</h2> {/* First row */} <div className="row"> <div className="mt-5 mb-5 mx-auto"> <Link to="/ben"> <img className="profile" src={ben} /> </Link> <h3>Ben</h3> <p className="title">Team Lead</p> </div> <div className="mt-5 mb-5 mx-auto"> <Link to="/dang"> <img className="profile" src={dang} /> </Link> <h3>Dang</h3> <p className="title">Front-End Lead</p> </div> <div className="mt-5 mb-5 mx-auto"> <Link to="/will"> <img className="profile" src={will} /> </Link> <h3>Will</h3> <p className="title">Back-End Lead</p> </div> </div> {/* Second row */} <div className="row"> <div className="mt-5 mb-5 mx-auto"> <Link to="/joe"> <img className="profile" src={joe} /> </Link> <h3>Weerachai</h3> <p className="title">Git Master</p> </div> <div className="mt-5 mb-5 mx-auto"> <Link to="/onu"> <img className="profile" src={onu} /> </Link> <h3>Onu</h3> <p className="title">Front-End</p> </div> <div className="mt-5 mb-5 mx-auto"> <Link to="/kevin"> <img className="profile" src={kevin} /> </Link> <h3>Kevin</h3> <p className="title">Back-End</p> </div> </div> </div> <Disclaimer /> </div> ); }; export default Team; 'use strict'; var log = _.partial(require('bows')('controllers'), 'StartRouter'); var FilterRouter = require( '../routers/Filter' ); module.exports = function(){ }; _.extend( module.exports.prototype, { wiring : ['filterState'], execute : function(){ log('#execute'); var router = new FilterRouter( { controller : this.filterState } ); this.context.wireValue('router', router); if( Backbone.history ){ Backbone.history.start(); } } } ); <filename>client/app/components/UserSystem/UserSystem.js import React, { Component } from 'react'; import 'whatwg-fetch'; import Button from '@material-ui/core/Button'; import { TextField } from "@material-ui/core"; import { setInStorage, getFromStorage } from '../../utils/storage'; import Typography from '@material-ui/core/Typography'; const userBox = { width: "400px", backgroundColor: "white", marginLeft: "auto", marginRight: "auto", }; const userInnerBox = { textAlign: "center", padding: "10px", }; const tab = { textDecoration: "none", padding: "5px", background: "#449B2E", color: "white", textAlign: "center", }; class UserSystem extends Component { constructor(props) { super(props); this.state = { isLoading: true, token: '', signUpError: '', signInError: '', signInEmail: '', signInPassword: '', signUpEmail: '', signUpPassword: '', signUpUsername: '', }; //user system this.onTextboxChangeSignInEmail = this.onTextboxChangeSignInEmail.bind(this); this.onTextboxChangeSignInPassword = this.onTextboxChangeSignInPassword.bind(this); this.onTextboxChangeSignUpEmail = this.onTextboxChangeSignUpEmail.bind(this); this.onTextboxChangeSignUpUsername = this.onTextboxChangeSignUpUsername.bind(this); this.onTextboxChangeSignUpPassword = this.onTextboxChangeSignUpPassword.bind(this); this.onSignUp = this.onSignUp.bind(this); this.onSignIn = this.onSignIn.bind(this); this.logout = this.logout.bind(this); } onTextboxChangeSignInEmail(event) { this.setState({ signInEmail: event.target.value, }); } onTextboxChangeSignInPassword(event) { this.setState({ signInPassword: event.target.value, }); } onTextboxChangeSignUpEmail(event) { this.setState({ signUpEmail: event.target.value, }); } onTextboxChangeSignUpUsername(event) { this.setState({ signUpUsername: event.target.value, }); } onTextboxChangeSignUpPassword(event) { this.setState({ signUpPassword: event.target.value, }); } onSignUp() { // Grabs values stored in state const { signUpEmail, signUpUsername, signUpPassword, } = this.state; this.setState({ isLoading: true, }); // Post request to backend fetch('/api/account/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: signUpEmail, username: signUpUsername, password: <PASSWORD>, }), }).then(res => res.json()) .then(json => { console.log('json', json); if (json.success) { this.setState({ signUpError: json.message, isLoading: false, signUpEmail: '', signUpUsername: '', signUpPassword: '', }); } else { this.setState({ signUpError: json.message, isLoading: false, }); } }); } onSignIn() { // Grab state const { signInEmail, signInPassword, } = this.state; this.setState({ isLoading: true, }); // Post request to backend fetch('/api/account/signin', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: signInEmail, password: <PASSWORD>, }), }).then(res => res.json()) .then(json => { console.log('json', json); if (json.success) { setInStorage('the_main_app', { token: json.token }); this.setState({ signInError: json.message, isLoading: false, signInPassword: '', signInEmail: '', token: json.token, }); } else { this.setState({ signInError: json.message, isLoading: false, }); } }); } logout() { this.setState({ isLoading: true, }); const obj = getFromStorage('the_main_app'); if (obj && obj.token) { const { token } = obj; // Verify token fetch('/api/account/logout?token=' + token) .then(res => res.json()) .then(json => { if (json.success) { this.setState({ token: '', isLoading: false }); } else { this.setState({ isLoading: false, }); } }); } else { this.setState({ isLoading: false, }); } } componentDidMount() { const obj = getFromStorage('freegan_directory_app'); if (obj && obj.token) { const { token } = obj; // Verify token fetch('/api/account/verify?token=' + token) .then(res => res.json()) .then(json => { if (json.success) { this.setState({ token, isLoading: false }); } else { this.setState({ isLoading: false, }); } }); } else { this.setState({ isLoading: false, }); } } render() { const { isLoading, token, signInError, signInEmail, signInPassword, signUpEmail, signUpUsername, signUpPassword, signUpError, } = this.state; if (isLoading) { return (<div><p>Loading...</p></div>); } if (!token) { return ( <div style={userBox}> <Typography component="h2" variant="h6" gutterBottom style={tab}> Login </Typography> <div style={userInnerBox}> {(signInError) ? (<p>{signInError}</p>) : (null)} <p> <TextField id="outlined-name" label="Email" value={signInEmail} onChange={this.onTextboxChangeSignInEmail} margin="normal" variant="outlined" /> </p> <p> <TextField id="outlined-name" label="password" value={signInPassword} onChange={this.onTextboxChangeSignInPassword} margin="normal" variant="outlined" /> </p> <Button onClick={this.onSignIn}>Login</Button> </div> <Typography component="h2" variant="h6" gutterBottom style={tab}> Sign Up </Typography> <div style={userInnerBox}> {(signUpError) ? (<p>{signUpError}</p>) : (null)} <p> <TextField id="outlined-name" label="Email" value={signUpEmail} onChange={this.onTextboxChangeSignUpEmail} margin="normal" variant="outlined" /> </p> <p> <TextField id="outlined-name" label="Display Name" value={signUpUsername} onChange={this.onTextboxChangeSignUpUsername} margin="normal" variant="outlined" /> </p> <p> <TextField id="outlined-name" label="Display Name" value={signUpUsername} onChange={this.onTextboxChangeSignUpUsername} margin="normal" variant="outlined" /> </p> <p> <TextField id="outlined-name" label="Password" value={signUpPassword} onChange={this.onTextboxChangeSignUpPassword} margin="normal" variant="outlined" /> </p> <Button onClick={this.onSignUp}>Sign Up</Button> </div> </div> ); } return ( <div> <p>Account</p> <button onClick={this.logout}>Logout</button> </div> ); } } export default UserSystem; var chai = require('chai'); var expect = chai.expect; var tap = require('falcor-observable').tap; var TestRunner = { run: function(obs, compares) { var count = 0; return obs. pipe(tap(function(x) { // Validates against all comparables compares.forEach(function(c) { jsongPartialCompare(c.jsonGraph, x.jsonGraph); }); count++; }, undefined, function() { expect(count, 'The observable should of onNext one time').to.equal(1); })); }, comparePath: function(expected, actual) { expected.forEach(function(el, i) { var aEl = actual[i]; if (typeof el === 'object') { el.forEach(function(innerEl, innerI) { expect(aEl[innerI]).to.deep.equal(innerEl); }); } else { expect(aEl).to.equal(el); } }); }, partialCompare: jsongPartialCompare, rangeToArray: function rangeToArray(ranges) { var out = []; ranges.forEach(function(range) { var to = range.to; for (var i = 0; i <= to; ++i) { out[out.length] = i; } }); return out; } }; module.exports = TestRunner; function jsongPartialCompare(expectedPartial, actual) { traverseAndConvert(actual); traverseAndConvert(expectedPartial); contains(expectedPartial, actual, ''); } function traverseAndConvert(obj) { if (Array.isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (typeof obj[i] === "object") { traverseAndConvert(obj[i]); } else if (typeof obj[i] === "number") { obj[i] = obj[i] + ""; } else if (typeof obj[i] === "undefined") { obj[i] = null; } } } /* eslint-disable no-eq-null, eqeqeq */ else if (obj != null && typeof obj === "object") { Object.keys(obj).forEach(function (k) { if (typeof obj[k] === "object") { traverseAndConvert(obj[k]); } else if (typeof obj[k] === "number") { obj[k] = obj[k] + ""; } else if (typeof obj[k] === "undefined") { obj[k] = null; } }); } /* eslint-enable no-eq-null, eqeqeq */ return obj; } function contains(expectedPartial, actual, position) { var obj = Object.keys(expectedPartial); obj.forEach(function (k) { var message = "Object" + position; expect(expectedPartial, message + " to have key " + k).to.include.keys(k); if (typeof expectedPartial[k] !== 'object' && typeof actual[k] !== 'object') { expect(actual[k], message + '.' + k).to.equals(expectedPartial[k]); } else if (typeof actual[k] === 'object' && Array.isArray(actual[k])) { expect(actual[k], message + '.' + k).to.deep.equals(expectedPartial[k]); } else { contains(expectedPartial[k], actual[k], position + '.' + k); } }); } ({ doInit: function(cmp, event, helper) { localStorage.removeItem('firstName'); localStorage.removeItem('lastName'); localStorage.removeItem('email'); }, facebookApi : function(cmp, event, helper) { console.log('entrou facebook'); var url; var action = cmp.get("c.getSocialMediaSetup"); action.setParams({ csName:'facebook' }) action.setCallback(this, function(response) { var state = response.getState(); console.log(state); if (state === "SUCCESS") { var res = JSON.parse(response.getReturnValue()); console.log(res); helper.continueFbApi(cmp, event, helper,res); }else if (state === "ERROR") { if (response.getError()) { console.log("Error message: " + response.getError()[0].message); } } }); $A.enqueueAction(action); }, googleApi : function(cmp, event, helper) { console.log('entrou google'); var url; var action = cmp.get("c.getSocialMediaSetup"); action.setParams({ csName:'google' }) action.setCallback(this, function(response) { var state = response.getState(); console.log(state); if (state === "SUCCESS") { var res = JSON.parse(response.getReturnValue()); console.log(res); helper.continueGoogleApi(cmp, event, helper,res); }else if (state === "ERROR") { if (response.getError()) { console.log("Error message: " + response.getError()[0].message); } } }); $A.enqueueAction(action); } })<reponame>mcarief110/Hikarei<filename>Commands/Information/Membercount.js const Djs = require("discord.js"); const client = new Djs.Client(); module.exports = { name: "membercount", aliases: [], category: "Information", description: "MemberCount list server", usage: "[membercount]", run: async (client, message, args) => { let sicon = message.guild.iconURL; const embed = new Djs.MessageEmbed() .setAuthor(message.guild.name, sicon) .setColor('RANDOM') .setThumbnail(sicon) .addField('Member', `**${message.guild.memberCount.cache}**`, true) .addField('Usercount', `**${message.guild.membersCount.cache.filter(x => x === x.bot)}**`, true) .addField('Bots', `**${message.guild.members.cache.filter(member => member.user.bot).size}**`, true) .addField('Member Status', `**${message.guild.members.cache.filter(o => o.presence.status === 'online').size}** Online\n**${message.guild.members.cache.filter(i => i.presence.status === 'idle').size}** Idle/Away\n**${message.guild.members.cache.filter(dnd => dnd.presence.status === 'dnd').size}** Do Not Disturb\n**${message.guild.members.cache.filter(off => off.presence.status === 'offline').size}** Offline/Invisible\n**${message.guild.members.cache.filter(s => s.presence.status === 'streaming').size}** Streaming`, true) .setFooter(`Owner: ${message.guild.owner.user.tag}`) message.channel.send(embed) } };import { useReducer } from 'react'; const defaultToggleReducer = (state, nextValue) => { return (typeof nextValue === 'boolean') ? nextValue : !state; }; /** * A custom Hook that toggles between boolean values. It also accepts a toggle function that can be used to change the value. * * @param {boolean} initialValue - The initial value of the toggle. * @param {function} [toggleReducer] - An optional reducer function that can be used to determine the next value. * @returns {[boolean, function]} Returns an array with the current value and a function to toggle the value. */ const useToggle = ( initialValue = false, toggleReducer = defaultToggleReducer, ) => { return useReducer(toggleReducer, initialValue); }; export default useToggle; import Val from './val'; import v from './v'; import { sym } from './sym'; import { exp } from './exp'; export class Native extends Val { apply(store, ...args) { for (let i = 0; i < args.length; i++) { const a = args[i]; const na = a.step(store); if (!na.equals(a)) { const nargs = args.concat(); nargs[i] = na; return exp(this, ...nargs); } } const oargs = args.map(a => a.origin); const orig = this.origin(...oargs.concat(this)); return v(orig); } replaceAsTop(matches) { const args = matches.map(m => m.target ? m.target : m.pattern); return exp(this, ...args); } stringify(indent) { return `<Native ${this.appendIndent(this.origin, indent)}>`; } } export class LiftedNative extends Native { apply(store, ...args) { const reducedArgs = args.map(a => a && a.reduce && a.reduce(store)); return this.origin(...reducedArgs.concat(store)); } stringify(indent) { return `<LiftedNative ${this.appendIndent(this.origin, indent)}>`; } } class CaseAlt extends Val { constructor(...args) { const pats = args.slice(0, -1).map(p => typeof(p) === "string" ? sym(p) : p); let grds = args[args.length-1]; { if (grds instanceof Function) { if (grds.length > 0 && grds.length != pats.length) { throw "arity mismatched for native function"; } grds = new Native(grds); } if (!Array.isArray(grds)) { grds = [grd(v(true), grds)]; } } super({ pats, grds }); } get pats() { return this.origin.pats; } get grds() { return this.origin.grds; } replaceAsTop(matches) { const pats = matches.filter(m => !m.target).map(m => m.pattern); const grds = this.grds.map(grd => grd.replaceAsTop(matches)); return new this.constructor(...pats.concat([grds])); } replace(matches) { // todo: Objのfiledsにバインドしている物を除外できていないのを修正する必要あり const submatches = matches.filter(m => m.target && Object.keys(m.result).every(k => this.pats.every(p => !sym(k).equals(p)))); const grds = this.grds.map(grd => grd.replace(submatches)); return new this.constructor(...this.pats.concat([grds])); } } export function alt(...args) { return new CaseAlt(...args); } class CaseGrd extends Val { constructor(cond, exp) { if (typeof(exp) === "string") { exp = sym(exp); } super({cond, exp}); } get cond() { return this.origin.cond; } get exp() { return this.origin.exp; } replaceAsTop(matches) { return new this.constructor( this.cond.replaceAsTop(matches), this.exp.replaceAsTop(matches) ); } replace(matches) { return new this.constructor( this.cond.replace(matches), this.exp.replace(matches) ); } } export function grd(cond, exp) { return new CaseGrd(cond, exp); } export const otherwise = v(true); export default class Case extends Val { static func(...args) { return new this(alt(...args)); } constructor(...alts) { super(alts); } get alts() { return this.origin; } replace(matches) { const alts = this.alts.map(alt => alt.replace(matches)); return new this.constructor(...alts); } matches(patterns, targets) { if (patterns.length === 0) { return targets.map(target => ({ target, result: {__it__: target} })); } return patterns.map((pattern, i) => { const target = targets[i]; if (target) { return target.match(pattern); } else { return {pattern}; } }); } apply(store, ...args) { for (const alt of this.alts) { const matches = this.matches(alt.pats, args); if (matches.every(match => match.result !== null)) { const nalt = alt.replaceAsTop(matches); if (nalt.pats.length > 0) { return new this.constructor(nalt); } for (const grd of nalt.grds) { if (grd.cond.reduce(store).origin) { return grd.exp; } } } } throw "matched pattern not found"; } } export function kase(...args) { return new Case(...args); } export class Func extends Case { get exp() { return this.alts[0].grds[0].exp; } reduce(store) { if (this.alts[0].pats.length === 0) { return exp(this).reduce(store); } return super.reduce(store); } } 'use strict'; const TutorAction = require('../models/TutorAction'); const RulesEvaluator = require('./rulesEvaluator'); const TutorialPlanner = require('./tutorialPlanner'); const stacktracex = require('../utilities/stacktracex'); class Tutor { constructor(student, session) { this.student = student; this.session = session; } // Process the event from the client processAsync(event) { try { return this._evaluateAsync(event) .then(() => this._makeDecisionAsync(event)) .then((tutorAction) => { if (tutorAction != null) { let action = this.student.studentModel.addAction(tutorAction); return action.createEvent( this.session.studentId, this.session.id); } else { return null; } }); } catch(err) { return Promise.reject(err); } } // Evaluate user action and update student model _evaluateAsync(event) { try { let evaluator = new RulesEvaluator(this.student, this.session); return evaluator.evaluateAsync(event); } catch(err) { return Promise.reject(err); } } // Use the student model to decide on which tutor action to take _makeDecisionAsync(event) { try { let tutorialPlanner = new TutorialPlanner(this.student, this.session); return tutorialPlanner.evaluateAsync(event); } catch(err) { return Promise.reject(err); } } } module.exports = Tutor;/* * jQuery Touch Optimized Sliders "R"Us * HTML media * * Copyright (c) <NAME> * www.frebsite.nl */ (function( $ ) { var _PLUGIN_ = 'tosrus', _MEDIA_ = 'html'; $[ _PLUGIN_ ].media[ _MEDIA_ ] = { // Filter anchors filterAnchors: function( $anchor ) { var href = $anchor.attr( 'href' ); return ( href.slice( 0, 1 ) == '#' && $(href).is( 'div' ) ) }, // Create Slides from anchors initAnchors: function( $slide, href ) { $('<div class="' + $[ _PLUGIN_ ]._c( 'html' ) + '" />') .append( $(href) ) .appendTo( $slide ); $slide.removeClass( $[ _PLUGIN_ ]._c.loading ) .trigger( $[ _PLUGIN_ ]._e.loaded ); }, // Filter slides filterSlides: function( $slide ) { return $slide.is( 'div' ); }, // Create slides from existing content initSlides: function( $slide ) {} }; $[ _PLUGIN_ ].defaults.media[ _MEDIA_ ] = {}; })( jQuery );<reponame>hdm/mac-tracker macDetailCallback("303d51700000/28",[{"d":"2022-05-15","t":"add","s":"ieee-mam.csv","a":"Aw House, \n6-8 Stuart Street Luton Bedfordshire GB LU1 2SJ","c":"GB","o":"Destiny Automate Limited"}]); function Log() {} Log.prototype.type = ["primary", "success", "warn", "error", "info"]; Log.prototype.typeColor = function(type) { let color = ""; switch (type) { case "primary": color = "#2d8cf0"; break; case "success": color = "#19be6b"; break; case "info": color = "#909399"; break; case "warn": color = "#ff9900"; break; case "error": color = "#f03f14"; break; default: color = "#35495E"; break; } return color; }; Log.prototype.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; Log.prototype.print = function(text, type = "default", back = false) { if (typeof text === "object") { // 如果是對象則調用打印對象方式 this.isArray(text) ? console.table(text) : console.dir(text); return; } if (back) { // 如果是打印帶背景圖的 console.log(`%c ${text} `, `background:${this.typeColor(type)}; padding: 2px; border-radius: 4px; color: #fff;`); } else { console.log( `%c ${text} `, `border: 1px solid ${this.typeColor(type)}; padding: 2px; border-radius: 4px; color: ${this.typeColor(type)};` ); } }; Log.prototype.printBack = function(type = "primary", title) { this.print(type, title, true); }; Log.prototype.pretty = function(type = "primary", title, text) { if (typeof text === "object") { console.group("Console Group", title); console.log( `%c ${title}`, `background:${this.typeColor(type)};border:1px solid ${this.typeColor(type)}; padding: 1px; border-radius: 4px; color: #fff;` ); this.isArray(text) ? console.table(text) : console.dir(text); console.groupEnd(); return; } console.log( `%c ${title} %c ${text} %c`, `background:${this.typeColor(type)};border:1px solid ${this.typeColor(type)}; padding: 1px; border-radius: 4px 0 0 4px; color: #fff;`, `border:1px solid ${this.typeColor(type)}; padding: 1px; border-radius: 0 4px 4px 0; color: ${this.typeColor(type)};`, "background:transparent" ); }; Log.prototype.prettyPrimary = function(title, ...text) { text.forEach(t => this.pretty("primary", title, t)); }; Log.prototype.prettySuccess = function(title, ...text) { text.forEach(t => this.pretty("success", title, t)); }; Log.prototype.prettyWarn = function(title, ...text) { text.forEach(t => this.pretty("warn", title, t)); }; Log.prototype.prettyError = function(title, ...text) { text.forEach(t => this.pretty("error", title, t)); }; Log.prototype.prettyInfo = function(title, ...text) { text.forEach(t => this.pretty("info", title, t)); }; export default new Log(); <gh_stars>1-10 'use strict'; exports.keys = '123456'; exports.easyProxy = [ { host: 'http://127.0.0.1:1111', match: /^\/proxy/, }, // { // host: 'https://github.com', // match: /^\/explore/, // }, ]; <gh_stars>0 define(function(require) { "use strict"; var Backbone = require("backbone"); /** * * * */ var Router = Backbone.Router.extend({ routes: { "": "list", ":id(/)": "detail" } }); // end Router return Router; }); <gh_stars>100-1000 import runTest from '../runTest'; import { run, print } from '../../../util'; describe('runTest', () => { it('works', () => { runTest({ config: { testCommandBeforeRelease: () => 'yarn test', }, dir: '.', dryRun: false, }); expect(run).toHaveBeenCalledTimes(1); expect(run.mock.calls[0][0]).toMatchInlineSnapshot(` Object { "command": "yarn test", "dir": ".", "dryRun": false, } `); }); it('skips test if testCommandBeforeRelease is falsy', () => { runTest({ config: { testCommandBeforeRelease: null, }, dir: '.', dryRun: false, }); expect(run).toHaveBeenCalledTimes(0); expect(print).toHaveBeenCalledTimes(2); expect(print.mock.calls).toMatchInlineSnapshot(` Array [ Array [ "› Running test.", ], Array [ "Skipping test because it is not configured.", ], ] `); }); it('skips test if testCommandBeforeRelease returns falsy', () => { runTest({ config: { testCommandBeforeRelease: () => '', }, dir: '.', dryRun: false, }); expect(run).toHaveBeenCalledTimes(0); expect(print).toHaveBeenCalledTimes(2); expect(print.mock.calls).toMatchInlineSnapshot(` Array [ Array [ "› Running test.", ], Array [ "Skipping test because it is not configured.", ], ] `); }); }); module.exports = { base: '/netprotocol/', dest: './dist/netprotocol', title: '趣谈网络协议', description: "Talking about Network Protocol", head: [ ['link', { rel: 'icon', href: '/logo.png' }] ], themeConfig: { nav: [{ text: 'Home', link: '/' }, { text: '其他专栏', items: [{ text: '重学前端', link: 'https://doc.now.sh/frontend/' },{ text: '数据结构与算法之美', link: 'https://doc.now.sh/ds/' },{ text: '深入拆解 Java 虚拟机', link: 'https://doc.now.sh/jvm/' },{ text: '左耳听风', link: 'https://doc.now.sh/air/' },{ text: '深入浅出区块链', link: 'https://doc.now.sh/blockchain/' }, { text: '前端面试之道', link: 'https://doc.now.sh/webyck/' }, { text: 'Web 前端面试指南与高频考题解析', link: 'https://doc.now.sh/webinter/' }, { text: '你不知道的 Chrome 调试技巧', link: 'https://doc.now.sh/chrome/' }, { text: '如何使用 Canvas 制作出炫酷的网页背景特效', link: 'https://doc.now.sh/canvas/' }, { text: 'MySQL实战45讲', link: 'https://doc.now.sh/mysql/' }] }], sidebar: [ ['./article/7398', '开篇词 | 想成为技术牛人?先搞定网络协议!'], ['./article/7581', '第1讲 | 为什么要学习网络协议?'], ['./article/7724', '第2讲 | 网络分层的真实含义是什么?'], ['./article/7772', '第3讲 | ifconfig:最熟悉又陌生的命令行'], ['./article/8015', '第4讲 | DHCP与PXE:IP是怎么来的,又是怎么没的?'], ['./article/8094', '第5讲 | 从物理层到MAC层:如何在宿舍里自己组网玩联机游戏?'], ['./article/8386', '第6讲 | 交换机与VLAN:办公室太复杂,我要回学校'], ['./article/8445', '第7讲 | ICMP与ping:投石问路的侦察兵'], ['./article/8590', '第8讲 | 世界这么大,我想出网关:欧洲十国游与玄奘西行'], ['./article/8729', '第9讲 | 路由协议:西出网关无故人,敢问路在何方'], ['./article/8924', '第10讲 | UDP协议:因性善而简单,难免碰到“城会玩”'], ['./article/8975', '第11讲 | TCP协议(上):因性恶而复杂,先恶后善反轻松'], ['./article/9141', '第12讲 | TCP协议(下):西行必定多妖孽,恒心智慧消磨难'], ['./article/9293', '第13讲 | 套接字Socket:Talk is cheap, show me the code' ], ['./article/9410', '第14讲 | HTTP协议:看个新闻原来这么麻烦'], ['./article/9492', '第15讲 | HTTPS协议:点外卖的过程原来这么复杂'], ['./article/9688', '第16讲 | 流媒体协议:如何在直播里看到美女帅哥?'], ['./article/9707', '第17讲 | P2P协议:我下小电影,99%急死你'], ['./article/9895', '第18讲 | DNS协议:网络世界的地址簿'], ['./article/9938', '第19讲 | HTTPDNS:网络世界的地址簿也会指错路'], ['./article/10085', '第20讲 | CDN:你去小卖部取过快递么?'], ['./article/10098', '第21讲 | 数据中心:我是开发商,自己拿地盖别墅'], ['./article/10386', '第22讲 | VPN:朝中有人好做官'], ['./article/10534', '第23讲 | 移动网络:去巴塞罗那,手机也上不了脸书'], ['./article/10742', '第24讲 | 云中网络:自己拿地成本高,购买公寓更灵活'], ['./article/10755', '第25讲 | 软件定义网络:共享基础设施的小区物业管理办法'], ['./article/10978', '第26讲 | 云中的网络安全:虽然不是土豪,也需要基本安全和保障'], ['./article/10994', '第27讲 | 云中的网络QoS:邻居疯狂下电影,我该怎么办?'], ['./article/11324', '第28讲 | 云中网络的隔离GRE、VXLAN:虽然住一个小区,也要保护隐私'], ['./article/11465', '第29讲 | 容器网络:来去自由的日子,不买公寓去合租'], ['./article/11643', '第30讲 | 容器网络之Flannel:每人一亩三分地'], ['./article/11940', '第31讲 | 容器网络之Calico:为高效说出善意的谎言'], ['./article/12230', '第32讲 | RPC协议综述:远在天边,近在眼前'], ['./article/12388', '第33讲 | 基于XML的SOAP协议:不要说NBA,请说美国职业篮球联赛'], ['./article/12512', '第34讲 | 基于JSON的RESTful接口协议:我不关心过程,请给我结果'], ['./article/12521', '第35讲 | 二进制类RPC协议:还是叫NBA吧,总说全称多费劲'], ['./article/12819', '第36讲 | 跨语言类RPC协议:交流之前,双方先来个专业术语表'], ['./article/12991', '第37讲 | 知识串讲:用双十一的故事串起碎片的网络协议(上)'], ['./article/12996', '第38讲 | 知识串讲:用双十一的故事串起碎片的网络协议(中)'], ['./article/13099', '第39讲 | 知识串讲:用双十一的故事串起碎片的网络协议(下)'], ['./article/13124', '第40讲 | 搭建一个网络实验环境:授人以鱼不如授人以渔'], ['./article/13520', '协议专栏特别福利 | 答疑解惑第一期'], ['./article/13847', '协议专栏特别福利 | 答疑解惑第二期'], ['./article/14028', '协议专栏特别福利 | 答疑解惑第三期'], ['./article/14194', '协议专栏特别福利 | 答疑解惑第四期'], ['./article/14381', '协议专栏特别福利 | 答疑解惑第五期'], ['./article/14384', '测一测 | 这些网络协议你都掌握了吗?'], ['./article/14553', '结束语 | 放弃完美主义,执行力就是限时限量认真完成'], ['./article/17846', '我是如何创作“趣谈网络协议”专栏的?'], ['./article/17862', '“趣谈网络协议”专栏「食用指南」'] ] } }<reponame>MizoPro/animelist /*! * db.js * database managment tool * @author MizoPro */ /** * An Array of anime objects * */ class AnimeCollection extends Array { constructor (...db) { super(...db); } findById (id) { return this.filter(anime => anime.id === parseInt(id))[0] || null; } filterByType (type) { type = type.toLowerCase(); const filtered = this.filter(anime => anime.type.toLowerCase() == type); return filtered; } getRandomId (filter) { return this.getRandom(filter).id; } getRandom (filter) { const collection = (typeof filter === "function") ? this.filter(filter) : this; return collection[Math.floor(Math.random() * collection.length)]; } sortByTitle() { return this.sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase())); } sortByScore() { return this.sort((a, b) => { const x = a.score.value, y = b.score.value; return (x && y ? (x === y ? a.title.toLowerCase().localeCompare(b.title.toLowerCase()) : y - x ) : (x ? -1 : (y ? 1 : 0))); }); } get tv () { return this.filterByType('tv'); } get ova () { return this.filterByType('ova'); } get movie () { return this.filterByType('movie'); } get ona () { return this.filterByType('ona'); } get special () { return this.filterByType('special'); } get music () { return this.filterByType('music'); } } /** * Module exports * @api public */ module.exports.AnimeCollection = AnimeCollection;<filename>tree/JS/zero-width-positive-look-ahead-assertion.js /** * @desc 去掉字符串中最后一个指定字符-零宽正向先行断言的运用 * @regexp 零宽正向先行断言 参考资料 https://www.kancloud.cn/zhongxia/javascript-regex/184194 * 它会从要匹配的字符的最右端开始匹配。 * @param {String} str * @param {String} target */ const delLastStr = (str, target) => { const reg = new RegExp(`${target}(?=([^${target}]*)$)`) // const ret = str.match(reg) // console.log(ret) return str.replace(reg, '') } // Test console.log(delLastStr('careteen', 'e')) <reponame>WeideMo/miniAjax /* * author: WeideMo * email: <EMAIL> * source: https://github.com/WeideMo/miniAjax **/ !function (ob) { function formatParams(data, random) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name])); } if(random){ arr.push(("v=" + Math.random()).replace(".", "")); } return arr.join("&"); } ob.ajax = function(options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.dataType = options.dataType || "json"; var params = formatParams(options.data, true); if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); } else { var xhr = new ActiveXObject('Microsoft.XMLHTTP'); } xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status >= 200 && status < 300) { options.success && options.success(xhr.responseText, xhr.responseXML); } else { options.fail && options.fail(status); } } } if (options.type == "GET") { xhr.open("GET", options.url + "?" + params, true); xhr.send(null); } else if (options.type == "POST") { xhr.open("POST", options.url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(params); } } ob.jsonp = function(options) { options = options || {}; if (!options.url || !options.callback) { throw new Error("参数不合法"); } var callbackName = ('jsonp_' + Math.random()).replace(".", ""); var oHead = document.getElementsByTagName('head')[0]; options.data[options.callback] = callbackName; var params = formatParams(options.data); var oS = document.createElement('script'); oHead.appendChild(oS); window[callbackName] = function (json) { oHead.removeChild(oS); clearTimeout(oS.timer); window[callbackName] = null; options.success && options.success(json); }; oS.src = options.url + '?' + params; if (options.time) { oS.timer = setTimeout(function () { window[callbackName] = null; oHead.removeChild(oS); options.fail && options.fail({ message: "超时" }); }, time); } }; ob.ready = function (readyFn) { if (document.addEventListener) { document.addEventListener('DOMContentLoaded', function () { readyFn && readyFn(); }, false); } else { var bReady = false; document.attachEvent('onreadystatechange', function () { if (bReady) { return; } if (document.readyState == 'complete' || document.readyState == "interactive") { bReady = true; readyFn && readyFn(); }; }); if (!window.frameElement) { setTimeout(checkDoScroll, 1); } function checkDoScroll() { try { document.documentElement.doScroll("left"); if (bReady) { return; } bReady = true; readyFn && readyFn(); } catch (e) { setTimeout(checkDoScroll, 1); } }; } }; }(window || this)import Vue from 'vue' import Router from 'vue-router' // Containers const TheContainer = () => import('@/containers/TheContainer') // Views const Dashboard = () => import('@/views/Dashboard') const Page404 = () => import('@/views/Page404') const Login = () => import('@/views/Login') const Members = () => import('@/views/Members') Vue.use(Router) export default new Router({ mode: 'history', // https://router.vuejs.org/api/#mode linkActiveClass: 'active', scrollBehavior: () => ({ y: 0 }), routes: configRoutes() }) function configRoutes () { return [ { path: '/', name: 'Login', component: Login }, { path: '/', redirect: '/dashboard', name: 'Home', component: TheContainer, children: [ { path: 'dashboard', name: 'Dashboard', component: Dashboard }, { path: '/members', name: 'Members', component: Members } ] }, { path: '/404', name: 'Page404', component: Page404 } ] } var searchData= [ ['qglviewerwidget',['QGLViewerWidget',['../a00252.html',1,'']]], ['qt_5fread_5ffilters',['qt_read_filters',['../a00069.html#ac3d9b92b132ce16580099c8ccd5ef94a',1,'OpenMesh::IO::_IOManager_']]], ['qt_5fwrite_5ffilters',['qt_write_filters',['../a00069.html#a14a72706b4c13a3635cf448e9ce55b6b',1,'OpenMesh::IO::_IOManager_']]], ['quadrict',['QuadricT',['../a00253.html',1,'OpenMesh::Geometry']]], ['quadrict',['QuadricT',['../a00253.html#aa4dd04f39435110361e4088cc376618a',1,'OpenMesh::Geometry::QuadricT::QuadricT(Scalar _a, Scalar _b, Scalar _c, Scalar _d, Scalar _e, Scalar _f, Scalar _g, Scalar _h, Scalar _i, Scalar _j)'],['../a00253.html#ae6a410e0bd234af03477f8466d0b45d3',1,'OpenMesh::Geometry::QuadricT::QuadricT(Scalar _a=0.0, Scalar _b=0.0, Scalar _c=0.0, Scalar _d=0.0)']]], ['quadrict_2ehh',['QuadricT.hh',['../a00421.html',1,'']]] ]; import React, { Component } from "react"; import "./Review.css"; import ReviewForm from "./components/ReviewForm" export default class Review extends Component { render() { return ( <ReviewForm/> ); } }// ============================================================================ // [binlib.js] // Binary structures in JS. // // This is free and unencumbered software released into the public domain. // // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non-commercial, and by any // means. // // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // // 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 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. // // For more information, please refer to <https://unlicense.org/> // ============================================================================ // ============================================================================ // This is a small library that allows to define C-like structures that are // used in binary data. It has the following goals: // // * Allow to define a C-like structs. // * Allow to define links between structs (absolute vs relative offsets). // * Allow to read a struct into a JS object (including substructs). // * Allow to update data back from JS object to the original Buffer/DataView. // // The following built-in types are provided: // // * I8/U8 - Signed/Unsigned 8-bit integer. // * I16/U16 - Signed/Unsigned 16-bit integer. // * I24/U24 - Signed/Unsigned 24-bit integer. // * I32/U32 - Signed/Unsigned 32-bit integer. // * Str - String of fixed size, read as ASCII string. // * Hex - String of fixed size, read as HEX string. // * Arr - Array of fixed or variable size. // ============================================================================ (function($export, $as) { "use strict"; // ============================================================================ // [Import] // ============================================================================ const freeze = Object.freeze; const hasOwn = Object.prototype.hasOwnProperty; const isArray = Array.isArray; const NoObject = freeze(Object.create(null)); // ============================================================================ // [Export] // ============================================================================ const binlib = Object.create(null); $export[$as] = binlib; // ============================================================================ // binlib.FLAGS] // ============================================================================ const FLAGS = freeze({ NONE : 0x00000000, // No flags (just for convenience). PRIMITIVE : 0x00000001, // Primitive type (integer / float). STRING : 0x00000002, // String type (null terminated or fixed). ARRAY : 0x00000004, // Array type, must have $ref pointing to type. STRUCT : 0x00000008, // Struct type LITTLE_ENDIAN : 0x00000010, // Always little endian (regardless of reader/writer mode). BIG_ENDIAN : 0x00000020, // Always big endian (regardless of reader/writer mode). FLOAT : 0x00000040, // Floating point (always combined with PRIMITIVE). SIGNED : 0x00000100, // Signed integer (always combined with PRIMITIVE). UNSIGNED : 0x00000200, // Unsigned integer (always combined with PRIMITIVE). ASCII : 0x00000400, // String data as ASCII (always combined with STRING). HEX : 0x00000800, // String data as HEX (always combined with STRING). ISOLATE : 0x00010000, // Used by `Struct` to isolate all offsets within it (starts a new absolute positioning from here). ABSOLUTE_OFFSET: 0x00040000, // This is an absolute offset that points to a struct (must be used with `$ref`). RELATIVE_OFFSET: 0x00080000 // This is a relative offset that points to a struct (must be used with `$ref`). }); binlib.FLAGS = FLAGS; const FLAGS_PRIMITIVE_LE = FLAGS.PRIMITIVE | FLAGS.LITTLE_ENDIAN; const FLAGS_PRIMITIVE_BE = FLAGS.PRIMITIVE | FLAGS.BIG_ENDIAN; const FLAGS_PRIMITIVE_ALL = FLAGS_PRIMITIVE_LE | FLAGS_PRIMITIVE_BE | FLAGS.FLOAT | FLAGS.SIGNED | FLAGS.UNSIGNED ; function updateFlags(existing, add) { const SIGN = FLAGS.SIGNED | FLAGS.UNSIGNED; const ENDIAN = FLAGS.LITTLE_ENDIAN | FLAGS.BIG_ENDIAN; const OFFSET = FLAGS.ABSOLUTE_OFFSET | FLAGS.RELATIVE_OFFSET; const ENCODING = FLAGS.ASCII | FLAGS.HEX; const clear = ((add & SIGN ) ? SIGN : 0) | ((add & ENDIAN ) ? ENDIAN : 0) | ((add & OFFSET ) ? OFFSET : 0) | ((add & ENCODING) ? ENCODING : 0) ; return (existing & ~clear) | add; } // ============================================================================ // [Globals] // ============================================================================ function isObject(obj) { return typeof obj === "object" && obj != null; } function dummy() {} function returnTrue() { return true; } function fail(msg) { throw Error(msg); } function clz32(x) { return Math.clz32(x); } function ctz32(x) { return 31 - clz32(x ^ (x - 1)); } function bitSizeOf(x) { return 32 - clz32(x); } function bitMaskOf(x) { return x >= 32 ? 0xFFFFFFFF : (1 << x) - 1; } function hasVersion(name) { return name.indexOf('$') !== -1; } function fullNameOf(name, version) { return (!version || !version.length) ? name : name + "$" + version.join("."); } function fullNameFromPartialObject(object, type) { var fullName = type.$name; var verInfo = type.$verInfo; if (!verInfo || !verInfo.length) return fullName; for (var i = 0; i < verInfo.length; i++) { fullName += i === 0 ? "$" : "."; fullName += String(object[verInfo[i]]); } return fullName; } function hexToAscii(x) { return x + (x <= 9 ? 48 : 65); } function asciiToHex(x) { if (x >= 48 && x <= 57) return x - 48; if (x >= 65 && x <= 90) return x - 55; if (x >= 97 && x <= 122) return x - 87; throw TypeError(`Invalid HEX CharCode '${x}'`); } function encodingFromFlags(flags) { return (flags & FLAGS.HEX) ? "hex" : "ascii"; } function dataViewOf(any) { if (any instanceof DataView) return any; var arrayBuffer = null; var byteOffset = 0; var byteLength = -1; if (any instanceof ArrayBuffer) { // The given object is an ArrayBuffer, easy... arrayBuffer = any; } else if (typeof any === "object" && any.buffer instanceof ArrayBuffer) { // The given object is a TypedArray view or node's Buffer. arrayBuffer = any.buffer; // If this is a node's Buffer then we must use the offset as well // as node would normally reuse single `ArrayBuffer` instance for // multiple `Buffer` instances. if (typeof any.offset === "number") byteOffset = any.offset; if (typeof any.length === "number") byteLength = any.length; } if (arrayBuffer === null || !(arrayBuffer instanceof ArrayBuffer)) throw TypeError(`Couldn't recognize the input buffer type`); if (byteLength === -1) byteLength = arrayBuffer.byteLength - byteOffset; return new DataView(arrayBuffer, byteOffset, byteLength); } function dumpFlags(flags) { var s = ""; var none = ""; for (var k in Flags) { const mask = Flags[k]; if (!mask) none = k; else if (flags & mask) s += (s ? "|" : "") + k; } return s || none; } function newObject(meta) { const object = Object.create(null); Object.defineProperty(object, "$meta", { value: meta, enumerable: false }); return object; } // ============================================================================ // binlib.utils] // ============================================================================ binlib.utils = Object.create(null); function getKeyInternal(obj, path, key) { if (!key) throw new TypeError(`Key '${path}' is invalid`); const prefix = path ? path + "." : ""; const m = key.match(/[\.\[]/); if (m) { // Object or array access. const what = m[0]; const index = m.index; const thisKey = key.substring(0, index); if (!hasOwn.call(obj, thisKey)) throw Error(`Key '${prefix + thisKey}' doesn't exist`); const thisObj = obj[thisKey]; if (what === ".") { // Object access. if (thisObj == null || typeof thisObj !== "object" || isArray(thisObj)) throw TypeError(`Key '${prefix + thisKey}' doesn't point to an Object`); const subKey = key.substring(index + 1); return getKeyInternal(thisObj, prefix + thisKey, subKey); } else { // Array access. const endIndex = key.indexOf("]", index); if (endIndex === -1 ) throw TypeError(`Key '${prefix + key}' is invalid`); const indexValue = key.substring(index + 1, endIndex); if (!/^\d+$/.test(indexValue)) throw TypeError(`Key '${prefix + key}' is invalid`); if (!isArray(thisObj)) throw TypeError(`Key '${prefix + thisKey}' doesn't point to an Array`); const i = parseInt(indexValue); if (i >= thisObj.length) throw TypeError(`Key '${prefix + thisKey}' index '${i}' out of range [0, ${thisObj.length})`); const subKey = key.substring(endIndex + 1); if (subKey) { if (!subKey.startsWith(".")) throw TypeError(`Key '${prefix + thisKey}' is invalid`); return getKeyInternal(thisObj[i], prefix + thisKey + `[${i}]`, subKey.substring(1)); } else { // TODO: throw new Error("NOT IMPLEMENTED"); } } } else { if (!hasOwn.call(obj, key)) throw TypeError(`Key '${prefix + key}' doesn't exist`); return obj[key]; } } function getKey(root, path) { return getKeyInternal(root, "", path); } binlib.utils.getKey = getKey; function setKeyInternal(obj, path, key, value) { if (!key) throw new TypeError(`Key '${path}' is invalid`); const prefix = path ? path + "." : ""; const m = key.match(/[\.\[]/); if (m) { // Object or array access. const what = m[0]; const index = m.index; const thisKey = key.substring(0, index); if (!hasOwn.call(obj, thisKey)) throw Error(`Key '${prefix + thisKey}' doesn't exist`); const thisObj = obj[thisKey]; if (what === ".") { // Object access. if (thisObj == null || typeof thisObj !== "object" || isArray(thisObj)) throw TypeError(`Key '${prefix + thisKey}' doesn't point to an Object`); const subKey = key.substring(index + 1); return setKeyInternal(thisObj, prefix + thisKey, subKey, value); } else { // Array access. const endIndex = key.indexOf("]", index); if (endIndex === -1 ) throw TypeError(`Key '${prefix + key}' is invalid`); const indexValue = key.substring(index + 1, endIndex); if (!/^\d+$/.test(indexValue)) throw TypeError(`Key '${prefix + key}' is invalid`); if (!isArray(thisObj)) throw TypeError(`Key '${prefix + thisKey}' doesn't point to an Array`); const i = parseInt(indexValue); if (i >= thisObj.length) throw TypeError(`Key '${prefix + thisKey}' index '${i}' out of range [0, ${thisObj.length})`); const subKey = key.substring(endIndex + 1); if (subKey) { if (!subKey.startsWith(".")) throw TypeError(`Key '${prefix + thisKey}' is invalid`); return setKeyInternal(thisObj[i], prefix + thisKey + `[${i}]`, subKey.substring(1), value); } else { // TODO: throw new Error("NOT IMPLEMENTED"); } } } else { if (!hasOwn.call(obj, key)) throw TypeError(`Key '${prefix + key}' doesn't exist`); const prev = obj[key]; if (prev == null || typeof prev === "object") throw TypeError(`Key '${prefix + key}' is an object, it cannot be set to '${value}'`); if (typeof prev === "number") { if (typeof value === "string") { if (!/^-?\d+$/.test(value)) throw TypeError(`Key '${prefix + key}' cannot be set to '${value}'`); value = parseInt(value); } else if (typeof value === "boolean") { value = Number(value); } else if (typeof value !== "number") { throw TypeError(`Key '${prefix + key}' cannot be set to '${value}'`); } obj[key] = value; return; } if (typeof prev === "string") { obj[key] = value; return; } throw TypeError(`Key '${prefix + key}' exists, but couldn't find a right setter`); } } function setKey(root, key, value) { return setKeyInternal(root, "", key, value); } binlib.utils.setKey = setKey; // ============================================================================ // binlib.Type] // ============================================================================ class Type { constructor(opt) { this.$name = ""; // Type name. this.$fullName = ""; // Full typename containing also the version. this.$size = 0; // Type size in bytes. this.$flags = 0; // Flags, see `binlib.Flags`. if (opt) this.$init(opt); } $init(opt) { if (hasOwn.call(opt, "$name")) { this.$name = opt.$name; this.$fullName = opt.$name; } if (hasOwn.call(opt, "$size")) this.$size = opt.$size; if (hasOwn.call(opt, "$flags")) this.$flags = updateFlags(this.$flags, opt.$flags); } } binlib.Type = Type; // ============================================================================ // binlib.Struct] // ============================================================================ class Struct extends Type { constructor(opt) { super(null); this.$flags |= FLAGS.STRUCT; // Mark this type as STRUCT. this.$verInfo = null; // Version info like `["Major", "Minor"]`. this.$version = null; // Version data like `[1, 0]`. this.$members = []; // Members, always in definition order. if (opt) this.$init(opt); } $init(opt) { const extend = opt.$extend; if (extend) { if (!this.$name && extend.$name) this.$name = extend.$name; if (extend.$flags) this.$flags = updateFlags(this.$flags, extend.$flags); if (extend.$verInfo) this.$verInfo = extend.$verInfo; this.$addMembers(extend.$members); } for (var k in opt) { switch (k) { // Already handled. case "$extend": case "$members": break; case "$flags": this.$flags = updateFlags(this.$flags, opt.$flags); break; default: this[k] = opt[k]; break; } } this.$fullName = fullNameOf(this.$name, this.$version); if (opt.$members) this.$addMembers(opt.$members); } $addMember(opt) { const name = opt.$name; if (!name) fail(`'${this.$name}': Cannot add member without a name`); if (hasOwn.call(this, name)) fail(`'${this.$name}['${name}']': Already exists`); const type = opt.$type; if (!type) fail(`'${this.$name}['${name}']': Doesn't provide member '$type'`); var size = opt.$size ? opt.$size : type.$size; var flags = updateFlags(type.$flags, (opt.$flags || 0)); const members = this.$members; const member = Object.create(null); member.$name = name; // Member name. member.$type = type; // Member type, references a `Type` instance. member.$size = size; // Member size, in bytes, based on Type.$size. member.$flags = flags; // Member flags, based on Type.$flags. member.$bitMask = 0; // Bit mask in case this is a bit-field. member.$bitShift = 0; // Bit shift in case this is a bit-field. member.$offset = 0; // Offset [bytes] relative to the beginning of the struct. member.$unit = null; // Describes a unit if this is a value, can be null. member.$ref = null; // Reference to another `Type` or `Struct`. member.$length = -1; // Only used by String and Array types. var bitSize = 0; // Handle all extra attributes. for (var k in opt) { if (k === "$type" || // Already handled. k === "$name" || // Already handled. k === "$size" || // Already handled. k === "$flags" || // Already handled. k === "$bitMask" || // Deduced automatically (can be part of an existing member from a base struct). k === "$bitShift") // Deduced automatically (can be part of an existing member from a base struct). continue; const v = opt[k]; switch (k) { case "$bitSize": if (v <= 0) fail(`'${this.$name}.${name}': The '$bitSize' attribute '${v}' cannot be zero or less`); bitSize = v; break; case "$ref": if (v === undefined) fail(`'${this.$name}.${name}]': Reference $ref cannot be undefined, use null instead`); if (v === undefined) fail(`'${this.$name}.${name}]': Reference $ref cannot be undefined, use null instead`); member.$ref = v; break; default: member[k] = v; break; } } // Handle fixed strings. if (flags & FLAGS.STRING) { size = member.$length; member.$size = size; } // This is an existing bit-field added to this struct, compute `$bitSize` from `$bitMask` and `$bitShift`. if (opt.$bitMask != null && opt.$bitShift != null) { if (bitSize) fail(`'${this.$name}.${name}': Something got wrong, $bitSize '${bitSize}' defined together with $bitMask '${opt.$bitMask}' and $bitShift '${opt.$bitShift}'`); bitSize = bitSizeOf(opt.$bitMask >>> opt.$bitShift); } if (bitSize) { if (flags & (FLAGS.STRING | FLAGS.ARRAY | FLAGS.STRUCT)) fail(`'${this.$name}.${name}': Something got wrong, $bitSize '${bitSize}' defined for non-primitive type`); if (bitSize > size * 8) fail(`'${this.$name}.${name}': Bit size '${bitSize} cannot be greater than a native type size '${size * 8}'`); } // Check the previous member if it's an unclosed bit-array. If true we must // continue it or fail immediately as holes in structs are not allowed. const prev = members.length ? members[members.length - 1] : null; var advance = true; var remainingBitShift = 0; var remainingBitCount = 0; if (prev && prev.$bitMask) { const prevBitShift = prev.$bitShift; const prevMaskSize = bitSizeOf(prev.$bitMask >>> prevBitShift); remainingBitShift = prevBitShift + prevMaskSize; remainingBitCount = prev.$size * 8 - remainingBitShift; if (remainingBitCount < 0) fail(`'${this.$name}.${name}': Something got wrong when calculating the remaining bit-count '${remainingBitCount}' of previous member '${prev.$name}'`); } if (remainingBitCount) { if (!(flags & FLAGS.PRIMITIVE)) fail(`'${this.$name}.${name}': Detected an unclosed bit-field, member '${prev.$name}' still has '${remainingBitCount}' remaining bits left`); if (prev.$size !== size) fail(`'${this.$name}.${name}': Bit-field size mismatch, member '${prev.$name}' has size '${prev.$size}' while '${name}' has size '${size}'`); if (bitSize > remainingBitCount) fail(`'${this.$name}.${name}': Bit-field size mismatch, cannot fit '${bitSize}' bits in '${remainingBitCount}' remaining bits`); } if (flags & FLAGS.PRIMITIVE) { // Handle bit-field specified by `$bitSize` ($bitShift and $bitMask are always deduced). if (bitSize) { if (remainingBitCount) { const bitMask = bitMaskOf(bitSize) << remainingBitShift; member.$offset = prev.$offset; member.$bitMask = bitMask; member.$bitShift = remainingBitShift; advance = false; } else { member.$bitMask = bitMaskOf(bitSize) | 0; member.$bitShift = 0; } } } else if (flags & FLAGS.ARRAY) { // Handle array. const ref = member.$ref; const length = member.$length; // Handle a fixed-length array. if (typeof length === "number") { const fixedLength = length; size = ref.$size * fixedLength; member.$size = size; } } // Now add the newly created member to members array and the struct itself. members.push(member); this[name] = member; // Only advance when necessary. if (advance) { member.$offset = this.$size; this.$size += size; } return this; } $addMembers(arr) { for (var i = 0; i < arr.length; i++) this.$addMember(arr[i]); return this; } } binlib.Struct = Struct; // ============================================================================ // binlib.BuiltInTypes] // ============================================================================ const I8 = binlib.I8 = freeze(new Type({ $name: "I8" , $size: 1, $flags: FLAGS.PRIMITIVE | FLAGS.SIGNED })); const U8 = binlib.U8 = freeze(new Type({ $name: "U8" , $size: 1, $flags: FLAGS.PRIMITIVE | FLAGS.UNSIGNED })); const I16LE = binlib.I16LE = freeze(new Type({ $name: "I16LE", $size: 2, $flags: FLAGS_PRIMITIVE_LE | FLAGS.SIGNED })); const I16BE = binlib.I16BE = freeze(new Type({ $name: "I16BE", $size: 2, $flags: FLAGS_PRIMITIVE_BE | FLAGS.SIGNED })); const U16LE = binlib.U16LE = freeze(new Type({ $name: "U16LE", $size: 2, $flags: FLAGS_PRIMITIVE_LE | FLAGS.UNSIGNED })); const U16BE = binlib.U16BE = freeze(new Type({ $name: "U16BE", $size: 2, $flags: FLAGS_PRIMITIVE_BE | FLAGS.UNSIGNED })); const I24LE = binlib.I24LE = freeze(new Type({ $name: "I24LE", $size: 3, $flags: FLAGS_PRIMITIVE_LE | FLAGS.SIGNED })); const I24BE = binlib.I24BE = freeze(new Type({ $name: "I24BE", $size: 3, $flags: FLAGS_PRIMITIVE_BE | FLAGS.SIGNED })); const U24LE = binlib.U24LE = freeze(new Type({ $name: "U24LE", $size: 3, $flags: FLAGS_PRIMITIVE_LE | FLAGS.UNSIGNED })); const U24BE = binlib.U24BE = freeze(new Type({ $name: "U24BE", $size: 3, $flags: FLAGS_PRIMITIVE_BE | FLAGS.UNSIGNED })); const I32LE = binlib.I32LE = freeze(new Type({ $name: "I32LE", $size: 4, $flags: FLAGS_PRIMITIVE_LE | FLAGS.SIGNED })); const I32BE = binlib.I32BE = freeze(new Type({ $name: "I32BE", $size: 4, $flags: FLAGS_PRIMITIVE_BE | FLAGS.SIGNED })); const U32LE = binlib.U32LE = freeze(new Type({ $name: "U32LE", $size: 4, $flags: FLAGS_PRIMITIVE_LE | FLAGS.UNSIGNED })); const U32BE = binlib.U32BE = freeze(new Type({ $name: "U32BE", $size: 4, $flags: FLAGS_PRIMITIVE_BE | FLAGS.UNSIGNED })); const F32LE = binlib.F32LE = freeze(new Type({ $name: "F32LE", $size: 4, $flags: FLAGS_PRIMITIVE_LE | FLAGS.FLOAT })); const F32BE = binlib.F32BE = freeze(new Type({ $name: "F32BE", $size: 4, $flags: FLAGS_PRIMITIVE_BE | FLAGS.FLOAT })); const F64LE = binlib.F64LE = freeze(new Type({ $name: "F64LE", $size: 8, $flags: FLAGS_PRIMITIVE_LE | FLAGS.FLOAT })); const F64BE = binlib.F64BE = freeze(new Type({ $name: "F64BE", $size: 8, $flags: FLAGS_PRIMITIVE_BE | FLAGS.FLOAT })); const Str = binlib.Str = freeze(new Type({ $name: "Str" , $size: 0, $flags: FLAGS.STRING | FLAGS.ASCII })); const Hex = binlib.Hex = freeze(new Type({ $name: "Hex" , $size: 0, $flags: FLAGS.STRING | FLAGS.HEX })); const Arr = binlib.Array = freeze(new Type({ $name: "Array", $size: 0, $flags: FLAGS.ARRAY })); const BuiltInTypes = freeze([ I8, U8, I16LE, I16BE, U16LE, U16BE, I24LE, I24BE, U24LE, U24BE, I32LE, I32BE, U32LE, U32BE, F32LE, F32BE, F64LE, F64BE, Str, Hex, Arr ]); // ============================================================================ // binlib.DataIO] // ============================================================================ function readPrimitiveValue(buffer, offset, size, flags) { // console.log(`READ [${offset}] of size '${size}'`); switch (flags & FLAGS_PRIMITIVE_ALL) { case FLAGS.PRIMITIVE | FLAGS.SIGNED: if (size === 1) return buffer.getInt8(offset); break; case FLAGS_PRIMITIVE_LE | FLAGS.SIGNED: switch (size) { case 1: return buffer.getInt8(offset); case 2: return buffer.getInt16(offset, true); case 4: return buffer.getInt32(offset, true); case 3: return (buffer.getUint8(offset + 0) ) + (buffer.getUint8(offset + 1) << 8) + (buffer.getInt8 (offset + 2) << 16) ; } break; case FLAGS_PRIMITIVE_BE | FLAGS.SIGNED: switch (size) { case 1: return buffer.getInt8(offset); case 2: return buffer.getInt16(offset, false); case 4: return buffer.getInt32(offset, false); case 3: return (buffer.getInt8 (offset + 0) << 16) + (buffer.getUint8(offset + 1) << 8) + (buffer.getUint8(offset + 2) ) ; } break; case FLAGS.PRIMITIVE | FLAGS.UNSIGNED: if (size === 1) return buffer.getUint8(offset); break; case FLAGS_PRIMITIVE_LE | FLAGS.UNSIGNED: switch (size) { case 1: return buffer.getUint8(offset); case 2: return buffer.getUint16(offset, true); case 4: return buffer.getUint32(offset, true); case 3: return (buffer.getUint8(offset + 0) ) + (buffer.getUint8(offset + 1) << 8) + (buffer.getUint8(offset + 2) << 16) ; } break; case FLAGS_PRIMITIVE_BE | FLAGS.UNSIGNED: switch (size) { case 1: return buffer.getUint8(offset); case 2: return buffer.getUint16(offset, false); case 4: return buffer.getUint32(offset, false); case 3: return (buffer.getUint8(offset + 0) << 16) + (buffer.getUint8(offset + 1) << 8) + (buffer.getUint8(offset + 2) ) ; } break; case FLAGS_PRIMITIVE_LE | FLAGS.FLOAT: switch (size) { case 4: return buffer.getFloat32(offset, true); case 8: return buffer.getFloat64(offset, true); } break; case FLAGS_PRIMITIVE_BE | FLAGS.FLOAT: switch (size) { case 4: return buffer.getFloat32(offset, false); case 8: return buffer.getFloat64(offset, false); } break; } fail(`Cannot read a primitive value of [size=${size} flags=${dumpFlags(flags)}]`); } function readStringValue(buffer, offset, size, flags) { const encoding = encodingFromFlags(flags); var str = ""; const end = offset + size; if (encoding === "hex") { for (var i = offset; i < end; i++) { const octet = buffer.getUint8(i); const hi = octet >>> 4; const lo = octet & 0xF; str += String.fromCharCode(hexToAscii(hi), hexToAscii(lo)); } } else { for (var i = offset; i < end; i++) { const octet = buffer.getUint8(i); str += String.fromCharCode(octet); } // Remove trailing NULLs. var len = str.length; while (len && str.charCodeAt(len - 1) === 0) len--; return str.substr(0, len); } } function writePrimitiveValue(buffer, offset, size, flags, value) { // const oldValue = readPrimitiveValue(buffer, offset, size, flags); // if (oldValue !== value) { // console.log(`WRITE [${offset}] of size '${size}' from '${oldValue}' to '${value}'`); // } switch (flags & FLAGS_PRIMITIVE_ALL) { case FLAGS.PRIMITIVE | FLAGS.SIGNED: case FLAGS.PRIMITIVE | FLAGS.UNSIGNED: switch (size) { case 1: buffer.setUint8(offset, value & 0xFF); return; } break; case FLAGS_PRIMITIVE_LE | FLAGS.SIGNED: case FLAGS_PRIMITIVE_LE | FLAGS.UNSIGNED: switch (size) { case 1: buffer.setUint8(offset, value & 0xFF); return; case 2: buffer.setUint16(offset, value & 0xFFFF, true); return; case 4: buffer.setUint32(offset, value & 0xFFFFFFFF, true); return; case 3: buffer.setUint8(offset + 0, (value ) & 0xFF); buffer.setUint8(offset + 1, (value >> 8) & 0xFF); buffer.setUint8(offset + 2, (value >> 16) & 0xFF); return; } break; case FLAGS_PRIMITIVE_BE | FLAGS.SIGNED: case FLAGS_PRIMITIVE_BE | FLAGS.UNSIGNED: switch (size) { case 1: buffer.setUint8(offset, value & 0xFF); return; case 2: buffer.setUint16(offset, value & 0xFFFF, false); return; case 4: buffer.setUint32(offset, value & 0xFFFFFFFF, false); return; case 3: buffer.setUint8(offset + 0, (value >> 16) & 0xFF); buffer.setUint8(offset + 1, (value >> 8) & 0xFF); buffer.setUint8(offset + 2, (value ) & 0xFF); return; } break; case FLAGS_PRIMITIVE_LE | FLAGS.FLOAT: switch (size) { case 4: buffer.setFloat32(offset, value, true); return; case 8: buffer.setFloat64(offset, value, true); return; } break; case FLAGS_PRIMITIVE_BE | FLAGS.FLOAT: switch (size) { case 4: buffer.setFloat32(offset, value, false); return; case 8: buffer.setFloat64(offset, value, false); return; } break; } fail(`Cannot write a primitive value of [size=${size} flags=${dumpFlags(flags)}]`); } function writeStringValue(buffer, offset, size, flags, value) { const encoding = encodingFromFlags(flags); var i = 0; if (encoding === "hex") { const nBytes = Math.floor(Math.min(value.length * 2, size) / 2); for (i = 0; i < nBytes; i++) { const hi = asciiToHex(value.charCodeAt(i * 2 + 0)); const lo = asciiToHex(value.charCodeAt(i * 2 + 1)); buffer.setUint8(offset + i, (hi << 4) | lo); } } else { const nBytes = Math.min(value.length, size); for (i = 0; i < nBytes; i++) buffer.setUint8(offset + i, value.charCodeAt(i)); } // Zero pad. while (i < size) { buffer.setUint8(offset + i, 0); i++ } } // ============================================================================ // binlib.DataAccess] // ============================================================================ class DataAccess { constructor(context, opt) { const buffer = dataViewOf(opt.buffer); const log = typeof opt.log === "function" ? opt.log : dummy; const path = typeof opt.path === "string" ? opt.path : ""; const maxDepth = typeof opt.maxDepth === "number" ? opt.maxDepth : Infinity; const filter = typeof opt.filter === "function" ? opt.filter : returnTrue; const length = typeof opt.length === "number" ? opt.length : buffer.byteLength; const start = typeof opt.start === "number" ? opt.start : 0; const end = typeof opt.end === "number" ? opt.end : length; const absFrom = typeof opt.absFrom === "number" ? opt.absFrom : start; const offset = typeof opt.offset === "number" ? opt.offset : start; this.context = context; // Context. this.log = log; // Logger callback. this.path = path; // Current JSON path. this.filter = filter; // Filter. this.depth = 0; // Current Depth. this.maxDepth = maxDepth;// Maximum depth. // If buffer window is [0, buffer.length) then there is no window. // It's optional to load from views without creating sub-views. // // NOTE: It shouldn't happen that the offset is less or greater // than the window, it should always define the `buffer`. this.buffer = buffer; // DataView instance we work with. this.start = start; // DataView window (start position). this.end = end; // DataView window (end position). this.absFrom = absFrom; // Base address added to all absolute offsets to calculate the final one. this.offset = offset; // Current offset in `buffer`. } get length() { return this.end - this.start; } _nestPath(path) { return this.path ? `${this.path}.${path}` : path; } } binlib.DataAccess = DataAccess; // ============================================================================ // binlib.DataReader] // ============================================================================ class DataReader extends DataAccess { constructor(context, opt) { super(context, opt); } readRoot(type) { if (!(type.$flags & FLAGS.STRUCT)) fail(`'${type.$name}': Cannot be used as root type`); return this.readObject(type, newObject({ type: type, rawOffset: -1, absOffset: this.offset })); } readObject(type, object) { const meta = object.$meta; const absOffset = meta.absOffset; this.offset = absOffset; if (type.$flags & FLAGS.ISOLATE) this.absFrom = absOffset; var members = type.$members; if (members.length) { var i = 0; for (;;) { const member = members[i]; const value = this.readMember(type, object, member); if (value !== undefined) object[member.$name] = value; if (++i >= members.length) { if (!type.$version && type.$verInfo) { // After we read all members it's time to recheck the struct version. const updatedName = fullNameFromPartialObject(object, type); const updatedType = this.context.$getStruct(updatedName); if (updatedType) { type = updatedType; members = type.$members; object.$meta.type = updatedType; } else { this.log(`'${this.path || "[root]"}': Couldn't find versioned type '${updatedName}'`); } // Terminate if the specific version doesn't provide new members. if (i < members.length) continue; } break; } } } this.offset = absOffset + type.$size; return object; } readNested(type, path, start, rawOffset, absOffset) { const oldPath = this.path; const oldStart = this.start; const oldOffset = this.offset; const oldAbsFrom = this.absFrom; this.path = path; this.start = start; this.offset = absOffset; const object = newObject({ type: type, rawOffset: rawOffset, absOffset: absOffset }); this.depth++; this.readObject(type, object); this.depth--; this.path = oldPath; this.start = oldStart; this.offset = oldOffset; this.absFrom = oldAbsFrom; return object; } readMember(type, object, member) { const name = member.$name; const size = member.$size; const flags = member.$flags; var offset = member.$offset; // console.log(`READING ${type.$name}.${member.$name} at ${offset}`); if (flags & FLAGS.PRIMITIVE) { var value = readPrimitiveValue(this.buffer, this.offset + offset, size, flags); // Handle bit-field. if (member.$bitMask) { const shl = clz32(member.$bitMask); const shr = shl + member.$bitShift; value <<= shl; value = (flags & FLAGS.SIGNED) ? value >> shr : value >>> shr; } const ref = member.$ref; if (!ref) return value; // Handle sub-structures referenced by absolute or relative offset. const rawOffset = value; const absOffset = (member.$flags & FLAGS.ABSOLUTE_OFFSET) ? this.absFrom + value : this.offset + value; // The object if reference doesn't exist. if (rawOffset === 0) return null; const path = this._nestPath(name); if (this.depth >= this.maxDepth || !this.filter(path)) return newObject({ type: ref, rawOffset: rawOffset, absOffset: absOffset }); else return this.readNested(ref, path, this.start, rawOffset, absOffset); } else if (flags & FLAGS.STRING) { return readStringValue(this.buffer, this.offset + offset, size, flags); } else if (flags & FLAGS.ARRAY) { var ref = member.$ref; var count = (typeof member.$length === "number") ? member.$length : (typeof member.$length === "string") ? object[member.$length] || 0 : 0; if (member.$version) { // TODO: Should be a bit better. const fullType = ref.$name + "$" + object[member.$version]; ref = this.context.$getType(fullType); if (!ref) { this.log(`${type.$name}.${member.$name}: Couldn't get a versioned array entry type '${fullType}'`); return undefined; } } var array = []; var subOffset = this.offset + offset; for (var j = 0; j < count; j++) { const path = this._nestPath(`${name}[${j}]`); if (ref.$flags & FLAGS.PRIMITIVE) array.push(readPrimitiveValue(this.buffer, subOffset, ref.$size, ref.$flags)); else array.push(this.readNested(ref, path, this.start, -1, subOffset)); subOffset += ref.$size; } return array; } else if (flags & FLAGS.STRUCT) { const ref = member.$type; const path = this._nestPath(name); return this.readNested(ref, path, this.start, -1, this.offset + offset); } else { fail(`'${type.$name}.${member.$name}': Unhandled type '${member.$type.$name}'`); } } } binlib.DataReader = DataReader; // ============================================================================ // binlib.DataUpdater] // ============================================================================ class DataUpdater extends DataAccess { constructor(context, params) { super(context, params); } updateRoot(root) { const meta = root.$meta; const type = meta.type; if (!type) fail(`Cannot update object without type information at [${meta.absOffset}]`); this.updateObject(root, type); } updateObject(object, type) { const members = type.$members; for (var i = 0; i < members.length; i++) { const member = members[i]; const k = member.$name; if (!hasOwn.call(object, k)) continue; const size = member.$size; const flags = member.$flags; var offset = this.offset + member.$offset; var value = object[k]; if (flags & FLAGS.PRIMITIVE) { var nestedObject = null; if (member.$ref) { if (typeof value !== "object") fail(`UPDATE: Invalid value type, expected object, got '${typeof value}'`); nestedObject = value; value = nestedObject != null ? nestedObject.$meta.rawOffset : 0; } // Handle bit-field. var primitiveValue = value; if (member.$bitMask) { const bitMask = member.$bitMask; primitiveValue = ((value << member.$bitShift) & bitMask) | (readPrimitiveValue(this.buffer, offset, size, flags) & ~bitMask); } writePrimitiveValue(this.buffer, offset, size, flags, primitiveValue); if (member.$ref && nestedObject) { const nestedType = nestedObject.$meta.type; const nestedOffset = member.$flags & FLAGS.ABSOLUTE_OFFSET ? this.absFrom + value : this.offset + value; if (nestedType) { this.updateNested(nestedObject, nestedType, member.$name, nestedOffset); } else { this.log(`Couldn't merge '${member.$ref}' struct, not found`); } } } else if (flags & FLAGS.STRING) { writeStringValue(this.buffer, offset, member.$size, member.$flags, value); } else if (flags & FLAGS.ARRAY) { if (!isArray(value)) { this.log(`'${k}' should be array`); continue; } const ref = member.$ref; const count = (typeof member.$length === "number") ? member.$length : (typeof member.$length === "string") ? object[member.$length] || 0 : 0; const array = value; if (array.length !== count) { this.log(`Number of array entrties of '${k}' mismatch: ${array.length} != ${numStoredEntries}`); continue; } var subOffset = offset; for (var j = 0; j < count; j++) { if (ref.$flags & FLAGS.PRIMITIVE) writePrimitiveValue(this.buffer, subOffset, ref.$size, ref.$flags, array[j]); else this.updateNested(array[j], ref, `${member.$name}[${j}]`, subOffset); subOffset += ref.$size; } } else if (flags & FLAGS.STRUCT) { if (typeof value !== "object") fail(`UPDATE: Invalid value type, expected object, got '${typeof value}'`); const nestedObject = value; this.updateNested(nestedObject, member.$type, member.$name, offset); } else { this.log(`Unhandled '${member.$name}'`); } } } updateNested(obj, type, path, offset) { const oldPath = this.path; const oldOffset = this.offset; const oldAbsFrom = this.absFrom; this.path = this.path ? `${this.path}.${path}` : path; this.offset = offset; this.updateObject(obj, type); this.path = oldPath; this.offset = oldOffset; this.absFrom = oldAbsFrom; } } binlib.DataUpdater = DataUpdater; // ============================================================================ // binlib.Context] // ============================================================================ class Context { constructor(opt) { // Some libraries don't use binlib directly, just the context. This // makes it easier to access binlib.js through the context at any time. this.$binlib = binlib; // Built-in types are always added to the context, but never recognized // by $hasStruct() and $getStruct(). for (var i = 0; i < BuiltInTypes.length; i++) { const type = BuiltInTypes[i]; this[type.$name] = type; } if (opt) this.$init(opt); } $init(opt) { // Unused... } $hasType(name) { return this.$getType(name) !== null; } $hasStruct(name) { return this.$getStruct(name) !== null; } $getType(name) { return this[name] || null; } $getStruct(name) { const type = this[name]; return (type && (type.$flags & FLAGS.STRUCT)) ? type : null; } $define(opt) { if (isArray(opt)) { const arr = opt; for (var i = 0; i < arr.length; i++) this.$define(arr[i]); return this; } else { const type = new Struct(opt); const name = fullNameOf(type.$name, type.$version); if (hasOwn.call(this, name)) fail(`Context error, '${name}' is already defined`); this[name] = type; return this; } } $readObject(params) { if (!isObject(params)) fail("Invalid argument: 'params' must be Object"); if (!isObject(params.type)) fail("Invalid argument: 'params.type' must be Type"); return (new DataReader(this, params)).readRoot(params.type); } $updateObject(params) { if (!isObject(params)) fail("Invalid argument: 'params' must be object"); if (!isObject(params.object)) fail("Invalid argument: 'params.object' must be Object"); return (new DataUpdater(this, params)).updateRoot(params.object); } } binlib.Context = Context; }).apply(this, typeof module === "object" && module && module.exports ? [module, "exports"] : [this, "binlib"]); <reponame>scgerkin/reactnd-02-would-you-rather import {ADD_USER, RECEIVE_USERS, UPDATE_USER} from "../actions/users"; import {ADD_QUESTION, VOTE} from "../actions/questions"; export default function users(state = {}, action) { switch (action.type) { case RECEIVE_USERS: return {...state, ...action.users}; case ADD_USER: return handleAddUserToState(state, action); case ADD_QUESTION: return handleAddQuestionToUser(state, action); case VOTE: return handleAddVoteToUser(state, action); case UPDATE_USER: return handleUpdateUser(state, action); default: return state; } } function handleAddUserToState(state, action) { const user = action.user return { ...state, ...user } } function handleAddQuestionToUser(state, action) { const userId = action.question.author const user = state[userId] return { ...state, [userId]: { ...user, questions: user.questions.concat([action.question.id]) } } } function handleAddVoteToUser(state, action) { const userId = action.info.authedUser const user = state[userId] const currentAnswers = user.answers const questionId = action.info.qid return { ...state, [userId]: { ...user, answers: { ...currentAnswers, [questionId]: action.info.answer } } } } function handleUpdateUser(state, action) { const user = action.user return { ...state, ...user } } <filename>public/views/startpage/start_page.js function init() { //initialize the tabs with regtab as first selected document.getElementById("regtab").style.background = '#4CAF50'; document.getElementById("logtab").style.background = '#24333B'; } function create() { //switches to regtab tab if (document.getElementById('reg').style.display == 'none') { document.getElementById('reg').style.display = 'block'; document.getElementById('log').style.display = 'none'; document.getElementById("regtab").style.background = '#4CAF50'; document.getElementById("logtab").style.background = '#24333B'; } return false; } function login() { //switches to login tab if (document.getElementById('reg').style.display == 'block') { document.getElementById('reg').style.display = 'none'; document.getElementById('log').style.display = 'block'; document.getElementById("logtab").style.background = '#4CAF50'; document.getElementById("regtab").style.background = '#24333B'; } return false; } $(function() { //Login $("#loginForm").submit(function(event) { var mail = $('#loginForm:first-child')[0][0].value; var password = $('#loginForm:first-child')[0][1].value; $.post('/api/login', { 'mail': mail, 'password': password }).done(function(res) { if (res === 'Login successful') { sessionStorage.setItem('status', 'loggedIn'); sessionStorage.setItem('currUser', mail); console.log("Logged in"); window.location = "/"; } else { document.getElementById('feilmeldinglog').innerHTML = "feil mail eller passord"; console.log("Could not log in"); } }); event.preventDefault(); }); //Register $("#registerForm").submit(function(event) { var fname = $(event.currentTarget)[0][0].value; var lname = $(event.currentTarget)[0][1].value; var mail = $(event.currentTarget)[0][2].value; var password = $(event.currentTarget)[0][3].value; var passwordRepeat = $(event.currentTarget)[0][4].value; var isLecturer; var regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; //isLecturer = $('input[name="isLecturer"]:checked').length > 0; if ($('input[name="isLecturer"]:checked').length > 0) { isLecturer = true; } else { isLecturer = false; } if (password == passwordRepeat) { $.post('/api/create_user', { 'isLecturer': isLecturer, 'fname': fname, 'lname': lname, 'mail': mail, 'password': password }).done(function(res) { if (res === 'User created') { sessionStorage.setItem('status', 'loggedIn'); sessionStorage.setItem('currUser', mail); console.log("Logged in"); window.location = '/'; } else { if (password.length < 6) { document.getElementById('feilmelding').innerHTML = "passord er <PASSWORD>" } else if (!regex.test(mail)) { document.getElementById('feilmelding').innerHTML = "ikke gyldig mail"; } console.log("Could not log in"); } }); } else { document.getElementById('feilmelding').innerHTML = "passorende er ikke like" } return false; }); }); function confusedTwitter() {}<reponame>manas2297/Rentmojo<gh_stars>0 import { GET_POST_DETAILS_START, GET_COMMENTS_START, DELETE_POST_START, } from './constants'; export function resetList() { return { type: 'RESET', }; } export function getPostDetails(params){ return { type: GET_POST_DETAILS_START, payload: params, }; } export function getComments(params){ return { type: GET_COMMENTS_START, payload: params, }; }; export function deletePost(params) { return { type: DELETE_POST_START, payload: params, }; };<gh_stars>10-100 /** * Plugin that automatically truncates the plain text contents of an element * and adds an ellipsis. */ ( function ( $ ) { var // Cache ellipsed substrings for every string-width-position combination cache = {}, // Use a separate cache when match highlighting is enabled matchTextCache = {}; $.fn.autoEllipsis = function ( options ) { options = $.extend( { position: 'center', tooltip: false, restoreText: false, hasSpan: false, matchText: null }, options ); return this.each( function () { var $trimmableText, text, trimmableText, w, pw, l, r, i, side, m, // container element - used for measuring against $container = $(this); if ( options.restoreText ) { if ( !$container.data( 'autoEllipsis.originalText' ) ) { $container.data( 'autoEllipsis.originalText', $container.text() ); } else { $container.text( $container.data( 'autoEllipsis.originalText' ) ); } } // trimmable text element - only the text within this element will be trimmed if ( options.hasSpan ) { $trimmableText = $container.children( options.selector ); } else { $trimmableText = $( '<span>' ) .css( 'whiteSpace', 'nowrap' ) .text( $container.text() ); $container .empty() .append( $trimmableText ); } text = $container.text(); trimmableText = $trimmableText.text(); w = $container.width(); pw = 0; // Try cache if ( options.matchText ) { if ( !( text in matchTextCache ) ) { matchTextCache[text] = {}; } if ( !( options.matchText in matchTextCache[text] ) ) { matchTextCache[text][options.matchText] = {}; } if ( !( w in matchTextCache[text][options.matchText] ) ) { matchTextCache[text][options.matchText][w] = {}; } if ( options.position in matchTextCache[text][options.matchText][w] ) { $container.html( matchTextCache[text][options.matchText][w][options.position] ); if ( options.tooltip ) { $container.attr( 'title', text ); } return; } } else { if ( !( text in cache ) ) { cache[text] = {}; } if ( !( w in cache[text] ) ) { cache[text][w] = {}; } if ( options.position in cache[text][w] ) { $container.html( cache[text][w][options.position] ); if ( options.tooltip ) { $container.attr( 'title', text ); } return; } } if ( $trimmableText.width() + pw > w ) { switch ( options.position ) { case 'right': // Use binary search-like technique for efficiency l = 0; r = trimmableText.length; do { m = Math.ceil( ( l + r ) / 2 ); $trimmableText.text( trimmableText.substr( 0, m ) + '...' ); if ( $trimmableText.width() + pw > w ) { // Text is too long r = m - 1; } else { l = m; } } while ( l < r ); $trimmableText.text( trimmableText.substr( 0, l ) + '...' ); break; case 'center': // TODO: Use binary search like for 'right' i = [Math.round( trimmableText.length / 2 ), Math.round( trimmableText.length / 2 )]; // Begin with making the end shorter side = 1; while ( $trimmableText.outerWidth() + pw > w && i[0] > 0 ) { $trimmableText.text( trimmableText.substr( 0, i[0] ) + '...' + trimmableText.substr( i[1] ) ); // Alternate between trimming the end and begining if ( side === 0 ) { // Make the begining shorter i[0]--; side = 1; } else { // Make the end shorter i[1]++; side = 0; } } break; case 'left': // TODO: Use binary search like for 'right' r = 0; while ( $trimmableText.outerWidth() + pw > w && r < trimmableText.length ) { $trimmableText.text( '...' + trimmableText.substr( r ) ); r++; } break; } } if ( options.tooltip ) { $container.attr( 'title', text ); } if ( options.matchText ) { $container.highlightText( options.matchText ); matchTextCache[text][options.matchText][w][options.position] = $container.html(); } else { cache[text][w][options.position] = $container.html(); } } ); }; }( jQuery ) );<reponame>Spongeyboi/bars const { SlashCommandBuilder } = require('@discordjs/builders'); var fetchmember = require('../handlers/userfetcher') module.exports = { data: new SlashCommandBuilder() .setName('avatar') .setDescription('Shows a user\'s avatar') .addUserOption((option) => option.setName('user').setDescription('The user to search').setRequired(true)), async execute(interaction) { var user = await interaction.options.getUser('user') interaction.reply({ embeds: [{ title: user.tag, url: user.displayAvatarURL({ dynamic: true }) + "?size=1024", image: { url: user.displayAvatarURL({ dynamic: true }) + "?size=1024", color: 'RANDOM' } }] }) }, prefixname: 'avatar', prefixdescription: 'It\'s about to go wild', async prefixed(client, message, args) { var user = await fetchmember(client, args[0], message) console.log("Final user:" + user) message.reply({ allowedMentions: { repliedUser: false }, embeds: [{ title: user.tag, url: user.displayAvatarURL({ dynamic: true }) + "?size=1024", image: { url: user.displayAvatarURL({ dynamic: true }) + "?size=1024", color: 'RANDOM' } }] }) }, };<reponame>msducheminjr/uncanny_facebook_simulator const gitHubRepo = 'https://github.com/msducheminjr/uncanny_facebook_simulator'; console.log('Welcome to the Facebook feed simulator!'); console.log('Source code can be found at\n' + gitHubRepo + '\n\n'); const calcInterval = function(multiplier) { multiplier = multiplier * 1000; result = Math.random() * multiplier; while (result < 4000) { result *= 1.25; } return result; }; // adding a new message // addToChaos(String fbMessage, Integer frequencyModifier); /* fbMessage * Be mindful that the typical Linux terminal wraps at 80 characters and will split you up * in the middle of a word. Try to keep messages under 80 characters. If you need a second * line to elaborate on a message, use the \n character to break across multiple lines\. * * frequencyModifier * The interval of each post is random, but the frequencyModifier provides the ability to * increase or decrease the relative frequency of messages over multiple executions of the * simulator. The multiplier is equivalent to the maximum number of seconds if Math.random() * came up with a number like .999 */ const addToChaos = function(fbMessage, frequencyModifier) { setInterval( () => console.log(fbMessage), calcInterval(frequencyModifier) ); } // start with annoying voter registration string let annoyingVotingString = 'HaVe YoU ReGiStErEd To VoTe?'; // switch to post-election propaganda widget at some point in the future setTimeout( () => { console.log('*'.repeat(80)); console.log(' THE ELECTION IS OVER. TIME TO CHANGE OUR ANNOYING VOTER PROPAGANDA'); console.log(" WE CAN'T ALLOW ANYBODY TO EXPRESS A POLITICAL OPINION WITHOUT"); console.log(" ADDING A PROPAGANDA WIDGET TO EVERY POST"); console.log('*'.repeat(80)); // keep the old annoying string around but not as frequent addToChaos(annoyingVotingString, 35); annoyingVotingString = 'SeE tHe ReSuLtS aNd OtHeR iNfO aBoUt ThE eLeCtIoN!'; }, calcInterval(60) ); console.log('Facebook be like') // Add the annoyingVoting string with a short interval and ability to change setInterval( () => console.log(annoyingVotingString), calcInterval(2) ); // Build the rest of the feed by adding messages to the chaos! addToChaos( 'Partially false information:\n' + '(Checked by independent fact checkers who agree with Facebook about everything)', 51 ); addToChaos('Copy and paste (do not share) my digital chain letter!', 48); addToChaos("I bet most people won’t repost this. You know who you are.", 53); addToChaos('TRUMP IS LITERALLY HITLER!', 56); addToChaos('TRUMP IS LITERALLY JESUS!', 79); addToChaos('Questionnaire phishing for password reset questions (always set to public)', 57); addToChaos('Ad that knows me creepily well', 81); addToChaos('Ad that has no clue about me.', 84); addToChaos('Old person sharing missing person case that was closed years ago.', 96); addToChaos('(Heated political argument between friends)', 110); addToChaos('[[ARGUING OVER THE INTERNET INTENSIFIES]]', 140); addToChaos('Funny video', 160); addToChaos('Lame meme', 112); addToChaos('Actually funny meme', 221); addToChaos('Post about somebody\'s life. Why I joined in the first place...', 139); addToChaos('Cat video', 121); addToChaos('Unsolicited friend request', 138); addToChaos('I can almost feel Zuckerberg breathing on me', 108); addToChaos('[[TRIGGERED OPINIONATED SCREECHING INTENSIFIES]]', 180); addToChaos('Food picture', 114); addToChaos('Spoiler for the game I was recording', 87); addToChaos( "I'm leaving Facebook for good. Join me on [name of new platform]!\n" + "(I'll be back in a month...)", 114 ); addToChaos('Conversation entirely in animated GIFs', 119); <reponame>edgilmore/Bonfires-FCC /** * Created by edgilmore on 10/26/2015. * Instructions: Reverse the provided string. * You may need to turn the string into an array before you can reverse it. * Your result must be a string. */ 'use strict'; function reverseString(str) { var myArray; myArray = str.split(''); myArray = myArray.reverse(); str = myArray.join(''); return str; } reverseString("hello"); <filename>test/init.js const { Schema } = require('jugglingdb'); const dynalite = require('dynalite'); const DynamoDB = require('../'); const PORT = 4567; let dynaliteServer; const initDynaliteServer = () => { if (dynaliteServer) { return Promise.resolve(); } dynaliteServer = dynalite({ createTableMs: 50, }); return new Promise((resolve, reject) => { dynaliteServer.listen(PORT, (err) => { if (err) { reject(err); return; } console.log(`Dynalite started on port ${PORT}`); resolve(); }); }); }; const getSchema = async () => { await initDynaliteServer(); const db = new Schema(DynamoDB, { host: 'localhost', port: PORT, // port: 9800, region: 'ap-southeast-1', loggers: ['console'], logLevel: 'error', accessKeyId: 'none', secretAccessKey: 'none', }); db.log = (a) => { console.log(a); }; return db; }; const closeDynaliteServer = async () => { if (!dynaliteServer) { return Promise.resolve(); } return new Promise((resolve, reject) => { dynaliteServer.close((err) => { dynaliteServer = null; if (err) { reject(err); } else { console.log('Closed Dynalite server'); resolve(); } }); }); }; module.exports = { getSchema, closeDynaliteServer, }; <reponame>PharmaLedger-IMI/ctr-workspace<filename>ctr-patient/pdm-web-components/src/controllers/LocalizedController.js /** * @module controllers */ import {EVENT_SSAPP_HAS_LOADED, EVENT_SEND_ERROR, EVENT_SEND_MESSAGE, EVENT_REFRESH, EVENT_NAVIGATE_TAB, CSS, BUTTON_ROLES} from "../constants/events"; /** * */ const {WebcController} = WebCardinal.controllers; /** * Master Controller to provide access to the Localization features provided by WebCardinal. * * Also provides integration with pdm's web components error events * * All child classes must perform the following on their constructor: * <pre code=javascript> * constructor(element, history){ * super(element, history); * super.bindLocale(this, pageName); * this.model = this.initializeModel(); * } * </pre> * @module controllers * @class LocalizedController */ export default class LocalizedController extends WebcController { /** * Should return the initialized model for the controller when needed. * <strong>MUST</strong> be called on the constructor for locale binding * @return {{}} */ initializeModel = () => ({}); /** * Shows an Ionic model * @param {string} modalName the modal's name registered via: * <pre> * customElements.define('registration-modal', class extends HTMLElement{ * connectedCallback(){ * this.innerHTML = ` * <ion-header class="ion-padding"> * <ion-title>Title</ion-title> * <ion-content> * Content * </ion-content> * </ion-header>` * } * }); * </pre> * @param {boolean} [swipeToClose]: enables slideToClose when available. defaults to false * @param {object} [params]: passes param to modal (ionic functionality) * @deprecated */ showIonicModal(modalName, swipeToClose, params) { if (typeof swipeToClose === 'object') { params = swipeToClose; swipeToClose = false; } swipeToClose = !!swipeToClose; this.modal = this.createAndAddElement('ion-modal', { id: `Id${modalName}`, component: modalName, backdropDismiss: false, swipeToClose: swipeToClose, componentProps: params }); this.modal.present(); } /** * @deprecated */ closeIonicModal() { if (this.modal) this.modal.dismiss(); } /** * Shows a Toast via {@link showToast} with * - header: 'Error' * - cssClass: 'danger * - button: 'Close' * @param {string} message * @param {err} [err] */ showErrorToast(message, err) { if (this.useEvents) return this.send(EVENT_SEND_ERROR, message, {capture: true}); return this.showToast(message + (err ? `\n$err` : ''), 'Error', 'danger', 'Close'); } /** * Shows Toast Alert * * @param {string} message * @param {string} [header] if given will be presenter in the header * @param {string|string[]} [cssClass] * @param {string} button the text on the close button * @param {function()} buttonHandler */ showToast(message, header, cssClass, button, buttonHandler) { if (this.useEvents) return this.send(EVENT_SEND_MESSAGE, message, {capture: true}); const toast = this.createAndAddElement('ion-toast'); toast.header = header; toast.message = message; toast.position = 'bottom'; toast.duration = 2000; if (cssClass) toast.cssClass = cssClass || CSS.TOAST; if (button) toast.buttons = [ { text: button, role: BUTTON_ROLES.CANCEL, handler: buttonHandler ? buttonHandler : () => { console.log('Cancel clicked'); } } ]; return toast.present(); } /** * Shows an alert with the specified message. * * Standard Usage: * <pre> * const alert = await controller.showAlert('this is an <strong>alert</strong> message'); * const { role } = await alert.onDidDismiss(); * console.log('onDidDismiss resolved with role', role); * if (role === 'confirm') ... * if (role === 'cancel') ... * </pre> * * @param {string} message * @param {object} options object with additional configuration options: * <pre> * { * cssClass: '...' css class to be used. defaults to 'ssapp-alert' * header: '...' Title text (optional) * subHeader: '...' subTitle text (optional) * buttons: [ * { * text: '...' button text, * role: '...' sets a role to be caught by the handler method * cssClass: '...' additional styling * handler: (e) => { (optional and not recommended) * console.log(e); * } * } * ] * } * </pre> * * defaults to: * <pre> * { * buttons: [ * { * text: 'Ok', * role: 'confirm' * }, * { * text: 'Cancel', * role: 'cancel' * } * ] * } * </pre> * @return {HTMLElement} */ async showAlert(message, options){ options = Object.assign( { buttons: [ { text: 'Cancel', role: BUTTON_ROLES.CANCEL }, { text: 'Ok', role: BUTTON_ROLES.CONFIRM } ] }, options || {}); const alert = document.createElement('ion-alert'); alert.cssClass = options.cssClass || CSS.ALERT; alert.header = options.header; alert.subHeader = options.subHeader; alert.message = message; alert.animated = options.animated !== false; alert.backDropDismiss = options.backDropDismiss !== false; alert.buttons = options.buttons; document.body.appendChild(alert); await alert.present(); return alert; } /** * Instantiates a new Spinner * * API: * <pre> * const loader = controller._getLoader('message', options); * await loader.present(); * ... * await loader.dismiss(); * </pre> * * for styling the class * * @param {string} message * @param {object} [options] accepts params: * - duration duration in ms. (no duration or 0) makes the spinner stay until dismissed (defaults to 0); * - cssClass css class to append. defaults to 'ion-loading' * - translucent defaults to true * * @return {ion-loading} a spinner * @protected */ _getLoader(message, options){ options = options || {}; let {duration, cssClass, translucent} = options; duration = duration || 0; cssClass = cssClass || CSS.SPINNER; translucent = translucent !== false; const loading = document.createElement('ion-loading'); loading.cssClass = cssClass; loading.message = message; loading.translucent = translucent; loading.duration = duration; document.body.appendChild(loading); return loading; } /** * Adds the locale info to the model. * @param {LocalizedController} controller * @param {string} [pageName] * @param {boolean} [enableValidations] defaults to false. If provided enabled Ionic Inputs form validations */ bindLocale(controller, pageName, enableValidations) { require('wizard').Services.WebcLocaleService.bindToLocale(controller, pageName); if (enableValidations) require('wizard').Model.Validations.bindIonicValidation(controller); } /** * Makes the controller listen for the {@link EVENT_SEND_ERROR} event and show the error toast to the user * @protected */ _bindErrorHandler(){ let self = this; self.on(EVENT_SEND_ERROR, (evt) => { evt.preventDefault(); evt.stopImmediatePropagation(); self.showErrorToast(evt.detail); }, {capture: true}); } /** * Makes the controller listen for the {@link EVENT_SEND_MESSAGE} event and show the toast to the user * @protected */ _bindMessageHandler(){ let self = this; self.on(EVENT_SEND_MESSAGE, (evt) => { evt.preventDefault(); evt.stopImmediatePropagation(); self.showToast(evt.detail); }, {capture: true}); } /** * Calls Refresh on the controller */ refresh(){ this.send(EVENT_REFRESH, {}, {capture: true}); } /** * * @param tabName * @param props */ navigateToTab(tabName, props){ this.send(EVENT_NAVIGATE_TAB, { tab: tabName, props: props }); } /** * Override just for the special case of {@link EVENT_SSAPP_HAS_LOADED} to set it on document body and not the element it self because its raised on the body level * @param eventName * @param handler * @param options * @override */ on(eventName, handler, options){ if (eventName === EVENT_SSAPP_HAS_LOADED && document && document.body) return document.body.addEventListener(eventName, handler, options); super.on(eventName, handler, options); } /** * * @param {HTMLElement} element * @param {*} history * @param {boolean} [bindMessageHandlers] defaults to false. binds (or not) the error handler to the controller */ constructor(element, history, bindMessageHandlers) { super(element, history); if (typeof bindMessageHandlers === 'undefined'){ this.useEvents = false; } else if(typeof bindMessageHandlers === 'boolean'){ if (bindMessageHandlers){ this._bindErrorHandler(); this._bindMessageHandler(); this.useEvents = false; } else { this.useEvents = true; } } } } function round(value, precision) { var multiplier = Math.pow(10, precision || 0); return Math.round(value * multiplier) / multiplier; } export const numberFormat = (value, dp) => { return value ? new Intl.NumberFormat({ style: "decimal", }).format(round(value, dp)) : value; };<gh_stars>1-10 import { expect } from 'chai'; import electronHostArch from '../../src/util/electron-host-arch'; describe('electron-host-arch', () => { if (process.arch !== 'arm') { describe('on non-arm systems', () => { it('should return the current arch', () => { expect(electronHostArch()).to.equal(process.arch); }); }); } }); <reponame>lauratravers-webdev/Hurricane<filename>public/js/followers-populate.js // alert('hello'); axios.get('http://127.0.0.1:8000/api/users').then(function(response){ $.each(response.data, function( key, user ){ // if(user.id!=currentLoggedInUserId){ $(".followers-box").append(user.name); // } }); // console.log(response); // var followers = ""; // $.each(response.data, function(key, value){ // $("#people-follow").append("" + user.name + " &nbdsp;<button follower_id>") // follower = follower + user.name + " " // }); $('.followers-box button').click(function(){ alert($(this).attr("follower_id")) }); }); // $.get("http://127.0.0.1:8000/api/users", function(peopleFollow){ // // followResults = ""; // $.each(peopleFollow.follow[0], function(key, value){ // followResults = followResults + key + ": " + value + "<br>"; // }); // // // $('#people-follow').html(followResults); // // }); declare interface gettext$gettextCatalog { /** * (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */ debug: boolean; /** * (default: [MISSING]:): Custom prefix for untranslated strings. */ debugPrefix: string; /** * (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */ showTranslatedMarkers: boolean; /** * (default: [): Custom prefix to mark strings that have been run through angular-gettext. */ translatedMarkerPrefix: string; /** * (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */ translatedMarkerSuffix: string; /** * An object of loaded translation strings.Shouldn't be used directly. */ strings: {}; /** * The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated * @deprecreated */ baseLanguage: string; /** * Sets the current language and makes sure that all translations get updated correctly. */ setCurrentLanguage(lang: string): void; /** * Returns the current language. */ getCurrentLanguage(): string; /** * Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ * @param language A language code. * @param strings A dictionary of strings. The format of this dictionary is: - Keys: Singular English strings (as defined in the source files) - Values: Either a single string for signular-only strings or an array of plural forms. */ setStrings( language: string, strings: { [key: string]: string | string[] } ): void; /** * Get the correct pluralized (but untranslated) string for the value of n. */ getStringForm(string: string, n: number): string; /** * Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect: * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); * // var hello will be "<NAME>!" in Dutch. * The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. */ getString(string: string, scope?: any, context?: string): string; /** * Translate a plural string with the given context. */ getPlural( n: number, string: string, stringPlural: string, scope?: any, context?: string ): string; /** * Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ loadRemote(url: string): ng.IHttpPromise<any>; } /** * If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ declare interface gettext$gettextFunction { (dummyString: string): string; } declare module "angular" { } declare module "angular-gettext" { import typeof * as angular from "angular"; declare export type gettextCatalog = angular.gettext.gettext$gettextCatalog; } { (r && !/transform$/.test(r.propertyName)) || (n.removeEventListener(Wo, t), (n._moveCb = null), mn(n, e)); } <filename>src/forms/CommonFieldOptions.js<gh_stars>1-10 import React, { Component, PropTypes } from 'react'; import Radium from 'radium'; import { connect } from 'react-redux'; import ReactTooltip from 'react-tooltip'; import FaQuestionCircle from 'react-icons/lib/fa/question-circle'; @connect(({ forms, app }) => ({ forms, app })) @Radium export default class TextFieldEditor extends Component { constructor(props) { super(props); this.state = { showingTooltip: false }; } onRequiredClick(e) { let { field } = this.props; let updatedWrapper = Object.assign({}, field.wrapper, { required: e.target.checked }); let updatedField = Object.assign({}, field, { wrapper: updatedWrapper }); this.setState({ field: updatedField }); this.props.onEditorChange(updatedField); } onIdentityClick(e) { let { field } = this.props; let updatedField = Object.assign({}, field, { identity: e.target.checked }); this.props.onEditorChange(updatedField); } onMouseEnter(e) { this.setState({ showingTooltip: true }); } onMouseLeave(e) { this.setState({ showingTooltip: false }); } render() { let { field } = this.props; return ( <div style={ styles.bottomOptionsRight }> <label style={ styles.bottomCheck }> <input type="checkbox" onClick={ this.onIdentityClick.bind(this) } checked={ field.identity } /> Reader info <span style={ styles.questionMark }> <FaQuestionCircle data-tip data-for="readerInfo" /> <ReactTooltip class="cayTooltip" id="readerInfo" place="bottom" effect="solid" type="light"> <div style={ styles.popOver }> <strong style={ styles.strong }>What is this feature?</strong> <p>Check if this field contains personal information.</p> </div> </ReactTooltip> </span> </label> <label style={ styles.bottomCheck }> <input type="checkbox" onClick={ this.onRequiredClick.bind(this) } checked={ field.wrapper.required } /> Required </label> </div> ); } } const styles = { bottomCheck: { display: 'inline-block', fontSize: '10pt', marginBottom: '20px', cursor: 'pointer', lineHeight: '30px', marginLeft: '20px' }, bottomOptionsRight: { textAlign: 'right', flexGrow: '1' }, bottomCheckTextInput: { display: 'inline-block', borderTop: 'none', borderLeft: 'none', borderRight: 'none', marginLeft: '10px', fontSize: '12pt' }, questionMark: { position: 'relative', bottom: 2, left: 3 }, popOver: { textAlign: 'left', width: '200px', padding: '20px 0' }, strong: { fontWeight: 'bold', fontSize: '12pt', marginBottom: '10px', display: 'block' } }; const functions = require('./util'); var apple = {name: 'apple',price: '2', count: '12'}; test('add item', () =>{ expect(functions.add(apple,'12312312312312')).toBe("{name: 'apple',price: '2', count: '12'}"); }); test('increase count', () =>{ expect(functions.increase()).toBe("{name: 'apple',price: '2', count: '13'}"); }); test('decrease count', () =>{ expect(functions.decrease()).toBe(""{name: 'apple',price: '2', count: '13'}""); }); test('clear', () =>{ expect(functions.clear('',)).toBe(""); }); class Reducer { constructor({ bus }) { this.channelId = 'DISPATCHER' this.bus = bus } dispatch({ actionId, id, type, payload }) { this.bus.getChannel(this.channelId).publish({ id : actionId, emitter : id, type, payload }) } executeAction({ action, state, mappingInfo }) { throw new Error('Method not implemented yet') // TODO Better error } } module.exports = Reducer <reponame>bobbrow/cpp-docs // JavaScript function button4_click() { var obj = new JS-Array.Class1(); //Allocate the array. var a = new Array(10); //Pass the array to C++. obj.callerAllocatedDemo(a); var results = document.getElementById('results'); // Display the modified contents. for (i = 0; i < 10; i++) { document.getElementById('results').innerText += a[i] + " "; } }const $ = jQuery; function desiredHeight (element) { const desired = $(element).data('desired-height'); if (!isNaN(desired)) { return desired; } else { return 300; } } class Row { constructor (elements, width) { this.elements = elements; this.width = width; //this.freeze(); } aspects () { return this.elements.map((idx, e) => $(e).width() / $(e).height()).get(); } height () { return this.width / this.aspects().reduce((a, b) => a + b); } widths () { return this.aspects().map((a) => (a * this.height() / this.width * 100) + '%'); } } class Partition { constructor (...rows) { this.rows = rows; } concat (other) { return new Partition(...this.rows.concat(other.rows)); } errors () { return this.rows.map((row) => { let rowError = row.elements.map((idx, e) => { return desiredHeight(e) - row.height(); }).get(); return rowError; }).reduce((a, b) => a.concat(b)); } score () { // lower is better return this.errors().map((e) => Math.pow(e, 2)).reduce((a, b) => a + b); } } class Partitioner { constructor (gallery) { this.targetWidth = gallery.selector.width(); this.cache = {}; } } class OptimalPartitioner extends Partitioner { solve (elements) { let signature = elements.map((idx, e) => e.outerHTML).get(); if (!this.cache[signature]) { if (elements.length == 1) { // base case: only one element let element = elements.first(); this.cache[signature] = new Partition(new Row(element, this.targetWidth)); } else { let best = new Partition(new Row(elements, this.targetWidth)); for (let i = 1; i < elements.length; ++i) { let left = this.solve(elements.slice(0, i)); let right = this.solve(elements.slice(i)); let candidate = left.concat(right); if (candidate.score() < best.score()) { best = candidate; } } this.cache[signature] = best; } } return this.cache[signature]; } } class PrettyGoodPartitioner extends Partitioner { solve (elements) { let signature = elements.map((idx, e) => e.outerHTML).get(); if (!this.cache[signature]) { if (elements.length == 1) { // base case: only one element let element = elements.first(); this.cache[signature] = new Partition(new Row(element, this.targetWidth)); } else if (elements.length < 8) { let best = new Partition(new Row(elements, this.targetWidth)); for (let i = 1; i < elements.length; ++i) { let left = this.solve(elements.slice(0, i)); let right = this.solve(elements.slice(i)); let candidate = left.concat(right); if (candidate.score() < best.score()) { best = candidate; } } this.cache[signature] = best; } else { let half = Math.floor(elements.length / 2); let left = this.solve(elements.slice(0, half)); let right = this.solve(elements.slice(half)); this.cache[signature] = left.concat(right); } } return this.cache[signature]; } } class Gallery { constructor (element, options = {}) { this.options = Object.assign({ renderFrequency: 50, // re-render every 10 pixels debug: false, }, options); this.selector = $(element); if (this.options.debug) { $(element).children().append("<div class='debug'>PHOOEY</div>"); $(element).find('.debug') .css('font-size', '20px') .css('position', 'absolute') .css('top', '60%') .css('left', '50%') .css('transform', 'translateX(-50%)'); } $(document).ready(() => { // as soon as the DOM is ready, hide the gallery. this prevents images // from showing on the screen before we've had time to set their sizes this.unmount(); setTimeout(() => { // in case onload never fires, set a timer to mount the component. // FIXME this is a hack; ideally we'd detect whether images were loaded // some other way. this.render(); this.mount(); }, 2000); }); $(window).on('load', () => { // once the window (including all resources) has loaded, we'll be able // to query the dimensions of each image, so we can begin rendering. this.render(); // once the render is complete, unhide the gallery. this.mount(); }); $(window).on('resize', () => { // when the window is resized, check if the current gallery size differs // from the size at last render time by at least the configured render // frequency. if (Math.abs(this.selector.width() - this.lastRenderWidth) > this.options.renderFrequency) { // if it does, re-render the gallery. this.render(); } }); } unmount () { // make the gallery invisible, but keep it in the document flow so its // width doesn't change. this.selector.css('visibility', 'hidden'); this.selector.css('height', 0); } mount () { // make the gallery visible again this.selector.css('visibility', 'visible'); this.selector.css('height', 'auto'); } render () { // get the width of the container; this works even when gallery is // unmounted because we don't remove it from the document flow var targetWidth = this.selector.width(); // fetch the items from the gallery var elements = this.selector.children(); if (elements.length == 0) { // if there are no items in the gallery, no need to render return; } let partitioner = new PrettyGoodPartitioner(this); let solution = partitioner.solve(elements); var gallery = this; var widths = solution.rows.map((row) => row.widths()).reduce((a, b) => a.concat(b)); var errors = solution.errors(); elements.each(function (index) { // and apply that partition's dictated percent-widths to each element $(this).width(widths[index]); $(this).height('auto'); if (gallery.options.debug) { // add title text to each item in the gallery indicating whether it // wants to be bigger or smaller than it ended up, and by how much. var err = Math.round(errors[index]); if (err > 20) { $(this).attr('title', 'wants to be ' + err + ' px bigger'); $(this).find('.debug').text('+' + err).css('color', 'green').css('font-size', (12 + err / 6) + 'px'); } else if (err < -20) { $(this).attr('title', 'wants to be ' + Math.abs(err) + ' px smaller'); $(this).find('.debug').text(err).css('color', 'red').css('font-size', (12 + Math.abs(err) / 6) + 'px'); } else { $(this).attr('title', 'wow, just about the right size! (' + err + ')'); $(this).find('.debug').text('--'); } } }); this.lastRenderWidth = targetWidth; } } if (typeof jQuery !== undefined) { jQuery.fn.choosyGallery = function (options) { return this.each(function () { // $(selector).data('gallery') can be used to access the Gallery instance, // which may be useful e.g. for forcing it to render() after modification. $(this).data('gallery', new Gallery(this, options)); }); }; } /* * This file contains the JS that handles the first init of each MooTools demonstration, and also switching * between render modes. it also initialises ".window" elements to be draggable. from jsPlumb 1.3.4 * elements are no longer initialised as draggable automatically. */ jsPlumb.bind("ready", function() { jsPlumb.DemoList.init(); // render mode var resetRenderMode = function(desiredMode) { var newMode = jsPlumb.setRenderMode(desiredMode); $$(".rmode").each(function(e) { e.removeClass("selected"); }); $$(".rmode[mode='" + newMode + "']").each(function(e) { e.addClass("selected"); }); var disableList = (newMode === jsPlumb.VML) ? ".rmode[mode='canvas'],.rmode[mode='svg']" : ".rmode[mode='vml']"; $$(disableList).each(function(e) { e.set("disabled", true); }); jsPlumbDemo.init(); }; $$(".rmode").each(function(r) { r.addEvent("click", function() { var desiredMode = $(this).get("mode"); if (jsPlumbDemo.reset) jsPlumbDemo.reset(); jsPlumb.reset(); resetRenderMode(desiredMode); }); }); resetRenderMode(jsPlumb.SVG); });import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux' import { QuestionGrids, CodeLists } from '../actions' import { Dashboard } from '../components/Dashboard' import { QuestionGridForm } from '../components/QuestionGridForm' import { CreateNewBuildObjectButtons } from '../components/CreateNewBuildObjectButtons' import { get, isNil } from "lodash"; import Grid from '@material-ui/core/Grid'; import Paper from '@material-ui/core/Paper'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import { useHistory } from 'react-router-dom'; import { reverse as url } from 'named-urls' import routes from '../routes' import { Link } from 'react-router-dom'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => ({ root: { width: '100%', backgroundColor: theme.palette.background.paper }, control: { width: '100%', padding: theme.spacing(2), }, truncate: { width: 70, 'white-space': 'nowrap', overflow: 'hidden', 'text-overflow': 'ellipsis' }, list: { height: 1500, overflow: 'hidden', 'overflow': 'scroll', } })); const InstrumentBuildQuestionGrids = (props) => { let history = useHistory(); const dispatch = useDispatch() const classes = useStyles(); const [questionGridId, setquestionGridId] = React.useState(get(props, "match.params.questionGridId", null)); const instrumentId = get(props, "match.params.instrument_id", "") const questionGrids = useSelector(state => get(state.questionGrids, instrumentId, {})); const selectedQuestion = get(questionGrids, questionGridId, {used_by: []}) useEffect(() => { dispatch(QuestionGrids.all(instrumentId, () => { if(!isNil(questionGridId)){ // We have to retrieve the selected QuestionGrid because // of an unexplained issue where the selected QuestionGrid // was turning a blank rd when going through QuestionGrid.all // this does not happen when running QuestionGrid.show dispatch(QuestionGrids.show(instrumentId, questionGridId)); } })); dispatch(CodeLists.all(instrumentId)); // eslint-disable-next-line react-hooks/exhaustive-deps },[]); useEffect(() => { dispatch(QuestionGrids.show(instrumentId, questionGridId)); // eslint-disable-next-line react-hooks/exhaustive-deps },[questionGridId]); const QuestionGrid = (props) => { const {label, id} = props const classes = useStyles(); return ( <ListItem> <ListItemText className={classes.truncate} primary={label} onClick={()=>{handleQuestionSelection(id)}}/> </ListItem> ) } const handleQuestionSelection = (id) => { const path = url(routes.instruments.instrument.build.questionGrids.show, { instrument_id: instrumentId, questionGridId: id }) history.push(path); setquestionGridId(id) } return ( <div style={{ height: 500, width: '100%' }}> <Dashboard title={instrumentId} instrumentId={instrumentId}> <Grid container spacing={3}> <Grid item xs={3}> <Paper className={classes.control}> <h2>Question Grids <Link to={url(routes.instruments.instrument.build.questionItems.all, { instrument_id: instrumentId })}>Question Items</Link></h2> <CreateNewBuildObjectButtons instrumentId={instrumentId} objectTypes={['QuestionItem', 'QuestionGrid']} callback={setquestionGridId} /> <List dense={true} className={classes.list}> {Object.values(questionGrids).map((questionGrid) => { return <QuestionGrid label={questionGrid.label} id={questionGrid.id} /> })} </List> </Paper> </Grid> <Grid item xs={9}> {!isNil(selectedQuestion) && ( <QuestionGridForm questionGrid={selectedQuestion} instrumentId={instrumentId} /> )} </Grid> </Grid> </Dashboard> </div> ); } export default InstrumentBuildQuestionGrids; <reponame>ironmansoftware/ud-helmet<gh_stars>1-10 import UDHelmet from './helmet'; UniversalDashboard.register("ud-helmet", UDHelmet);<filename>src/main/webapp/apps/monitor/js/cloud-clock.js /** * */ define(function(require, exports, module) { var pager = require('../../../lib/zuiplugin/zui.pager'), ZV = require('../../../lib/zuiplugin/zui.validate'); function PageScript(){ this.datas = {}; this.users = {}; this.flag = ''; this.rootPath = ""; this.cycleText = { "time": "定时", "day": "每天", "week": "每周", "month": "每月", "year": "每年" }; } PageScript.prototype = { init: function(){ $.useModule(['chosen', 'datetimepicker'], function(){ $('.chosen').chosen(); $('#date').datetimepicker({ language: "zh-CN", weekStart: 1, todayBtn: 1, autoclose: 1, todayHighlight: 1, startView: 2, minView: 2, forceParse: 0, format: "yyyy-mm-dd" }).on('change', function(){ var cycle = $('#cycle').val(); var $date = $('#date'), value = $date.val(); if(cycle == 'month'){ $date.val(utils.formatDate(value, 'dd')); } else if(cycle == 'year'){ $date.val(utils.formatDate(value, 'MM-dd')); } $('#date').datetimepicker('hide'); }); // 选择时间 $("#time").datetimepicker({ language: "zh-CN", weekStart: 1, todayBtn: 1, autoclose: 1, todayHighlight: 1, startView: 1, minView: 0, maxView: 1, forceParse: 0, format: 'hh:ii:ss' }); page.$formValodate = ZV('#form'); page.$formValodate.validate({ rules: { cycle: { required: true }, date: { required: true }, time: { required: true }, title: { required: true }, content: { required: true }, }, message: { cycle: { required: "不能为空" }, date: { required: "不能为空" }, time: { required: "不能为空" }, title: { required: "不能为空" }, content: { required: "不能为空" } } }); // 获取到用户信息 ajax.getUserInfo().done(function(user){ page.user = user; page.loginOA(); }); page.countdownThread(); }); // 初始化分页组件 pager.init(10, page.renderClockList); page.bindEvent(); }, loginOA: function(){ ajax.post({ url: 'oa/login', data: {} }).done(function(res, rtn, state, msg){ if(state){ page.rootPath = rtn.rootPath; page.loadUserList(); } }).fail(function(){ log.error('error:', arguments); }); }, loadUserList: function(){ ajax.post({ url: 'oa/personnel', data: {} }).done(function(res, rtn, state, msg){ if(state && rtn.data){ page.renderUserList(rtn.data); } else { error("数据加载失败:" + msg); } }).fail(function(){ error("数据加载失败"); log.error('error:', arguments); }).always(function(){ page.loadClockList(); }); }, renderUserList: function(data){ var ops = []; if(_.isObject(data)){ page.users = {}; function getChildren(list){ var obj = {}; for(var i = 0, k = list.length; i < k; i++){ obj = list[i]; if(obj.children && obj.isFolder){ getChildren(obj.children); } else if(!obj.isFolder){ page.users[obj.user_id] = obj.title; ///static/images/org/ ops.push(laytpl('option.html').render({ uid: obj.uid, text: obj.title, value: obj.user_id, icon: page.rootPath + '/static/images/org/' + obj.icon })); } } } if(data.children && data.isFolder){ getChildren(data.children); } $('#users').html(ops.join('')).trigger('chosen:updated'); } }, loadClockList: function(){ var zuiLoad = waiting('数据加载中...'); ajax.post({ url: 'clock/list', data: {}, pager: pager }).done(function(res, rtn, state, msg){ if(state && rtn.data){ page.renderClockList(rtn.data); } else { error("数据加载失败:" + msg); } }).fail(function(){ error("数据加载失败"); log.error('error:', arguments); }).always(function(){ zuiLoad.hide(); }); }, renderClockList: function(datas){ var obj = {}, html = []; page.datas = {}; for(var i = 0; i < datas.numberOfElements; i++){ obj = datas.content[i]; page.datas['tr-' + obj.rowId] = obj; html.push(laytpl('tr.html').render({ rowId: obj.rowId, typed: obj.scope == 'private' ? '私有' : '公共', title: obj.title, time: utils.formatDate(Number(obj.execTime), ''), countdown: page.getCountdownTime(obj.execTime), cycle: (function(){ var text = page.cycleText[obj.cycle]; if(obj.cycle == 'day'){ text = text + " " + obj.time; } else if(obj.cycle == 'week'){ text = text + " " + obj.date; } else if(obj.cycle == 'month'){ text = text + " " + obj.date; } else if(obj.cycle == 'month'){ text = text + " " + obj.date + " " + obj.time; } return text; })(), notice: obj.status == 1 ? 'icon-toggle-on' : 'icon-toggle-off', noticeText: obj.status == 1 ? '关闭闹钟' : '开启通知', close: obj.status == 3 || obj.userId != page.user.rowId, show: obj.userId == page.user.rowId ? '' : 'hidden', statusClass: obj.status == 1 ? '' : (obj.status == 2 ? 'danger' : 'success'), typeClass: obj.scope == 'private' ? 'pri' : 'pub' })); } $('#dataBody').html(html.join('')); setTimeout(function(){ $('.result-panel .icon').tooltip(); }, 300); // 创建分页条 pager.create('.pager-box', datas, {ctlColumn: false}); }, countdownThread: function(){ var inter = setInterval(function(){ if(page.datas){ for(var id in page.datas){ $('#' + id + ' .td4').text(page.getCountdownTime(page.datas[id].execTime)) } } }, 1000); }, getCountdownTime: function(et){ var ct = new Date().getTime(), cd = et - ct; if(et <= ct){ return "已执行 / 已过期"; } else { cd = cd / 1000; var s = parseInt(cd%60), m = parseInt((cd/60)%60), h = parseInt((cd/(60 * 60))%24), d = parseInt(cd/(60 * 60 * 24)); return "待执行 / " + utils.format('{0}天{1}时{2}分{3}秒', utils.upzore(d, 3), utils.upzore(h, 2), utils.upzore(m, 2), utils.upzore(s, 2)); } }, wsMessage: function(pack){ if(pack){ if(pack.head.type == 'check'){ log.info(pack.head.type, pack); //$('#tr-' + pack.body.rowId).removeClass('').removeClass('danger').addClass('danger'); } else if(pack.head.type == "process"){ $('.process-' + pack.body.rowId).html(laytpl('progress.html').render({ max: pack.body.max, now: pack.body.now, width: parseInt((pack.body.now/pack.body.max) * 100) || 1 })); } } }, bindEvent: function(){ if(top['SYSTEM']){ top['SYSTEM'].regEvent('monitor.clock', 'clock', page.wsMessage); } $('.btn-save').on('click', function(){ if(page.$formValodate.validate()){ var param = $('#form').serializeJson(); if(_.isArray(param.users)){ param.users = param.users.join(','); } if(!/(,)$/.test(param.users)){ param.users = param.users + ','; } if(param.rowId){ var item = page.datas['tr-' + param.rowId]; param['execTime'] = item.execTime; param['lastTime'] = item.lastTime; param['status'] = item.status; param['userId'] = item.userId; } if(param.cycle == 'week'){ if(_.isArray(param.week)){ param.date = param.week.join(',') } else { param.date = param.week } } var zuiLoad = waiting('数据保存中...'); ajax.post({ url: 'clock/save', data: param }).done(function(res, rtn, state, msg){ if(state){ $('.panel-left').addClass('hid'); $('.panel-cover').addClass('hidden'); page.loadClockList(); } else { error("数据保存失败:" + msg); } }).fail(function(){ error("数据保存失败"); log.error('error:', arguments); }).always(function(){ zuiLoad.hide(); }); } }); $('.btn-cancel').on('click', function(){ $('.panel-left').addClass('hid'); $('.panel-cover').addClass('hidden'); }); $('.btn-add').on('click', function(){ $('#form')[0].reset(); $('#rowId').val(''); $('#typed,#cycle,#users').val('').trigger('chosen:updated'); $('.week-box').addClass('hidden'); $('#date').removeClass('hidden'); $('.btn-save').removeClass('hidden'); $('.panel-left').removeClass('hid'); $('.panel-cover').removeClass('hidden'); }); $('#cycle').on('change', function(){ var $this = $(this), type = $this.val(); var $date = $('#date'); $date.val(''); if(type == 'time'){ $date.attr('disabled', false).removeClass('hidden'); $('.week-box').addClass('hidden'); } else if(type == 'day'){ $date.val(utils.formatDate(new Date(), 'yyyy-MM-dd')).removeClass('hidden').attr('disabled', true) $('.week-box').addClass('hidden'); } else if(type == 'week'){ $date.addClass('hidden') $('.week-box').removeClass('hidden'); $('input[name="week"]').val([]); } else if(type == 'month'){ $date.attr('disabled', false).removeClass('hidden'); $('.week-box').addClass('hidden'); } else if(type == 'year'){ $date.attr('disabled', false).removeClass('hidden'); $('.week-box').addClass('hidden'); } }); $('input[name="week"]').on('click', function(e){ var v = $('input[name="week"]:checked').val(); $('#date').val(v ? v : '') }); $('#dataBody').on('click', '.btn-edit', function(){ var $this = $(this), rowId = $this.parent().data('id'); var item = page.datas['tr-' + rowId]; if(item){ $('#rowId').val(item.rowId); $('#scope').val(item.scope).trigger('chosen:updated'); $('#cycle').val(item.cycle).trigger('chosen:updated'); $('#title').val(item.title); $('#content').val(item.content); $('#date').val(item.date); $('#time').val(item.time); if(item.cycle == 'week'){ var ws = item.date.split(','); $('input[name="week"]').val(ws || []); $('.week-box').removeClass('hidden'); $('#date').addClass('hidden').val(item.date); } else { $('.week-box').addClass('hidden'); $('#date').removeClass('hidden'); } $('#email').val(item.email); $('#users').val((item.users || "").split(',')).trigger('chosen:updated'); } $('.btn-save').removeClass('hidden'); $('.panel-left').removeClass('hid'); $('.panel-cover').removeClass('hidden'); }); $('#dataBody').on('click', '.btn-detail', function(){ var $this = $(this), rowId = $this.parent().data('id'); var item = page.datas['tr-' + rowId]; if(item){ var html = laytpl('info.html').render({ cycle: (function(){ var text = page.cycleText[item.cycle]; if(item.cycle == 'day'){ text = text + " " + item.time; } else if(item.cycle == 'week'){ text = text + " " + item.date; } else if(item.cycle == 'month'){ text = text + " " + item.date; } else if(item.cycle == 'month'){ text = text + " " + item.date + " " + item.time; } return text; })(), typed: item.scope == 'private' ? '私有' : '公共', title: item.title, content: item.content, date: item.date, time: item.time, execTime: utils.formatDate(Number(item.execTime)), title: item.title, content: item.content, email: item.email, users: (function(){ var names = []; var us = item.users.split(','); for(var i = 0, k = us.length; i < k; i++){ if(us[i]){ names.push(page.users[us[i]]); } } return names.join(','); })() }); $.confirm({ title: item.title + " 明细", msg: html, showYes: false, cancelText: '关闭' }); } }); $('#dataBody').on('click', '.btn-notice', function(){ var $this = $(this), rowId = $this.parent().data('id'); var item = page.datas['tr-' + rowId]; if(item){ if(item.status == 1){ item.status = 2; } else if(item.status == 2){ item.status = 1; } var zuiLoad = waiting('数据保存中...'); ajax.post({ url: 'clock/save', data: item }).done(function(res, rtn, state, msg){ if(state){ if(item.status == 1){ $this.removeClass('icon-toggle-off').addClass('icon-toggle-on').attr('关闭闹钟'); } else if(item.status == 2){ $this.removeClass('icon-toggle-on').addClass('icon-toggle-off').attr('开启闹钟'); } } else { error("数据保存失败:" + msg); } }).fail(function(){ error("数据保存失败"); log.error('error:', arguments); }).always(function(){ zuiLoad.hide(); }); } }); $('#dataBody').on('click', '.btn-del', function(){ var $this = $(this), rowId = $this.parent().data('id'); var item = page.datas['tr-' + rowId] if(item){ $.confirm({ msg: '确定要删除此监控项【' + item.title + '】吗?', yesText: '确认删除', yesClick: function($modal){ $modal.modal('hide'); var zuiLoad = waiting('数据加载中...'); ajax.post({ url: 'clock/del', data: { rowId: rowId } }).done(function(res, rtn, state, msg){ if(state){ page.loadClockList(); } else { error(msg); } }).fail(function(){ error("删除失败"); log.error('error:', arguments); }).always(function(){ zuiLoad.hide(); }); } }); } else { error("数据错误,请刷新页面再试"); } }); } }; var page = new PageScript(); page.init(); });<filename>UED-DEMO/pages/word/more/more.js // pages/word/more/more.js Page({ /** * 页面的初始数据 */ data: { }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, moreToSales: function (event) { var page = event.currentTarget.dataset.page; var toPage = ""; switch (page) { case "share": toPage = "../share/share"; break; case "notice": toPage = "../notice/notice"; break; case "nickname": toPage = "../nickname/nickname"; break; case "noteview": toPage = "../../notes/noteview/noteview"; break; case "book": toPage = "../book/book"; break; case "member": toPage = "../member/member"; break; case "paymodel": toPage = "../paymodel/paymodel"; break; case "favorites": toPage = "../favorites/favorites"; break; case "message": toPage = "../message/message"; break; default: break; } wx.navigateTo({ url: toPage }); } })'use strict'; var testRequire = require('../test-require'); var suggestionService = testRequire('./services/suggestions-service'); var fixtureLoader = require('gitter-web-test-utils/lib/test-fixtures'); var assert = require('assert'); function serialize(f) { var s = JSON.stringify(f); return JSON.parse(s); } describe('suggestion-service', function() { describe('integration #slow', function() { var fixture = fixtureLoader.setup({ user1: {}, user2: {}, troupe1: { users: ['user1', 'user2'], security: 'PUBLIC' }, troupe2: { users: ['user2'], security: 'PUBLIC' } }); before(function() { suggestionService.testOnly.HIGHLIGHTED_ROOMS.push({ uri: fixture.troupe1.uri, localeLanguage: 'en' }); suggestionService.testOnly.HIGHLIGHTED_ROOMS.push({ uri: fixture.troupe2.uri, localeLanguage: 'en' }); }); describe('findSuggestionsForUserId', function() { it('should return suggestions', function() { return suggestionService .findSuggestionsForUserId(fixture.user1._id) .then(function(suggestions) { assert( suggestions.some(function(f) { return String(f._id) === fixture.troupe2.id; }) ); }); }); }); describe('findSuggestionsForRooms', function() { it('should return suggestions', function() { return suggestionService .findSuggestionsForRooms({ user: fixture.user1, rooms: [fixture.troupe1], language: 'en' }) .then(function(suggestions) { assert( suggestions.some(function(f) { return String(f._id) === fixture.troupe2.id; }) ); }); }); }); }); }); // @ts-check /** * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ var rotate = function(matrix) { const N = matrix.length; for (let y = 0; y < Math.floor(N / 2); y++) { for (let x = 0; x < Math.ceil(N / 2); x++) { const values = [ matrix[y][x], matrix[x][N - y - 1], matrix[N - y - 1][N - x - 1], matrix[N - x - 1][y], ]; matrix[x][N - y - 1] = values[0]; matrix[N - y - 1][N - x - 1] = values[1]; matrix[N - x - 1][y] = values[2]; matrix[y][x] = values[3]; } } }; export { rotate }; <reponame>ajayesivan/react-native-remix-icon import * as React from "react"; import Svg, { Path } from "react-native-svg"; function SvgMusic2Fill(props) { return ( <Svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" {...props}> <Path fill="none" d="M0 0h24v24H0z" /> <Path d="M20 3v14a4 4 0 11-2-3.465V6H9v11a4 4 0 11-2-3.465V3h13z" /> </Svg> ); } export default SvgMusic2Fill; import startJob from './start_job'; export default function () { startJob(); } const http = require('http'); const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(`Hello from inside Docker (on ${process.platform})! It's ${new Date()} here.`); }); server.listen(3000, "0.0.0.0", () => { console.log("Server is listening to requests on port 3000"); });/** * skylark-pox - A version of pox that ported to running on skylarkjs * @author Hudaokeji, Inc. * @version v0.9.0 * @link https://github.com/skylark-integration/skylark-pox/ * @license MIT */ define(["skylark-langx/skylark"],function(e){const t={};function o(e){return document.getElementById(e)}return t.$=o,t.RAD=Math.PI/180,t.msg=(e=>{let t=new Date;if("string"==typeof e){let t=location.protocol+"//"+location.host;e=e.replace(new RegExp(t,"g"),"").replace(/data:[^:]+/,"module")}if(o("msglog")&&(o("msglog").value+=t.toTimeString().substr(0,8)+"."+("000"+t.getMilliseconds()).substr(-3)+" "+e+"\n",o("msglog").scrollTop=o("msglog").scrollHeight),!o("msgc"))return void console.log(e);const l=document.createElement("div");l.innerHTML=e,o("msgc").appendChild(l),o("msg").scrollTop=o("msgc").offsetHeight}),e.attach("intg.pox",t)}); //# sourceMappingURL=sourcemaps/pox.js.map var five = require("../"); var board = new five.Board(); board.on("ready", function() { var imu = new five.IMU({ controller: "MPU6050" }); imu.on("change", function() { console.log("temperature"); console.log(" celsius : ", this.temperature.celsius); console.log(" fahrenheit : ", this.temperature.fahrenheit); console.log(" kelvin : ", this.temperature.kelvin); console.log("--------------------------------------"); console.log("accelerometer"); console.log(" x : ", this.accelerometer.x); console.log(" y : ", this.accelerometer.y); console.log(" z : ", this.accelerometer.z); console.log(" pitch : ", this.accelerometer.pitch); console.log(" roll : ", this.accelerometer.roll); console.log(" acceleration : ", this.accelerometer.acceleration); console.log(" inclination : ", this.accelerometer.inclination); console.log(" orientation : ", this.accelerometer.orientation); console.log("--------------------------------------"); console.log("gyro"); console.log(" x : ", this.gyro.x); console.log(" y : ", this.gyro.y); console.log(" z : ", this.gyro.z); console.log(" pitch : ", this.gyro.pitch); console.log(" roll : ", this.gyro.roll); console.log(" yaw : ", this.gyro.yaw); console.log(" rate : ", this.gyro.rate); console.log(" isCalibrated : ", this.gyro.isCalibrated); console.log("--------------------------------------"); }); }); import React from "react" import styled from "styled-components" import Button from "../Button" import { Link } from "react-scroll" const Hero = () => { return ( <HeroWrapper id="section-1"> <div className="inner"> <h1>Practicalweb</h1> <h3> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget tortor risus. </h3> <Button> <Link activeClass="" to="section-2" spy={true} smooth={true} offset={0} duration={500} > learn more </Link> </Button> </div> </HeroWrapper> ) } const HeroWrapper = styled.section` background: var(--blue); padding: 100px; height: 100vh; display: flex; justify-content: center; align-items: center; .inner { height: 270px; display: flex; flex-direction: column; justify-content: space-between; align-items: flex-start; } h1 { font-size: 3rem; margin: 0; } h3 { color: #ccc; line-height: 3rem; font-weight: 500; font-size: 1.4rem; max-width: 800px; } @media (max-width: 1227px) { padding: 200px 40px 40px 40px; max-width: 100vw; display: block; text-align: center; .inner { display: block; max-width: 100%; } h3 { font-size: 1.2rem; max-width: 80%; margin: 50px auto; } } @media (max-width: 600px) { padding: 0; display: flex; justify-content: center; align-items: center; } ` export default Hero #!/usr/bin/env node const program = require('commander'); const vizreg = require('./vizreg_lib.js'); const report = require('../report/report.js'); program .version('0.1.0') .option('-u, --update', 'update the expected images for the specified set of tests', false) .description('Visual regression tool for React components. Provide no arguments to run all tests. Provide a group name to run all tests in a group. Provide a group name and test name (e.g. npx hubble group1/test1) to run a single test.') .arguments('[test-spec]') .action((spec) => { testSpec = spec; }); program.parse(process.argv); if(typeof testSpec === 'undefined') { vizreg({ update: program.update}); } else if(testSpec == 'report'){ report.buildHTML(); report.openHTML(); } else { let delimited = testSpec.split("/"); let groupName = delimited[0]; let testName = delimited[1]; vizreg({groupName:groupName, testName:testName, update:program.update}); } /* * GLoader - Web resources loader * Author : <NAME> * URL : https://github.com/gabsoftware/gloader * License : MIT * */ var GLoader = function GLoader() { "use strict"; this.graph = new DepGraph(); this.validTypes = [ "js", "css" ]; }; if( typeof exports !== "undefined" ) { exports.GLoader = GLoader; } GLoader.prototype = { /** * Add a script to the dependency graph. If a dependency already exists with this id, this method will do nothing. */ "addScript": function( id, data, callback ) { "use strict"; return this.addResource( id, data, "js", callback ); }, /** * Add a stylesheet to the dependency graph. If a dependency already exists with this id, this method will do nothing. */ "addStylesheet": function( id, data, callback ) { "use strict"; return this.addResource( id, data, "css", callback ); }, /** * Add a generic resource to the dependency graph. If a dependency already exists with this id, this method will do nothing. */ "addResource": function( id, data, type, callback ) { "use strict"; if( ! id ) { throw new Error( "id was empty" ); } if( typeof id !== "string" ) { throw new Error( "id was not a string" ); } if( ! data ) { throw new Error( "data was empty for script #" + id ); } // if data is a string, consider it as an URL if( typeof data == "string" ) { data = { "url": data }; } if( typeof data !== "object" ) { throw new Error( "data was not an object or a string for #" + id ); } if( ! data.url || typeof data.url !== "string" ) { throw new Error( "data.url was not a string for #" + id ); } if( data.fallback && typeof data.fallback !== "string" ) { throw new Error( "data.fallback was not a string for #" + id ); } if( ! type ) { throw new Error( "type cannot be empty for #" + id ); } if( typeof type !== "string" ) { throw new Error( "type was not a string for #" + id ); } if( this.validTypes.indexOf( type ) == -1 ) { throw new Error( "type was not a valid value for #" + id ); } data.type = type; if( callback ) { data.callback = callback; } return this.graph.addNode( id, data ); }, /** * Remove a resource from the dependency graph. */ "removeResource": function( id ) { "use strict"; return this.graph.removeNode( id ); }, "hasResource": function( id ) { "use strict"; return this.graph.hasNode( id ); }, "addDependency": function( idfrom, idto ) { "use strict"; return this.graph.addDependency( idfrom, idto ); }, "removeDependency": function( from, to ) { "use strict"; return this.graph.removeDependency( idfrom, idto ); }, "getData": function( id ) { "use strict"; //console.log( "getData with", id ); return this.graph.getNodeData( id ); }, "loadResource": function( id ) { "use strict"; //console.log( "loadResource with", id ); var self = this; return new Promise( function( resolve, reject ) { var obj = self.getData( id ); var url = obj.url, type = obj.type, clbk = obj.callback; //console.log( "Loading of " + type + " : " + url ); var r = false, t, s; if( type == "js" ) { t = document.getElementsByTagName( "script" )[0]; s = document.createElement ( "script" ); s.type = "text/javascript"; s.src = url; s.defer = true; } else if( type == "css" ) { s = document.createElement( "link" ); s.type = "text/css"; s.rel = "stylesheet"; s.href = url; } s.onload = s.onreadystatechange = function () { //console.log( type + " s.onload " + url ); if( ! r && ( ! this.readyState || this.readyState == "complete" ) ) { r = true; resolve( this ); //console.log( "resolved : " + type + " " + url ); if( typeof clbk == "function" ) { clbk.call( this ); } else if( typeof clbk == "object" && typeof clbk.fn == "function" ) { clbk.fn.apply( ( clbk.scope ? clbk.scope : this ), ( typeof clbk.args == "object" && clbk.args.length ? clbk.args : [] ) ); } } }; // if no fallback specified, reject the promise directly if( ! obj.fallback ) { s.onerror = s.onabort = reject; } else { s.onerror = s.onabort = function( message ) { //console.log( "fallback pour " + obj.cdn ); var url2 = obj.fallback, type2 = obj.type, clbk2 = obj.callback; //console.log( "Loading2 of " + type2 + " : " + url2 ); var r2 = false, t2, s2; if( type2 == "js" ) { t2 = document.getElementsByTagName("script")[0]; s2 = document.createElement ("script"); s2.type = "text/javascript"; s2.src = url2; s2.defer = true; } else if( type2 == "css" ) { s2 = document.createElement ( "link" ); s2.type = "text/css"; s2.rel = "stylesheet"; s2.href = url2; } s2.onload = s.onreadystatechange = function () { //console.log( type2 + " s2.onload " + url2 ); if( ! r2 && ( ! this.readyState || this.readyState == "complete" ) ) { r2 = true; resolve( this ); //console.log( "resolved2 : " + type2 + " " + url2 ); if( typeof clbk2 == "function" ) { clbk2.call( this ); } else if( typeof clbk2 == "object" && typeof clbk2.fn == "function" ) { clbk2.fn.apply( ( clbk2.scope ? clbk2.scope : this ), ( typeof clbk2.args == "object" && clbk2.args.length ? clbk2.args : [] ) ); } } }; s2.onerror = s2.onabort = reject; if( type2 == "css" ) document.body.appendChild ( s2 ); else t2.parentNode.insertBefore( s2, t2 ); }; } if( type == "css" ) document.body.appendChild( s ); else t.parentNode.insertBefore( s, t ); }); }, // load an array of resources (a step) in parallel "loadResources": function( step ) { "use strict"; //console.log( "loadResources with", step ); var self = this; var proms = [], prom; for( var i = 0, n = step.length; i < n; i++ ) { prom = self.loadResource( step[ i ] ); proms.push( prom ); } return Promise.all( proms ); }, // helper function to run sequencially several async tasks "sequence": function( tasks, fn ) { "use strict"; var self = this; return tasks.reduce( function( promise, task ) { return promise.then( function( onFulfilled, onRejected ) { //console.log( "resources step loaded!" ); return fn( task ); }.bind( self ) ); }.bind( self ), Promise.resolve() ); }, // begin the loading of the resources "load": function() { "use strict"; var self = this; var steps = self.graph.steps(); if( ! steps || ! Array.isArray( steps ) || ! steps.length ) { throw new Error( "nothing to load" ); } // launch the resources loading sequence return self.sequence( steps, self.loadResources.bind( self ) ).then( function( onFulfilled, onRejected ) { // (optional) code to execute when all the resources have been loaded //console.log( "all is loaded" ); }, function( message ) { // (optionnal) code to execute if any resource can't be loaded //console.log( "Problem!", message ); }); } };$(function () { $('#login').click(function () { Bmob.User.logIn($("#username").val(), $("#password").val(), { success: function (user) { $(location).attr('href', './query.html'); }, error: function (user, error) { // The login failed. Check error to see why. // alert("Error: " + error.code + " " + error.message); alert("密码错误"); } }); }); }); // $(function () { // $('#register').click(function () { // $(location).attr('href', './register.html'); // console.log(11); // }); // }); import Phaser from 'phaser' export default { type: Phaser.AUTO, parent: 'content', width: 1920, height: 1080, localStorageName: 'phaseres6webpack' } "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var config = { url: 'mongodb://dev:<EMAIL>:11851/myappforhomedb' }; exports.default = config; //# sourceMappingURL=db.js.mapexport const Spinner = (id) =>({ id: id, el: null, renderSpinner() { const frgSpinner = document.createRange().createContextualFragment(` <div class="spinner d-flex justify-content-center align-items-center"> <div class="spinner-grow text-light" style="width: 4rem; height: 4rem;" role="status"> <span class="sr-only">Loading...</span> </div> </div> `); this.el = document.getElementById(this.id); this.el.innerHTML = ''; //replacing this.el.appendChild(frgSpinner); return this; }, async delay (delay = 2000) { await new Promise(resolve => setTimeout(resolve, delay)); } });print('Bonjour!'); <reponame>raywill/rw-credit import React, {Component} from 'react' import {Popover, Panel, Button, Form, Input, Grid, Col} from 'amazeui-react' export default class ContactForm extends Component { handleChange(e) { // mute } render() { const { handleChanges, // inputList, isInputValid } = this.props; var inputList = [ { "placeholder" : "真实姓名", "icon" : "user", "defaultValue" : "晓楚", "validation" : "success", "value" : "hello" }, { "placeholder" : "真实姓名", "icon" : "phone", "defaultValue" : "132xxxxxxxx", "validation" : "warning", "value" : "13222222222" }, { "placeholder" : "邮寄地址", "icon" : "home", "defaultValue" : "北京", "validation" : null, "value" : null }, { "placeholder" : "备注", "icon" : null, "defaultValue" : "叮嘱一句", "validation" : null, "value" : null } ]; var inputListElements = inputList.map((item,key) => ( <Input placeholder={item.placeholder} icon={item.icon} defaultValue={item.defaultValue} key={key} value={item.value} validation={item.validation} onChange={this.handleChange} /> )); return ( <div> <p style={ {fontSize: '0.8em', textAlign : 'center' , padding: '80px 0px 0px 0px', color : 'gray' } }>请认真填写收件人信息,客服人员会与你联系</p> <Form style={ {padding: '20px'} } > {inputListElements} </Form> <Button type="submit" amStyle="warning" amSize="xl" style={ {position: 'fixed', bottom: '0px' } } block disabled={!isInputValid}>兑换</Button> </div> ); } } suite('rb/views/CommentDialogView', function() { let reviewRequest; let reviewRequestEditor; beforeEach(function() { RB.DnDUploader.create(); reviewRequest = new RB.ReviewRequest(); reviewRequestEditor = new RB.ReviewRequestEditor({ reviewRequest: reviewRequest, }); }); afterEach(function() { RB.DnDUploader.instance = null; }); describe('Class methods', function() { describe('create', function() { it('Without a comment', function() { expect(() => RB.CommentDialogView.create({ animate: false, container: $testsScratch, reviewRequestEditor: reviewRequestEditor, })).toThrow(); expect(RB.CommentDialogView._instance).toBeFalsy(); expect($testsScratch.children().length).toBe(0); }); it('With a comment', function() { const dlg = RB.CommentDialogView.create({ animate: false, comment: new RB.DiffComment(), container: $testsScratch, reviewRequestEditor: reviewRequestEditor, }); expect(dlg).toBeTruthy(); expect(RB.CommentDialogView._instance).toBe(dlg); expect($testsScratch.children().length).toBe(1); }); it('Replacing an open dialog', function() { const dlg1 = RB.CommentDialogView.create({ animate: false, comment: new RB.DiffComment(), container: $testsScratch, reviewRequestEditor: reviewRequestEditor, }); expect(dlg1).toBeTruthy(); const dlg2 = RB.CommentDialogView.create({ animate: false, comment: new RB.DiffComment(), container: $testsScratch, reviewRequestEditor: reviewRequestEditor, }); expect(dlg2).toBeTruthy(); expect(dlg2).not.toBe(dlg1); expect(dlg1.$el.parents().length).toBe(0); expect(RB.CommentDialogView._instance).toBe(dlg2); expect($testsScratch.children().length).toBe(1); }); }); }); describe('Instances', function() { let editor; let dlg; beforeEach(function() { editor = new RB.CommentEditor({ comment: new RB.DiffComment(), canEdit: true, reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }); dlg = new RB.CommentDialogView({ animate: false, model: editor, commentIssueManager: new RB.CommentIssueManager(), }); dlg.on('closed', () => { dlg = null; }); dlg.render().$el.appendTo($testsScratch); }); afterEach(function() { if (dlg) { dlg.close(); } }); describe('Buttons', function() { beforeEach(function() { dlg.open(); }); describe('Cancel', function() { let $button; beforeEach(function() { $button = dlg.$el.find('.buttons .cancel'); }); it('Enabled', function() { expect($button.is(':disabled')).toBe(false); }); it('Cancels editor when clicked', function() { spyOn(editor, 'cancel'); $button.click(); expect(editor.cancel).toHaveBeenCalled(); }); it('Closes dialog when clicked', function() { spyOn(editor, 'cancel'); spyOn(dlg, 'close'); $button.click(); expect(dlg.close).toHaveBeenCalled(); }); it('Confirms before cancelling unsaved comment', function() { spyOn(editor, 'cancel'); spyOn(dlg, 'close'); spyOn(window, 'confirm').and.returnValue(true); editor.set('dirty', true); $button.click(); expect(dlg.close).toHaveBeenCalled(); }); it('Cancel close when unsaved comment', function() { spyOn(editor, 'cancel'); spyOn(dlg, 'close'); spyOn(window, 'confirm').and.returnValue(false); editor.set('dirty', true); $button.click(); expect(dlg.close).not.toHaveBeenCalled(); }); describe('Visibility', function() { it('Shown when canEdit=true', function() { editor.set('canEdit', true); expect($button.is(':visible')).toBe(true); }); it('Hidden when canEdit=false', function() { editor.set('canEdit', false); expect($button.is(':visible')).toBe(false); }); }); }); describe('Close', function() { let $button; beforeEach(function() { $button = dlg.$el.find('.buttons .close'); }); it('Cancels editor when clicked', function() { spyOn(editor, 'cancel'); $button.click(); expect(editor.cancel).toHaveBeenCalled(); }); it('Closes dialog when clicked', function() { spyOn(editor, 'cancel'); spyOn(dlg, 'close'); $button.click(); expect(dlg.close).toHaveBeenCalled(); }); describe('Visibility', function() { it('Shown when canEdit=false', function() { editor.set('canEdit', false); expect($button.is(':visible')).toBe(true); }); it('Hidden when canEdit=true', function() { editor.set('canEdit', true); expect($button.is(':visible')).toBe(false); }); }); }); describe('Delete', function() { let $button; beforeEach(function() { $button = dlg.$el.find('.buttons .delete'); }); it('Cancels editor when clicked', function() { editor.set('canDelete', true); spyOn(editor, 'deleteComment'); $button.click(); expect(editor.deleteComment).toHaveBeenCalled(); }); it('Closes dialog when clicked', function() { editor.set('canDelete', true); spyOn(editor, 'deleteComment'); spyOn(dlg, 'close'); $button.click(); expect(dlg.close).toHaveBeenCalled(); }); describe('Enabled state', function() { it('Enabled when editor.canDelete=true', function() { editor.set('canDelete', true); expect($button.is(':disabled')).toBe(false); }); it('Disabled when editor.canDelete=false', function() { editor.set('canDelete', false); expect($button.is(':disabled')).toBe(true); }); }); describe('Visibility', function() { it('Shown when canDelete=true', function() { editor.set('canDelete', true); expect($button.is(':visible')).toBe(true); }); it('Hidden when caDelete=false', function() { editor.set('canDelete', false); expect($button.is(':visible')).toBe(false); }); }); }); describe('Save', function() { let $button; beforeEach(function() { $button = dlg.$el.find('.buttons .save'); }); it('Cancels editor when clicked', function() { editor.set('canSave', true); spyOn(editor, 'save').and.resolveTo(); $button.click(); expect(editor.save).toHaveBeenCalled(); }); it('Closes dialog when clicked', function() { editor.set('canSave', true); spyOn(editor, 'save').and.resolveTo(); spyOn(dlg, 'close'); $button.click(); expect(dlg.close).toHaveBeenCalled(); }); describe('Enabled state', function() { it('Enabled when editor.canSave=true', function() { editor.set('canSave', true); expect($button.is(':disabled')).toBe(false); }); it('Disabled when editor.canSave=false', function() { editor.set('canSave', false); expect($button.is(':disabled')).toBe(true); }); }); describe('Visibility', function() { it('Shown when canEdit=true', function() { editor.set('canEdit', true); expect($button.is(':visible')).toBe(true); }); it('Hidden when canEdit=false', function() { editor.set('canEdit', false); expect($button.is(':visible')).toBe(false); }); }); }); }); describe('Fields', function() { beforeEach(function() { dlg.open(); }); describe('Open an Issue checkbox', function() { describe('Visibility', function() { it('Shown when canEdit=true', function() { editor.set('canEdit', true); expect(dlg._$issueOptions.is(':visible')).toBe(true); }); it('Hidden when canEdit=false', function() { editor.set('canEdit', false); expect(dlg._$issueOptions.is(':visible')).toBe(false); }); }); }); describe('Textbox', function() { describe('Visibility', function() { it('Shown when canEdit=true', function() { editor.set('canEdit', true); expect(dlg._textEditor.$el.is(':visible')).toBe(true); }); it('Hidden when canEdit=false', function() { editor.set('canEdit', false); expect(dlg._textEditor.$el.is(':visible')).toBe(false); }); }); }); }); describe('Height', function() { beforeEach(function() { editor = new RB.CommentEditor({ comment: new RB.DiffComment(), reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }); dlg = new RB.CommentDialogView({ animate: false, model: editor, }); }); it('When canEdit=true', function() { editor.set('canEdit', true); dlg.render(); dlg.open(); expect(dlg.$el.height()).toBe( RB.CommentDialogView.prototype.DIALOG_TOTAL_HEIGHT); }); it('When canEdit=false', function() { editor.set('canEdit', false); dlg.render(); dlg.open(); expect(dlg.$el.height()).toBe( RB.CommentDialogView.prototype.DIALOG_NON_EDITABLE_HEIGHT); }); }); describe('Other published comments list', function() { let $commentsList; let $commentsPane; beforeEach(function() { $commentsPane = dlg.$el.find('.other-comments'); $commentsList = $commentsPane.children('ul'); expect($commentsList.length).toBe(1); }); describe('Empty list', function() { it('Hidden pane', function() { expect($commentsPane.is(':visible')).toBe(false); }); }); describe('Populated list', function() { let comment; let commentReply; let parentCommentReplyLink; beforeEach(function() { comment = new RB.DiffComment(); comment.user = { 'name': 'Test User', }; comment.url = 'http://example.com/'; comment.comment_id = 1; comment.text = 'Sample comment.'; comment.issue_opened = false; parentCommentReplyLink = '/?reply_id=' + comment.comment_id; commentReply = new RB.DiffComment(); commentReply.user = { 'name': 'Test User', }; commentReply.url = 'http://example.com/'; commentReply.comment_id = 2; commentReply.text = 'Sample comment.'; commentReply.issue_opened = false; commentReply.reply_to_id = 1; }); describe('Visible pane', function() { it('Setting list before opening dialog', function() { editor.set('publishedComments', [comment]); dlg.open(); expect($commentsPane.is(':visible')).toBe(true); }); it('Setting list after opening dialog', function() { dlg.open(); editor.set('publishedComments', [comment]); expect($commentsPane.is(':visible')).toBe(true); }); }); it('List items added', function() { dlg.open(); editor.set('publishedComments', [comment]); expect($commentsList.children().length).toBe(1); }); it('Parent comment reply link links to itself', function() { editor.set('publishedComments', [comment]); dlg.open(); const $replyLink = $commentsList.find('.comment-list-reply-action'); expect($replyLink[0].href).toContain(parentCommentReplyLink); }); it('Both parent and reply comment reply links link to parent comment', function() { editor.set('publishedComments', [comment, commentReply]); dlg.open(); const $replyLinks = $commentsList.find('.comment-list-reply-action'); expect($replyLinks.length).toEqual(2); expect($replyLinks[0].href).toContain(parentCommentReplyLink); expect($replyLinks[1].href).toContain(parentCommentReplyLink); }); }); describe('Issue bar buttons', function() { let comment; beforeEach(function() { comment = new RB.DiffComment(); comment.user = { 'name': 'Test User', }; comment.url = 'http://example.com/'; comment.comment_id = 1; comment.text = 'Sample comment.'; comment.issue_opened = true; comment.issue_status = 'open'; }); it('When interactive', function() { reviewRequestEditor.set('editable', true); editor.set('publishedComments', [comment]); dlg = new RB.CommentDialogView({ animate: false, model: editor, commentIssueManager: new RB.CommentIssueManager(), }); dlg.render().$el.appendTo($testsScratch); dlg.open(); const $buttons = dlg.$el.find('.other-comments .issue-button'); expect($buttons.length).toBe(5); expect($buttons.is(':visible')).toBe(true); }); it('When not interactive', function() { reviewRequestEditor.set('editable', false); editor.set('publishedComments', [comment]); dlg = new RB.CommentDialogView({ animate: false, model: editor, commentIssueManager: new RB.CommentIssueManager(), }); dlg.render().$el.appendTo($testsScratch); dlg.open(); const $buttons = dlg.$el.find('.other-comments .issue-button'); expect($buttons.length).toBe(0); }); }); }); describe('Methods', function() { describe('close', function() { it('Editor state', function() { dlg.open(); expect(editor.get('editing')).toBe(true); dlg.close(); expect(editor.get('editing')).toBe(false); }); it('Dialog removed', function() { dlg.open(); spyOn(dlg, 'trigger'); dlg.close(); expect(dlg.trigger).toHaveBeenCalledWith('closed'); expect(dlg.$el.parents().length).toBe(0); expect($testsScratch.children().length).toBe(0); }); }); describe('open', function() { it('Editor state', function() { expect(editor.get('editing')).toBe(false); dlg.open(); expect(editor.get('editing')).toBe(true); }); it('Visibility', function() { expect(dlg.$el.is(':visible')).toBe(false); dlg.open(); expect(dlg.$el.is(':visible')).toBe(true); }); it('Default focus', function() { const $textarea = dlg.$el.find('textarea'); expect($textarea.is(':focus')).toBe(false); spyOn($textarea[0], 'focus'); dlg.open(); expect($textarea[0].focus).toHaveBeenCalled(); }); }); }); describe('Special keys', function() { let $textarea; function simulateKeyPress(c, altKey, ctrlKey, metaKey) { $textarea.focus(); ['keydown', 'keypress', 'keyup'].forEach(type => { const e = $.Event(type); e.which = c; e.altKey = altKey; e.ctrlKey = ctrlKey; e.metaKey = metaKey; $textarea.trigger(e); }); } function setupForRichText(richText, canSave) { editor.set('richText', richText); editor.set('canSave', !!canSave); $textarea = dlg.$('textarea'); } beforeEach(function() { dlg.open(); $textarea = dlg.$('textarea'); }); describe('Control-Enter to save', function() { beforeEach(function() { spyOn(editor, 'save').and.resolveTo(); spyOn(dlg, 'close'); }); describe('With editor.canSave=true', function() { describe('Keycode 10', function() { it('If Markdown', function() { setupForRichText(true, true); simulateKeyPress(10, false, true); expect(editor.save).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); it('If plain text', function() { setupForRichText(false, true); simulateKeyPress(10, false, true); expect(editor.save).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); }); describe('Keycode 13', function() { it('If Markdown', function() { setupForRichText(true, true); simulateKeyPress(13, false, true); expect(editor.save).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); it('If plain text', function() { setupForRichText(false, true); simulateKeyPress(13, false, true); expect(editor.save).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); }); }); describe('With editor.canSave=false', function() { beforeEach(function() { editor.set('canSave', false); }); describe('Keycode 10', function() { it('If Markdown', function() { setupForRichText(true); simulateKeyPress(10, false, true); expect(editor.save).not.toHaveBeenCalled(); expect(dlg.close).not.toHaveBeenCalled(); }); it('If plain text', function() { setupForRichText(false); simulateKeyPress(10, false, true); expect(editor.save).not.toHaveBeenCalled(); expect(dlg.close).not.toHaveBeenCalled(); }); }); describe('Keycode 13', function() { it('If Markdown', function() { setupForRichText(true); simulateKeyPress(13, false, true); expect(editor.save).not.toHaveBeenCalled(); expect(dlg.close).not.toHaveBeenCalled(); }); it('If plain text', function() { setupForRichText(false); simulateKeyPress(13, false, true); expect(editor.save).not.toHaveBeenCalled(); expect(dlg.close).not.toHaveBeenCalled(); }); }); }); }); describe('Command-Enter to save', function() { beforeEach(function() { spyOn(editor, 'save').and.resolveTo(); spyOn(dlg, 'close'); }); describe('With editor.canSave=true', function() { describe('Keycode 10', function() { it('If Markdown', function() { setupForRichText(true, true); simulateKeyPress(10, false, false, true); expect(editor.save).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); it('If plain text', function() { setupForRichText(false, true); simulateKeyPress(10, false, false, true); expect(editor.save).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); }); describe('Keycode 13', function() { it('If Markdown', function() { setupForRichText(true, true); simulateKeyPress(13, false, false, true); expect(editor.save).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); it('If plain text', function() { setupForRichText(false, true); simulateKeyPress(13, false, false, true); expect(editor.save).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); }); }); describe('With editor.canSave=false', function() { beforeEach(function() { editor.set('canSave', false); }); describe('Keycode 10', function() { it('If Markdown', function() { setupForRichText(true); simulateKeyPress(10, false, false, true); expect(editor.save).not.toHaveBeenCalled(); expect(dlg.close).not.toHaveBeenCalled(); }); it('If plain text', function() { setupForRichText(false); simulateKeyPress(10, false, false, true); expect(editor.save).not.toHaveBeenCalled(); expect(dlg.close).not.toHaveBeenCalled(); }); }); describe('Keycode 13', function() { it('If Markdown', function() { setupForRichText(true); simulateKeyPress(13, false, false, true); expect(editor.save).not.toHaveBeenCalled(); expect(dlg.close).not.toHaveBeenCalled(); }); it('If plain text', function() { setupForRichText(false); simulateKeyPress(13, false, false, true); expect(editor.save).not.toHaveBeenCalled(); expect(dlg.close).not.toHaveBeenCalled(); }); }); }); }); describe('Escape to cancel', function() { describe('Pressing escape in text area', function() { beforeEach(function() { spyOn(editor, 'cancel'); spyOn(dlg, 'close'); }); it('If Markdown', function() { spyOn(window, 'confirm').and.returnValue(true); setupForRichText(true); simulateKeyPress($.ui.keyCode.ESCAPE, false, false); expect(editor.cancel).toHaveBeenCalled(); expect(window.confirm).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); it('If plain text', function() { setupForRichText(false); simulateKeyPress($.ui.keyCode.ESCAPE, false, false); expect(editor.cancel).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); it('If unsaved comment', function() { spyOn(window, 'confirm').and.returnValue(true); editor.set('dirty', true); simulateKeyPress($.ui.keyCode.ESCAPE, false, false); expect(editor.cancel).toHaveBeenCalled(); expect(window.confirm).toHaveBeenCalled(); expect(dlg.close).toHaveBeenCalled(); }); it('If unsaved comment, do not close', function() { spyOn(window, 'confirm').and.returnValue(false); editor.set('dirty', true); simulateKeyPress($.ui.keyCode.ESCAPE, false, false); expect(editor.cancel).not.toHaveBeenCalled(); expect(window.confirm).toHaveBeenCalled(); expect(dlg.close).not.toHaveBeenCalled(); }); }); }); describe('Toggle open issue', function() { let $checkbox; function runToggleIssueTest(richText, startState, keyCode) { setupForRichText(richText); $checkbox.prop('checked', startState); editor.set('openIssue', startState); simulateKeyPress(keyCode.charCodeAt(0), true, false); expect($checkbox.prop('checked')).toBe(!startState); expect(editor.get('openIssue')).toBe(!startState); expect($textarea.val()).toBe(''); } beforeEach(function() { $checkbox = dlg.$el.find('input[type=checkbox]'); }); describe('Alt-I', function() { describe('Checked to unchecked', function() { it('If Markdown', function() { runToggleIssueTest(true, true, 'I'); }); it('If Markdown', function() { runToggleIssueTest(false, true, 'I'); }); }); describe('Unchecked to checked', function() { it('If Markdown', function() { runToggleIssueTest(true, false, 'I'); }); it('If plain text', function() { runToggleIssueTest(false, false, 'I'); }); }); }); describe('Alt-i', function() { describe('Checked to unchecked', function() { it('If Markdown', function() { runToggleIssueTest(true, true, 'i'); }); it('If plain text', function() { runToggleIssueTest(false, true, 'i'); }); }); describe('Unchecked to checked', function() { it('If Markdown', function() { runToggleIssueTest(true, false, 'i'); }); it('If plain text', function() { runToggleIssueTest(false, false, 'i'); }); }); }); }); }); describe('Title text', function() { let $title; beforeEach(function() { dlg.open(); $title = dlg.$el.find('form .title'); }); it('Default state', function() { expect($title.text()).toBe('Your comment'); }); it('Setting dirty=true', function() { editor.set('dirty', true); expect($title.text()).toBe('Your comment (unsaved)'); }); it('Setting dirty=false', function() { editor.set('dirty', true); editor.set('dirty', false); expect($title.text()).toBe('Your comment'); }); }); describe('State synchronization', function() { describe('Comment text', function() { let $textarea; beforeEach(function() { dlg.open(); $textarea = $(dlg._textEditor.$('textarea')); }); describe('Dialog to editor', function() { const text = 'foo'; beforeEach(function(done) { $textarea.focus(); for (let i = 0; i < text.length; i++) { const c = text.charCodeAt(i); let e = $.Event('keydown'); e.which = c; $textarea.trigger(e); e = $.Event('keypress'); e.which = c; $textarea.trigger(e); dlg._textEditor.setText(dlg._textEditor.getText() + text[i]); e = $.Event('keyup'); e.which = c; $textarea.trigger(e); } const t = setInterval(() => { if (dlg._textEditor.getText() === text) { clearInterval(t); done(); } }, 100); }); it('', function() { expect(editor.get('text')).toEqual(text); }); }); it('Editor to dialog', function() { const text = 'bar'; editor.set('text', text); expect(dlg._textEditor.getText()).toEqual(text); }); }); describe('Open Issue checkbox', function() { let $checkbox; beforeEach(function() { dlg.open(); $checkbox = dlg.$('#comment_issue'); $checkbox.prop('checked', false); editor.set('openIssue', false); }); it('Dialog to editor', function() { $checkbox.click(); expect(editor.get('openIssue')).toBe(true); }); it('Editor to dialog', function() { editor.set('openIssue', true); expect($checkbox.prop('checked')).toBe(true); }); }); describe('Enable Markdown checkbox', function() { let $checkbox; beforeEach(function() { dlg.open(); $checkbox = dlg.$('#enable_markdown'); $checkbox.prop('checked', false); editor.set('richText', false); expect(dlg._textEditor.richText).toBe(false); }); it('Dialog to editor', function() { $checkbox.click(); expect(editor.get('richText')).toBe(true); expect(dlg._textEditor.richText).toBe(true); }); it('Editor to dialog', function() { editor.set('richText', true); expect($checkbox.prop('checked')).toBe(true); expect(dlg._textEditor.richText).toBe(true); }); }); }); describe('User preference defaults', function() { describe('Open Issue checkbox', function() { it('When commentsOpenAnIssue is true', function() { RB.UserSession.instance.set('commentsOpenAnIssue', true); editor = new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }); dlg = new RB.CommentDialogView({ animate: false, model: editor, }); dlg.render(); const $checkbox = dlg.$('#comment_issue'); expect(editor.get('openIssue')).toBe(true); expect($checkbox.prop('checked')).toBe(true); }); it('When commentsOpenAnIssue is false', function() { RB.UserSession.instance.set('commentsOpenAnIssue', false); editor = new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }); dlg = new RB.CommentDialogView({ animate: false, model: editor, }); dlg.render(); const $checkbox = dlg.$('#comment_issue'); expect(editor.get('openIssue')).toBe(false); expect($checkbox.prop('checked')).toBe(false); }); }); describe('Enable Markdown checkbox', function() { describe('When defaultUseRichText is true', function() { beforeEach(function() { RB.UserSession.instance.set('defaultUseRichText', true); }); it('New comment', function() { editor = new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }); dlg = new RB.CommentDialogView({ animate: false, model: editor, }); dlg.render(); const $checkbox = dlg.$('#enable_markdown'); expect(editor.get('richText')).toBe(true); expect($checkbox.prop('checked')).toBe(true); expect(dlg._textEditor.richText).toBe(true); }); it('Existing comment with richText=true', function() { editor = new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, comment: new RB.DiffComment({ richText: true, }), }); dlg = new RB.CommentDialogView({ animate: false, model: editor, }); dlg.render(); const $checkbox = dlg.$('#enable_markdown'); expect(editor.get('richText')).toBe(true); expect($checkbox.prop('checked')).toBe(true); expect(dlg._textEditor.richText).toBe(true); }); it('Existing comment with richText=false', function() { editor = new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, comment: new RB.DiffComment({ richText: false, }), }); dlg = new RB.CommentDialogView({ animate: false, model: editor, }); dlg.render(); const $checkbox = dlg.$('#enable_markdown'); expect(editor.get('richText')).toBe(true); expect($checkbox.prop('checked')).toBe(true); expect(dlg._textEditor.richText).toBe(true); }); }); describe('When defaultUseRichText is false', function() { beforeEach(function() { RB.UserSession.instance.set('defaultUseRichText', false); }); it('New comment', function() { editor = new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }); dlg = new RB.CommentDialogView({ animate: false, model: editor, }); dlg.render(); const $checkbox = dlg.$('#enable_markdown'); expect(editor.get('richText')).toBe(false); expect($checkbox.prop('checked')).toBe(false); expect(dlg._textEditor.richText).toBe(false); }); it('Existing comment with richText=true', function() { editor = new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, comment: new RB.DiffComment({ richText: true, }), }); dlg = new RB.CommentDialogView({ animate: false, model: editor, }); dlg.render(); const $checkbox = dlg.$('#enable_markdown'); expect(editor.get('richText')).toBe(true); expect($checkbox.prop('checked')).toBe(true); expect(dlg._textEditor.richText).toBe(true); }); it('Existing comment with richText=false', function() { editor = new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, comment: new RB.DiffComment({ richText: false, }), }); dlg = new RB.CommentDialogView({ animate: false, model: editor, }); dlg.render(); const $checkbox = dlg.$('#enable_markdown'); expect(editor.get('richText')).toBe(false); expect($checkbox.prop('checked')).toBe(false); expect(dlg._textEditor.richText).toBe(false); }); }); }); }); describe('Logged Out indicator', function() { it('When logged in', function() { RB.UserSession.instance.set('authenticated', true); dlg = new RB.CommentDialogView({ animate: false, model: new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }), }); dlg.render(); expect(dlg.$el.find('p[class="login-text"]').length).toBe(0); }); it('When logged out', function() { RB.UserSession.instance.set('authenticated', false); dlg = new RB.CommentDialogView({ animate: false, model: new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }), }); dlg.render(); expect(dlg.$el.find('p[class="login-text"]').length).toBe(1); }); }); describe('In Draft indicator', function() { it('Shown when hasDraft=true', function() { reviewRequest.set('hasDraft', true); dlg = new RB.CommentDialogView({ animate: false, model: new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }), }); dlg.render(); expect(dlg.$el.find('p[class="draft-warning"]').length) .toBe(1); }); it('Hidden when hasDraft=false', function() { reviewRequest.set('hasDraft', false); dlg = new RB.CommentDialogView({ animate: false, model: new RB.CommentEditor({ reviewRequest: reviewRequest, reviewRequestEditor: reviewRequestEditor, }), }); dlg.render(); expect(dlg.$el.find('p[class="draft-warning"]').length) .toBe(0); }); }); }); }); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const webpack = require("webpack"); const fs = require("fs"); const path = require("path"); const distPath = path.resolve(__dirname, "./dist"); const package = require("./package.json"); const appPackage = require("./app.json"); if (package.version.indexOf("-") > 0) { appPackage.version = package.version.substring( 0, package.version.indexOf("-") ); } else { appPackage.version = package.version; } const tempDir = __dirname + "/tmp"; if (!fs.existsSync(tempDir)) { fs.mkdirSync(tempDir); } fs.writeFileSync(tempDir + "/app.json", JSON.stringify(appPackage, null, 4)); const appConfig = (env, argv) => { const PRODUCTION = argv.mode === "production"; const plugins = [ new webpack.DefinePlugin({ __PRODUCTION__: JSON.stringify(PRODUCTION), __VERSION: JSON.stringify(package.version), __BUILD: JSON.stringify(process.env.TRAVIS_BUILD_NUMBER) }), // // source-map is wrong for typescript code but better than nothing // PRODUCTION // ? new webpack.SourceMapDevToolPlugin({ // filename: "[file].map", // publicPath: `https://raw.githubusercontent.com/zzave/de.buschjaeger.freeathome/release/v${package.version}/` // }) // : null, new CleanWebpackPlugin(), new CopyWebpackPlugin({ patterns: [ { from: "./tmp/app.json", to: distPath }, { from: "./*.md", to: distPath }, { from: "./LICENSE", to: distPath }, { from: "./.homeyignore", to: distPath }, { from: "./.homeyplugins.json", to: distPath }, { from: "./APPSTORE.md", to: distPath }, { from: "assets/**/*", to: distPath }, // { // from: "**/assets/**/*", // context: "drivers", // to: distPath + "/drivers" // }, { from: "**/*.json", context: "drivers", to: distPath + "/drivers" }, { from: "settings/**/*", to: distPath }, { from: ".homeycompose/**/*", to: distPath }, { from: "locales/**/*", to: distPath } ] }) ].filter(Boolean); return { target: "node", entry: { app: "./app.js", api: "./api.js", "drivers/switch/driver": "./drivers/switch/driver.js", "drivers/switch/device": "./drivers/switch/device.js", "drivers/dimmer/driver": "./drivers/dimmer/driver.js", "drivers/dimmer/device": "./drivers/dimmer/device.js", "drivers/blind/driver": "./drivers/blind/driver.js", "drivers/blind/device": "./drivers/blind/device.js", "drivers/heating/driver": "./drivers/heating/driver.js", "drivers/heating/device": "./drivers/heating/device.js" }, module: { rules: [ { test: /\.tsx?$/, use: "ts-loader", exclude: /node_modules/ } ] }, resolve: { extensions: [".tsx", ".ts", ".js"] }, plugins: plugins, output: { filename: "[name].js", path: distPath, libraryTarget: "commonjs2" }, devtool: PRODUCTION ? false : "eval-source-map", // devtool: PRODUCTION ? false : "cheap-module-eval-source-map", externals: { homey: "homey", bufferutil: "bufferutil", "utf-8-validate": "utf-8-validate" } }; }; module.exports = appConfig; <gh_stars>0 (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/cropper/cropper" ], { 79: function(n, e, t) { (function(n) { t(4); e(t(2)); function e(n) { return n && n.__esModule ? n : { default: n }; } n(e(t(80)).default); }).call(this, t(1).createPage); }, 80: function(n, e, t) { t.r(e); var r = t(81), o = t(83); for (var c in o) "default" !== c && function(n) { t.d(e, n, function() { return o[n]; }); }(c); t(85), t(87); var u = t(10), i = Object(u.default)(o.default, r.render, r.staticRenderFns, !1, null, null, null, !1, r.components, void 0); i.options.__file = "pages/cropper/cropper.vue", e.default = i.exports; }, 81: function(n, e, t) { t.r(e); var r = t(82); t.d(e, "render", function() { return r.render; }), t.d(e, "staticRenderFns", function() { return r.staticRenderFns; }), t.d(e, "recyclableRender", function() { return r.recyclableRender; }), t.d(e, "components", function() { return r.components; }); }, 82: function(n, e, t) { t.r(e), t.d(e, "render", function() { return r; }), t.d(e, "staticRenderFns", function() { return c; }), t.d(e, "recyclableRender", function() { return o; }), t.d(e, "components", function() {}); var r = function() { var n = this.$createElement; this._self._c; }, o = !1, c = []; r._withStripped = !0; }, 83: function(n, e, t) { t.r(e); var r = t(84), o = t.n(r); for (var c in r) "default" !== c && function(n) { t.d(e, n, function() { return r[n]; }); }(c); e.default = o.a; }, 84: function(n, e, t) { (function(n) { Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var r = { components: { lClipper: function() { Promise.all([ t.e("common/vendor"), t.e("components/lime-clipper/index") ]).then(function() { return resolve(t(104)); }.bind(null, t)).catch(t.oe); } }, data: function() { return { show: !1, canvasZoom: 1, cutWidth: 0, cutHeight: 0 }; }, onLoad: function(n) { this.api.ad_cp_show(); var e = this; n = n.h ? n : { h: 800, w: 800, i: 0 }, e.h = parseInt(n.h), e.w = parseInt(n.w), e.i = n.i; }, mounted: function() { var e = this; n.createSelectorQuery().selectAll(".container").boundingClientRect(function(t) { var r = t[0].height - 50 - 100, o = (t[0].width - 40) / e.w; e.h * o > r && (o = r / e.h), e.cutWidth = e.w * o / (n.upx2px(100) / 100), e.cutHeight = e.h * o / (n.upx2px(100) / 100), e.canvasZoom = e.w / (n.upx2px(100) / 100) / e.cutWidth, e.show = !0, console.log(e.canvasZoom); }).exec(); }, methods: { success: function(e) { n.setStorageSync("cropper", '{"url":"' + e.url + '","i":"' + this.i + '"}'), this.cancel(); }, cancel: function(e) { n.navigateBack({ delta: 1 }); } } }; e.default = r; }).call(this, t(1).default); }, 85: function(n, e, t) { t.r(e); var r = t(86), o = t.n(r); for (var c in r) "default" !== c && function(n) { t.d(e, n, function() { return r[n]; }); }(c); e.default = o.a; }, 86: function(n, e, t) {}, 87: function(n, e, t) { t.r(e); var r = t(88), o = t.n(r); for (var c in r) "default" !== c && function(n) { t.d(e, n, function() { return r[n]; }); }(c); e.default = o.a; }, 88: function(n, e, t) {} }, [ [ 79, "common/runtime", "common/vendor" ] ] ]);var angularVelocities; angularVelocities = { 'av-rad/s': { to_anchor: 1, name: { singular: 'radian per second', plural: 'radians per second' } }, 'av-rad/m': { to_anchor: 1/60, name: { singular: 'radian per minute', plural: 'radians per minutes' } }, 'av-rad/hr': { to_anchor: 1/3600, name: { singular: 'radian per second', plural: 'radians per hour' } }, 'av-deg/s': { to_anchor: 1/57.3, name: { singular: 'degree per second', plural: 'degrees per second' } }, 'av-deg/m': { to_anchor: 1/3438, name: { singular: 'degree per minute', plural: 'degrees per minute' } }, 'av-deg/hr': { to_anchor: 1/206265, name: { singular: 'degree per hour', plural: 'degrees per hour' } }, 'av-rpm': { to_anchor: 1 / (60 * 2 * Math.PI), name: { singular: 'rotation per minute', plural: 'rotations per minute' } }, }; module.exports = { metric: angularVelocities , _anchors: { metric: { unit: 'av-rad/s' , ratio: 1 } } }; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = connectRange; var _find = require("lodash/find"); var _find2 = _interopRequireDefault(_find); var _isFinite2 = require("lodash/isFinite"); var _isFinite3 = _interopRequireDefault(_isFinite2); var _utils = require("../../lib/utils.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 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 usage = 'Usage:\nvar customRange = connectRange(function render(params, isFirstRendering) {\n // params = {\n // refine,\n // range,\n // start,\n // format,\n // instantSearchInstance,\n // widgetParams,\n // }\n});\nsearch.addWidget(\n customRange({\n attributeName,\n [ min ],\n [ max ],\n [ precision = 2 ],\n })\n);\nFull documentation available at https://community.algolia.com/instantsearch.js/v2/connectors/connectRange.html\n'; /** * @typedef {Object} CustomRangeWidgetOptions * @property {string} attributeName Name of the attribute for faceting. * @property {number} [min = undefined] Minimal range value, default to automatically computed from the result set. * @property {number} [max = undefined] Maximal range value, default to automatically computed from the result set. * @property {number} [precision = 2] Number of digits after decimal point to use. */ /** * @typedef {Object} RangeRenderingOptions * @property {function(Array<number, number>)} refine Sets a range to filter the results on. Both values * are optional, and will default to the higher and lower bounds. You can use `undefined` to remove a * previously set bound or to set an infinite bound. * @property {{min: number, max: number}} range Results bounds without the current range filter. * @property {Array<number, number>} start Current numeric bounds of the search. * @property {{from: function, to: function}} formatter Transform for the rendering `from` and/or `to` values. * Both functions take a `number` as input and should output a `string`. * @property {Object} widgetParams All original `CustomRangeWidgetOptions` forwarded to the `renderFn`. */ /** * **Range** connector provides the logic to create custom widget that will let * the user refine results using a numeric range. * * This connectors provides a `refine()` function that accepts bounds. It will also provide * information about the min and max bounds for the current result set. * @type {Connector} * @param {function(RangeRenderingOptions, boolean)} renderFn Rendering function for the custom **Range** widget. * @param {function} unmountFn Unmount function called when the widget is disposed. * @return {function(CustomRangeWidgetOptions)} Re-usable widget factory for a custom **Range** widget. */ function connectRange(renderFn, unmountFn) { (0, _utils.checkRendering)(renderFn, usage); return function () { var widgetParams = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var attributeName = widgetParams.attributeName, minBound = widgetParams.min, maxBound = widgetParams.max, _widgetParams$precisi = widgetParams.precision, precision = _widgetParams$precisi === undefined ? 2 : _widgetParams$precisi; if (!attributeName) { throw new Error(usage); } var hasMinBound = (0, _isFinite3.default)(minBound); var hasMaxBound = (0, _isFinite3.default)(maxBound); var formatToNumber = function formatToNumber(v) { return Number(Number(v).toFixed(precision)); }; var rangeFormatter = { from: function from(v) { return v; }, to: function to(v) { return formatToNumber(v).toLocaleString(); } }; return { _getCurrentRange: function _getCurrentRange(stats) { var pow = Math.pow(10, precision); var min = void 0; if (hasMinBound) { min = minBound; } else if ((0, _isFinite3.default)(stats.min)) { min = stats.min; } else { min = 0; } var max = void 0; if (hasMaxBound) { max = maxBound; } else if ((0, _isFinite3.default)(stats.max)) { max = stats.max; } else { max = 0; } return { min: Math.floor(min * pow) / pow, max: Math.ceil(max * pow) / pow }; }, _getCurrentRefinement: function _getCurrentRefinement(helper) { var _ref = helper.getNumericRefinement(attributeName, '>=') || [], _ref2 = _slicedToArray(_ref, 1), minValue = _ref2[0]; var _ref3 = helper.getNumericRefinement(attributeName, '<=') || [], _ref4 = _slicedToArray(_ref3, 1), maxValue = _ref4[0]; var min = (0, _isFinite3.default)(minValue) ? minValue : -Infinity; var max = (0, _isFinite3.default)(maxValue) ? maxValue : Infinity; return [min, max]; }, _refine: function _refine(helper, currentRange) { return function () { var _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [], _ref6 = _slicedToArray(_ref5, 2), nextMin = _ref6[0], nextMax = _ref6[1]; var currentRangeMin = currentRange.min, currentRangeMax = currentRange.max; var _ref7 = helper.getNumericRefinement(attributeName, '>=') || [], _ref8 = _slicedToArray(_ref7, 1), min = _ref8[0]; var _ref9 = helper.getNumericRefinement(attributeName, '<=') || [], _ref10 = _slicedToArray(_ref9, 1), max = _ref10[0]; var isResetMin = nextMin === undefined || nextMin === ''; var isResetMax = nextMax === undefined || nextMax === ''; var nextMinAsNumber = !isResetMin ? parseFloat(nextMin) : undefined; var nextMaxAsNumber = !isResetMax ? parseFloat(nextMax) : undefined; var newNextMin = void 0; if (!hasMinBound && currentRangeMin === nextMinAsNumber) { newNextMin = undefined; } else if (hasMinBound && isResetMin) { newNextMin = minBound; } else { newNextMin = nextMinAsNumber; } var newNextMax = void 0; if (!hasMaxBound && currentRangeMax === nextMaxAsNumber) { newNextMax = undefined; } else if (hasMaxBound && isResetMax) { newNextMax = maxBound; } else { newNextMax = nextMaxAsNumber; } var isResetNewNextMin = newNextMin === undefined; var isValidNewNextMin = (0, _isFinite3.default)(newNextMin); var isValidMinCurrentRange = (0, _isFinite3.default)(currentRangeMin); var isGreaterThanCurrentRange = isValidMinCurrentRange && currentRangeMin <= newNextMin; var isMinValid = isResetNewNextMin || isValidNewNextMin && (!isValidMinCurrentRange || isGreaterThanCurrentRange); var isResetNewNextMax = newNextMax === undefined; var isValidNewNextMax = (0, _isFinite3.default)(newNextMax); var isValidMaxCurrentRange = (0, _isFinite3.default)(currentRangeMax); var isLowerThanRange = isValidMaxCurrentRange && currentRangeMax >= newNextMax; var isMaxValid = isResetNewNextMax || isValidNewNextMax && (!isValidMaxCurrentRange || isLowerThanRange); var hasMinChange = min !== newNextMin; var hasMaxChange = max !== newNextMax; if ((hasMinChange || hasMaxChange) && isMinValid && isMaxValid) { helper.clearRefinements(attributeName); if (isValidNewNextMin) { helper.addNumericRefinement(attributeName, '>=', formatToNumber(newNextMin)); } if (isValidNewNextMax) { helper.addNumericRefinement(attributeName, '<=', formatToNumber(newNextMax)); } helper.search(); } }; }, getConfiguration: function getConfiguration(currentConfiguration) { var configuration = { disjunctiveFacets: [attributeName] }; var isBoundsDefined = hasMinBound || hasMaxBound; var boundsAlreadyDefined = currentConfiguration && currentConfiguration.numericRefinements && currentConfiguration.numericRefinements[attributeName] !== undefined; var isMinBoundValid = (0, _isFinite3.default)(minBound); var isMaxBoundValid = (0, _isFinite3.default)(maxBound); var isAbleToRefine = isMinBoundValid && isMaxBoundValid ? minBound < maxBound : isMinBoundValid || isMaxBoundValid; if (isBoundsDefined && !boundsAlreadyDefined && isAbleToRefine) { configuration.numericRefinements = _defineProperty({}, attributeName, {}); if (hasMinBound) { configuration.numericRefinements[attributeName]['>='] = [minBound]; } if (hasMaxBound) { configuration.numericRefinements[attributeName]['<='] = [maxBound]; } } return configuration; }, init: function init(_ref11) { var helper = _ref11.helper, instantSearchInstance = _ref11.instantSearchInstance; var stats = {}; var currentRange = this._getCurrentRange(stats); var start = this._getCurrentRefinement(helper); renderFn({ // On first render pass an empty range // to be able to bypass the validation // related to it refine: this._refine(helper, {}), format: rangeFormatter, range: currentRange, widgetParams: _extends({}, widgetParams, { precision: precision }), start: start, instantSearchInstance: instantSearchInstance }, true); }, render: function render(_ref12) { var results = _ref12.results, helper = _ref12.helper, instantSearchInstance = _ref12.instantSearchInstance; var facetsFromResults = results.disjunctiveFacets || []; var facet = (0, _find2.default)(facetsFromResults, { name: attributeName }); var stats = facet && facet.stats || {}; var currentRange = this._getCurrentRange(stats); var start = this._getCurrentRefinement(helper); renderFn({ refine: this._refine(helper, currentRange), format: rangeFormatter, range: currentRange, widgetParams: _extends({}, widgetParams, { precision: precision }), start: start, instantSearchInstance: instantSearchInstance }, false); }, dispose: function dispose(_ref13) { var state = _ref13.state; unmountFn(); var nextState = state.removeNumericRefinement(attributeName).removeDisjunctiveFacet(attributeName); return nextState; } }; }; }const { promisify } = require('util'); const exec = promisify(require('child_process').exec); const fs = require('fs'); const path = require('path'); const pfs = ['exists', 'mkdir', 'readdir', 'unlink', 'lstat'] .reduce((result, func) => Object.assign(result, { [func]: promisify(fs[func]) }), {}); const prepareWasmOutput = async () => { console.log('Preparing wasm output folder...\n'); const src = 'src/assets/wasm'; if (await pfs.exists(src)) { const files = await pfs.readdir(src); for (let file of files) { await pfs.unlink(path.join(src, file)); } } else { await pfs.mkdir(src); } }; const compileWasm = async () => { console.log('Compiling wasm sources...\n'); const commands = []; for (let file of await pfs.readdir('src/app/wasm')) { if ((await pfs.lstat(`src/app/wasm/${file}`)).isDirectory()) { const command = require(`./src/app/wasm/${file}/build-cmd.js`).cmd; commands.push(command); } } return Promise.all(commands.map(command => exec(command, { cwd: __dirname }))) .then(([_, ...statuses]) => { const status = statuses.map(s => s.stdour + s.stderr).filter(s => !!s && s !== 'undefined').join('\n'); console.log(status); }, err => { console.error('Error while compiling the sources.'); console.error(err); }); }; const allPromises = [ prepareWasmOutput, compileWasm ]; return (async () => { for (const promise of allPromises) { await promise(); } console.log('All sources have been successfully compiled.\n'); })();<gh_stars>0 "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; return t; }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = __importStar(require("react")); var prop_types_1 = __importDefault(require("prop-types")); var react_redux_1 = require("react-redux"); var compose_1 = __importDefault(require("recompose/compose")); var Delete_1 = __importDefault(require("@material-ui/icons/Delete")); var styles_1 = require("@material-ui/core/styles"); var colorManipulator_1 = require("@material-ui/core/styles/colorManipulator"); var ra_core_1 = require("ra-core"); var Button_1 = __importDefault(require("./Button")); var sanitizeRestProps = function (_a) { var basePath = _a.basePath, classes = _a.classes, dispatchCrudDeleteMany = _a.dispatchCrudDeleteMany, filterValues = _a.filterValues, label = _a.label, resource = _a.resource, selectedIds = _a.selectedIds, startUndoable = _a.startUndoable, undoable = _a.undoable, rest = __rest(_a, ["basePath", "classes", "dispatchCrudDeleteMany", "filterValues", "label", "resource", "selectedIds", "startUndoable", "undoable"]); return rest; }; var styles = function (theme) { return ({ deleteButton: { color: theme.palette.error.main, '&:hover': { backgroundColor: colorManipulator_1.fade(theme.palette.error.main, 0.12), // Reset on mouse devices '@media (hover: none)': { backgroundColor: 'transparent', }, }, }, }); }; var BulkDeleteButton = /** @class */ (function (_super) { __extends(BulkDeleteButton, _super); function BulkDeleteButton() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.handleClick = function () { var _a = _this.props, basePath = _a.basePath, dispatchCrudDeleteMany = _a.dispatchCrudDeleteMany, resource = _a.resource, selectedIds = _a.selectedIds, startUndoable = _a.startUndoable, undoable = _a.undoable, onClick = _a.onClick; if (undoable) { startUndoable(ra_core_1.crudDeleteMany(resource, selectedIds, basePath)); } else { dispatchCrudDeleteMany(resource, selectedIds, basePath); } if (typeof onClick === 'function') { onClick(); } }; return _this; } BulkDeleteButton.prototype.render = function () { var _a = this.props, classes = _a.classes, label = _a.label, icon = _a.icon, onClick = _a.onClick, rest = __rest(_a, ["classes", "label", "icon", "onClick"]); return (react_1.default.createElement(Button_1.default, __assign({ onClick: this.handleClick, label: label, className: classes.deleteButton }, sanitizeRestProps(rest)), icon)); }; BulkDeleteButton.propTypes = { basePath: prop_types_1.default.string, classes: prop_types_1.default.object, dispatchCrudDeleteMany: prop_types_1.default.func.isRequired, label: prop_types_1.default.string, resource: prop_types_1.default.string.isRequired, startUndoable: prop_types_1.default.func, selectedIds: prop_types_1.default.arrayOf(prop_types_1.default.any).isRequired, undoable: prop_types_1.default.bool, icon: prop_types_1.default.element, }; BulkDeleteButton.defaultProps = { label: 'ra.action.delete', undoable: true, icon: react_1.default.createElement(Delete_1.default, null), }; return BulkDeleteButton; }(react_1.Component)); var EnhancedBulkDeleteButton = compose_1.default(react_redux_1.connect(undefined, { startUndoable: ra_core_1.startUndoable, dispatchCrudDeleteMany: ra_core_1.crudDeleteMany, }), styles_1.withStyles(styles))(BulkDeleteButton); exports.default = EnhancedBulkDeleteButton; <reponame>rpsychologist/likelihood import React, { useContext, useState, useMemo } from "react"; import { makeStyles, withStyles } from "@material-ui/core/styles"; import Tabs from "@material-ui/core/Tabs"; import Tab from "@material-ui/core/Tab"; import Typography from "@material-ui/core/Typography"; import Box from "@material-ui/core/Box"; import { chisquare, normal } from "jstat"; import { format } from "d3-format"; import katex from "katex"; import { VizDispatch } from "../../App"; const f2n = format(".2n"); const f3n = format(".3n"); const WaldPanel = React.memo(({sigma, muHat, muNull, n}) => { const classes = useStyles(); const se = sigma / Math.sqrt(n); const waldZ = (muHat - muNull) / se; const pvalZ = 2 * (1 - normal.cdf(Math.abs(waldZ), 0, 1)); const eqSE = katex.renderToString( `\\text{se}(\\hat\\mu) = I(\\hat\\mu, \\hat\\sigma^2)^{-1/2}`, { displayMode: false, throwOnError: false } ) const eqWald = katex.renderToString(` \\begin{aligned} Z =& \\frac{\\hat\\mu - \\mu_0}{\\text{se}(\\hat\\mu)} \\\\ =& \\frac{${f3n(muHat)} - ${f3n(muNull)}}{${f3n(se)}} \\\\ =& ${f3n(waldZ)} \\end{aligned} `, { displayMode: true, throwOnError: false }) return ( <TabPanel className={classes.panel}> <Typography variant="body1"> The Wald test is based on the difference between the maximum likelihood estimate of the mean and μ0 divided by the standard error of the MLE, <span dangerouslySetInnerHTML={{ __html: eqSE }} /> </Typography> <Typography variant="body1" dangerouslySetInnerHTML={{ __html: eqWald }} /> <Typography variant="body1"> Asymptotically <em>Z</em> follows a standard normal distribution, giving <em>p</em> = {format(".2f")(pvalZ)}. </Typography> </TabPanel> ) }) const ScorePanel = React.memo(({derivMuNull, deriv2MuNull, eqChisq}) => { const classes = useStyles() const score = (derivMuNull * derivMuNull) / -deriv2MuNull; const eqScore = katex.renderToString( ` \\begin{aligned} S(\\mu_0, \\hat\\sigma_0^2) =& \\frac{U(\\mu_0, \\hat\\sigma_0^2)^2}{I(\\mu_0, \\hat\\sigma_0^2)} \\\\ &= \\frac{${f2n(derivMuNull)}^2}{${f2n(-deriv2MuNull)}} \\\\ &= ${f3n(score)} \\end{aligned} `, { displayMode: true, throwOnError: false } ); const pvalScore = 1 - chisquare.cdf(score, 1); return ( <TabPanel className={classes.panel}> <Typography variant="body1"> The Score test (also known as the Lagrange multiplier test) is slightly different in the sense that we only evaluate it at the null. It involves both the first and second derivative evaluated at the null. </Typography> <Typography variant="body1" dangerouslySetInnerHTML={{ __html: eqScore }} /> <Typography variant="body1"> Asymptotically <em>S</em> follows a{" "} <span dangerouslySetInnerHTML={{ __html: eqChisq }} /> distribution with 1 degrees of freedom, which gives <em>p</em> ={" "} {format(".2f")(pvalScore)}. </Typography> </TabPanel> ) }) const LrtPanel = React.memo(({sigma, sigma0, n, eqChisq}) => { const classes = useStyles() const calcLR = (sigma, sigma0, n) => { const W = Math.pow((sigma0 * sigma0) / (sigma * sigma), -n / 2); return -2 * Math.log(W); }; const LR = calcLR(sigma, sigma0, n); const LRFormat = format(".3n")(LR); const eqLogLik = katex.renderToString( `\\begin{aligned} \\text{LR} &= -2[\\ell(\\mu_{0}, \\hat\\sigma^2_{0}) - [\\ell(\\hat\\mu, \\hat\\sigma^2)]\\\\ &= ${LRFormat} \\end{aligned}`, { displayMode: true, throwOnError: false } ); const pvalLRT = format(".2f")(1 - chisquare.cdf(LR, 1)); return ( <TabPanel className={classes.panel}> <Typography variant="body1"> The likelihood ratio test compares the likelihood ratios of two models. In this example {"it's"} the likelihood evaluated at the MLE and at the null. This is illustrated in the plot by the vertical distance between the two horizontal lines. If we multiply the difference in log-likelihood by -2 we get the statistic, </Typography> <Typography variant="body1" dangerouslySetInnerHTML={{ __html: eqLogLik }} /> <Typography variant="body1"> Asymptotically LR follows a{" "} <span dangerouslySetInnerHTML={{ __html: eqChisq }} /> distribution with 1 degrees of freedom, which gives <em>p</em> = {pvalLRT}. </Typography> <Typography variant="body1"> Note: The figure is simplified and does not account for the fact that each likelihood is based on different variance estimates. </Typography> </TabPanel> ) }) function TabPanel(props) { const { children, value, index, ...other } = props; return ( <Typography component="div" role="tabpanel" hidden={value !== index} id={`wrapped-tabpanel-${index}`} aria-labelledby={`wrapped-tab-${index}`} {...other} > {value === index && <Box p={3}>{children}</Box>} </Typography> ); } const TestTabs = withStyles({ root: { borderBottom: "1px solid #e8e8e8", backgroundColor: "#ccdae3" }, indicator: { backgroundColor: "#0984e3" } })(Tabs); const useStyles = makeStyles(() => ({ root: { flexGrow: 1 }, panel: { backgroundColor: "#f1f7f9", color: "#425358" } })); const TestTab = withStyles(theme => ({ root: { textTransform: "none", minWidth: 72, fontWeight: theme.typography.fontWeightRegular, fontSize: theme.typography.pxToRem(15), marginRight: theme.spacing(4), "&:hover": { color: "#40a9ff", opacity: 1 }, "&$selected": { color: "#0984e3", fontWeight: "700" }, "&:focus": { color: "#0984e3" } }, selected: {} }))(props => <Tab {...props} />); function a11yProps(index) { return { id: `wrapped-tab-${index}`, "aria-controls": `wrapped-tabpanel-${index}` }; } export default function TabsWrappedLabel({ muNull, muHat, sigma2, sigma2Null, n, derivMuNull, deriv2MuNull }) { const classes = useStyles(); const [value, setValue] = useState("LRT"); const dispatch = useContext(VizDispatch); const sigma = Math.sqrt(sigma2); const sigma0 = Math.sqrt(sigma2Null); const handleChange = (event, newVal) => { setValue(newVal); dispatch({ name: "test", value: newVal }); }; const eqHypo = katex.renderToString( `H_0: \\mu = ${muNull} \\quad \\text{versus} \\quad H_1: \\mu \\ne ${muNull}`, { displayMode: true, throwOnError: false } ); const eqChisq = useMemo(() => katex.renderToString("\\chi^2", { displayMode: false, throwOnError: false }), []) return ( <div className={classes.root}> <p>We have the following null and alternative hypothesis,</p> <p dangerouslySetInnerHTML={{ __html: eqHypo }}></p> <TestTabs value={value} onChange={handleChange} aria-label="test type"> <TestTab value="LRT" label="LRT" wrapped {...a11yProps("LRT")} /> <TestTab value="wald" label="Wald" {...a11yProps("wald")} /> <TestTab value="score" label="Score Test" {...a11yProps("score")} /> </TestTabs> {value === 'LRT' && ( <LrtPanel sigma={sigma} sigma0={sigma0} n={n} eqChisq={eqChisq} /> )} {value === 'wald' && ( <WaldPanel n={n} sigma={sigma} muNull={muNull} muHat={muHat} /> )} {value === 'score' && ( <ScorePanel derivMuNull={derivMuNull} deriv2MuNull={deriv2MuNull} eqChisq={eqChisq} /> )} </div> ); } import commentsApi from '../api/commentsApi' export function commentsFetchData(url) { return (dispatch) => { dispatch(commentsIsLoading(true)); fetch(url) .then((response) => { dispatch(commentsIsLoading(false)); return response }) .then(response => response.json()) .then(comments => dispatch(commentsFetchDataSuccess(comments))) // .catch(() => dispatch(commentsHasErrored(true))) } } export function commentsHasErrored(bool) { return { type: 'COMMENTS_HAS_ERRORED', hasErrored: bool } } export function commentsIsLoading(bool) { return { type: 'COMMENTS_IS_LOADING', isLoading: bool } } export function commentsFetchDataSuccess(comments) { return { type: 'COMMENTS_FETCH_DATA_SUCCESS', comments } } export function postCommentData(comment) { return (dispatch) => { return commentsApi.postComment(comment).then(response => { if (response.id) { dispatch(postCommentSuccess(response)); } else { dispatch(postCommentHasErrored(true)) } }) } } export function postCommentSuccess(comment) { return { type: 'POST_COMMENT_SUCCESS', comment } } export function postCommentHasErrored(bool) { return { type: 'POST_COMMENT_HAS_ERRORED', hasErrored: bool } } import { toContainExactPath } from './exact-path'; import using from 'jasmine-data-provider'; describe('toMatchExactPath', () => { describe('should return true', () => { using(pathProvider, (expected, actual) => { it('if the path is contained in the url', () => { expect(toContainExactPath(expected, actual)).toBeTruthy(); }); }); function pathProvider() { return [ [ 'http://foo.bar/', '/' ], [ 'http://foo.bar/simple', '/simple' ], [ 'http://foo.bar/simple-dash', '/simple-dash' ], [ 'http://foo.bar/simple/nested', '/simple/nested' ], [ 'http://foo.bar/simple/double/nested', '/simple/double/nested' ], [ 'http://foo.bar:80/with-port-number', '/with-port-number' ] ] } }); describe('should return false', () => { it('if the expected url is undefined', () => { expect(toContainExactPath(void 0, '')).toBeFalsy(); }); it('if the actual path is undefined', () => { expect(toContainExactPath('http://foo.bar/', void 0)).toBeFalsy(); }); it('if the url is invalid', () => { expect(toContainExactPath('foobar', '')).toBeFalsy(); }); }); }); $(document).ready(function() { getLocation(); function getLocation() { if (navigator && navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { $("#error").text("Geolocation is not supported by this browser>"); } } function showPosition(position) { getData(position.coords.latitude, position.coords.longitude); } function getData(latitude, longitude) { $.ajax({ dataType: "jsonp", url: "https://api.darksky.net/forecast/" + config.apiKey + "/" + latitude + "," + longitude, }).done(function(data) { console.log(data); var temperature = data.currently.temperature; var windSpeed = (data.currently.windSpeed * 1.6).toFixed(2); var where = data.timezone; var summary = data.currently.summary; var icon = data.currently.icon; setData(temperature, windSpeed, where, summary, icon); }) } function setData(temp, wind, where, summary, icon) { $("#temperature").text("Temperature: " + getDegreesFromFarenheit(Math.round(temp)).toString() + " C"); $("#wind").text("Windspeed: " + wind.toString() + " kmph"); $("#location").text("Location: " + where); $("#summary").text("General Weather: " + summary); setBackground(icon); } function getFarenheitFromDegrees(degrees) { return Math.round((parseInt(degrees) * 1.8)) + 32; } function getDegreesFromFarenheit(farenheit) { return Math.round(((parseInt(farenheit) - 32) / 1.8)).toString(); } function strip(str) { return str .replace(" F", "") .replace(" C", "") .replace("Windspeed: ", "") .replace("Location: ", "") .replace("General Weather: ", "") .replace("Temperature: ", ""); } function setBackground(icon) { var url; switch(icon) { case "clear-night": case "clear-day": url = 'url("media/sunny.jpg")'; break; case "rain": url = 'url("media/rainy.jpg")'; break; case "snow": url = 'url("media/snowy.jpg")'; break; case "sleet": url = 'url("media/sleety.jpg")'; break; case "wind": url = 'url("media/windy.jpg")'; break; case "partly-cloudy-day": case "partly-cloudy-night": case "cloudy": url = 'url("media/cloudy.jpg")'; break; case "fog": url = 'url("media/foggy.jpg")'; break; default: url = 'url("media/generally.jpg")'; break; } $("html").css("background-image", url); } $("#convert").on("click", function() { var currentTemperature = $("#temperature").text(); if (currentTemperature.indexOf("F") > -1) { $("#temperature").text("Temperature: " + getDegreesFromFarenheit(strip(currentTemperature)) + " C"); $("#convert").text("Convert to Farenheit"); } else { $("#temperature").text("Temperature: " + getFarenheitFromDegrees(strip(currentTemperature)) + " F"); $("#convert").text("Convert to Celcius"); } }); }); <gh_stars>0 import {HttpClient} from 'aurelia-http-client'; import {GameStyles} from './gameStyles'; import {GameThemes} from './gameThemes'; /* created to : store game state singleton scoped to a story playthough using update pattern to preserve references to objects */ export class GameState{ static inject = [HttpClient, GameThemes]; constructor(http, themeAdapter){ this.pages = []; this.story = {}; this.selectedPage = {}; this.themeAdapter = themeAdapter; http.get("/json/pages.json").then( response =>{ this.addRange(this.pages, response.content) }); http.get("/json/story.json").then( response =>{ this.updateValues( this.story, response.content); }); } updateValues(obj, values){ //Object.assign(obj, values); for( var key in values){ obj[key] = values[key]; } } addRange( sourceArr, values){ var len = values.length; for (var i = 0; i < len; i++){ sourceArr.push(values[i]); }; } }const Token = require('markdown-it/lib/token'); const MarkdownIt = require('markdown-it'); const md = new MarkdownIt(); function callPlugin(plugin, tokens, opts) { md.disable = () => {}; md.enable = () => {}; const state = { tokens, env: {}, Token, md, }; const fakeMd = { core: { ruler: { push: (name, cb) => cb(state), before: (anotherPlugin, name, cb) => cb(state), }, }, }; plugin(fakeMd, opts); return state.tokens; } const paragraph = (content) => [ { 'type': 'paragraph_open', 'content': '', }, { 'type': 'inline', 'children': [{ 'type': 'text', 'tag': '', 'children': null, content, }], content, }, { 'type': 'paragraph_close', 'content': '', }, ]; const tokenize = (lines = []) => md.parse(lines.join('\n'), {}); const log = require('../lib/log'); module.exports = {callPlugin, paragraph, tokenize, log}; <gh_stars>0 import React from 'react'; import {mount} from 'enzyme'; import Tags from '../components/Tags'; const event = { preventDefault: jest.fn() }; const addTag = jest.fn(); const deleteTag = jest.fn(); test('display existing tags', () => { const tags = mount( <Tags tags={['one fish','two fish','red fish']} addTag={addTag} deleteTag={deleteTag} /> ); expect(tags.find('.tag').length).toBe(3); }); test('add tag on form submit', () => { const tags = mount( <Tags tags={['one fish','two fish','red fish']} addTag={addTag} deleteTag={deleteTag} /> ); const inputField = tags.find('input'); inputField.node.value = 'blue fish'; tags.instance().submitForm(event); expect(event.preventDefault).toBeCalled(); expect(addTag).toBeCalled(); expect(addTag.mock.calls[0][0]).toEqual(['one fish', 'two fish', 'red fish', 'blue fish']); }); test('add tag on comma separator', () => { const tags = mount( <Tags tags={['one fish','two fish','red fish']} addTag={addTag} deleteTag={deleteTag} /> ); tags.instance().handleKeyUp({target: {value: 'blue fish, '}}); expect(addTag).toBeCalled(); expect(addTag.mock.calls[0][0]).toEqual(['one fish', 'two fish', 'red fish', 'blue fish']); }); import React from 'react'; import { Link } from 'react-router-dom'; import Typography from 'material-ui/Typography'; import Grid from 'material-ui/Grid'; import { withStyles } from 'material-ui/styles'; import Paper from 'material-ui/Paper'; const urlPicture = 'https://avatars1.githubusercontent.com/u/21246251?s=400&u=70a8b7debc32833028f4ea8e9330c59a25d15deb&v=4'; const Epitech = 'http://www.epitech.eu/strasbourg/ecole-informatique-strasbourg.aspx'; const RUC = 'https://ruc.dk/en'; const Technologies = [[ 'React', 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/1000px-React-icon.svg.png', 'https://reactjs.org/', ], [ 'Redux', 'https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/spaces%2F-L5K1I1WsuQMZ8ecEuWg%2Favatar.png?generation=1518623866348435&alt=media', 'https://redux.js.org/', ], [ 'Webpack', 'https://webpack.js.org/assets/icon-square-small-slack.png', 'https://webpack.js.org/', ], [ 'Express', 'http://www.rosselli.com.br/img/posts/credentials-expressjs.jpg', 'https://expressjs.com/', ], [ 'Flow', 'http://mherman.org/assets/img/blog/flow-logo.jpeg', 'https://flow.org/', ], [ 'Jest', 'https://facebook.github.io/jest/img/opengraph.png', 'https://facebook.github.io/jest/', ], ]; export const About = ({ classes }) => ( <div className={classes.root}> <Paper className={classes.paper}> <Typography noWrap paragraph variant="display1">Me</Typography> <Typography variant="body1"> Hey ! <br /> My name is <NAME>, I'm an <a href={Epitech}>Epitech Strasbourg </a> student and I'm currently attending my 4<sup>th</sup> year of study at <a href={RUC}>Roskilde University</a> in Denmark thanks to the Erasmus program. <br /> I'm { new Date().getFullYear() - new Date(1995, 5, 1).getFullYear() } years old, and I will graduate in August 2019. </Typography> </Paper> <Paper className={classes.paper}> <Typography paragraph noWrap variant="display1">Technologies</Typography> <Typography variant="body1"> This application has been built using lots of great framework : </Typography> <div className={classes.iconsBox}> { Technologies.map(e => ( <a href={e[2]}> <div className={classes.icons} style={{ backgroundImage: `url(${e[1]})` }} /> </a> )) } </div> </Paper> <Paper className={classes.paper}> <Typography noWrap paragraph variant="display1">Context</Typography> <Typography variant="body1"> This application is part of a 1 week technical challenge for an internship interview. <br /> This repository is a as of today representation of my web development knowledge. (May 2018) </Typography> </Paper> </div> ); const style = theme => ({ iconsBox: { display: 'flex', justifyContent: 'space-evenly', alignItems: 'center', }, icons: { height: 100, width: 100, backgroundSize: 'contain', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', }, paper: { margin: 'auto', marginTop: theme.spacing.unit * 2, padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit}px`, maxWidth: 800, [theme.breakpoints.down('xs')]: { margin: theme.spacing.unit, }, }, }); export default withStyles(style)(About); 'use strict'; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; 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 _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 BaseLog = (function () { function BaseLog() { _classCallCheck(this, BaseLog); this.logName = 'Hey\n \n something\n \n special'; } _createClass(BaseLog, [{ key: 'log', value: function log(msg) { console.log(this.logName + ': ' + msg); } }]); return BaseLog; })(); var Logger = (function (_BaseLog) { _inherits(Logger, _BaseLog); function Logger(logName) { _classCallCheck(this, Logger); _get(Object.getPrototypeOf(Logger.prototype), 'constructor', this).call(this, logName); } _createClass(Logger, [{ key: 'writeLine', value: function writeLine(msg) { _get(Object.getPrototypeOf(Logger.prototype), 'log', this).call(this, msg + '\r\n'); } }]); return Logger; })(BaseLog); var NewLogger = (function (_BaseLog2) { _inherits(NewLogger, _BaseLog2); function NewLogger(logName) { _classCallCheck(this, NewLogger); _get(Object.getPrototypeOf(NewLogger.prototype), 'constructor', this).call(this, logName); } _createClass(NewLogger, [{ key: 'writeLine', value: function writeLine(msg) { _get(Object.getPrototypeOf(NewLogger.prototype), 'log', this).call(this, msg + '\r\n' + " some"); } }]); return NewLogger; })(BaseLog);const bcrypt = require("bcrypt"); const saltRounds = 10; const generateHash = (plainTextPassword) => { return new Promise((resolve, reject) => { bcrypt.hash(plainTextPassword, saltRounds, (err, hash) => { if (err) { reject(err); } else { resolve(hash); } }); }); }; const compareHash = (plainTextPassword, passwordHash) => { return new Promise((resolve, reject) => { bcrypt.compare(plainTextPassword, passwordHash, (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }; exports.generateHash = generateHash; exports.compareHash = compareHash; var _max = 128; var _escape = 4; addEventListener("message", onMessage, false); function onMessage (e) { // Extract input values from e.data var id = e.data.id; var bitmap = e.data.bitmap; var rmin = e.data.rmin; var rmax = e.data.rmax; var imin = e.data.imin; var imax = e.data.imax; var h = _max >> 1; // Divide max by 2 var q = _max >> 2; // Divide max by 4 // Compute increments for real and imaginary components var dr = (rmax - rmin) / (bitmap.width - 1); var di = (imax - imin) / (bitmap.height - 1); // Check each pixel for inclusion in the Mandelbrot set for (x = 0; x < bitmap.width; x++) { var cr = rmin + (x * dr); for (y = 0; y < bitmap.height; y++) { var ci = imin + (y * di); var zr = cr; var zi = ci; var count = 0; while (count < _max) { var zr2 = zr * zr; var zi2 = zi * zi; if (zr2 + zi2 > _escape) { setPixel(bitmap, x, y, 0xff, (count * 255) / _max, ((count % h) * 255) / h, ((count % q) * 255) / q); break; } zi = ci + (2 * zr * zi); zr = cr + zr2 - zi2; count++; } if (count == _max) setPixel(bitmap, x, y, 0xff, 0, 0, 0); } } // Post the populated imageData object along with the // quadrant ID back to the UI thread postMessage({ "id": id, "bitmap": bitmap }); } function setPixel(bitmap, x, y, a, r, g, b) { var index = (x + y * bitmap.width) << 2; bitmap.data[index + 0] = r; bitmap.data[index + 1] = g; bitmap.data[index + 2] = b; bitmap.data[index + 3] = a; }<reponame>lizamedina/lizamedina /** * * * @author carpincho/Victoria/Liza * @since 16/04/19. * @version 1.0 */ (() => { 'use strict'; const API_URL = 'https://task-backend-fpuna.herokuapp.com/tasks'; const TASK_STATUS = { PENDING: 'PENDIENTE', DONE: 'TERMINADO' }; class Task { constructor(description) { this.id = null; this.description = description; this.status = TASK_STATUS.PENDING; this.date = new Date().toUTCString(); } } /** * This method is executed once the page have just been loaded and call the service to retrieve the * list of tasks */ document.onreadystatechange = () => { // TODO ITEM 0: Llamar al API con el método GET para recuperar la lista de tareas existentes. // - Como parámetro `callbackSuccess` envía la función `loadTasks`. // - Como parámetro `callbackError` envía una función que llame al método `showError` enviando un mensaje de // error // - La llamada debe ser asíncrona. //Ajax.sendGetRequest(API_URL, {}, MediaFormat.JSON, loadTasks, (text) => showError(1, text), true); //$.get(API_URL, loadTasks); cargaLista() //setInterval(function(){ alert("Hello"); }, 3000); }; const cargaLista = () => { let lListas = document.getElementsByClassName('listView'); if (lListas) { for (var i = 0; i < lListas.lenght; i++) { const element = lListas[i]; element.innerHTML = ""; } } var param = {} $.get(API_URL, function (valor) { loadTasks(valor); }) }; const procesar = () => { let limpiarnewTaskInput = document.getElementById("new-task"); limpiarnewTaskInput.value = ""; cargaLista(); }; /** * This method displays an error on the page. * @param code the status code of the HTTP response. * @param text error message */ const showError = (code, text) => { // TODO ITEM 6 recuperar el elemento HTML con la clase `error-bar` y modificar el HTML interno de // manera a mostrar el mensaje de error. // El mensaje de error debe desaparacer luego de 3 segundos. // El error debe mostrarse solo por 5 segundos, luego de ésto, debe desaparecer. Agregado para esta tarea //Se recupera el elemento HTML //var contentError = document.getElementsByClassName('error-bar'); //var modal = document.getElementById('myModal'); //modal.style.display = "block"; //contentError[0].innerText = text //El mensaje de error debe desaparacer luego de 3 segundos //setTimeout(function() { //borra el mensaje //contentError[0].innerText = ""; //oculta el modal //modal.style.display = "none"; //}, 3000); //3000 milisegundos console.log("showError"); let errorBar = document.getElementsByClassName('error-bar')[0]; errorBar.innerHTML = `${text}. Codigo error: ${code}`; errorBar.classList.remove('hide-bar'); errorBar.classList.add('show-bar'); setTimeout(() => { errorBar.classList.remove('show-bar'); errorBar.classList.add('hide-bar'); },5000); }; /** * This method receives the list of tasks and calls the method to add each of them to the page * * @param array the string coming on the body of the API response */ const loadTasks = (tasks) => { //console.log(tasks); //let tasks = JSON.parse(array); for (let i in tasks) { if (tasks.hasOwnProperty(i)) { addTaskToList(tasks[i]); } } }; /** * Send the request to the API to create a new task * * @param e the event from the click on the new item button * @return {boolean} */ const addTask = (e) => { let newTaskInput = document.getElementById("new-task"); let content = newTaskInput.value; if (content.length === 0) return false;//si la longitud es 0 devuelve false y no hace nada e.preventDefault(); let task = new Task(content); //let taskjson = JSON.stringify(task); //let task = JSON.parse(content); // TODO ITEM 1: Llamar al API con el método POST para crear una nueva tarea. // - Como parámetro `callbackSuccess` envía una función que llame al método `addTaskToList` enviando la // variable `task` y limpia el valor del input#new-task. // - Como parámetro `callbackError` envía una función que llame al método `showError` enviando un mensaje de // error // - La llamada debe ser asíncrona. // - No te olvides de envíar el parámetro `task` para que se cree la tarea. //Ajax.sendPostRequest(API_URL, task, MediaFormat.JSON, (Task) => addTaskToList(task), (code) => showError(code, 'La tarea no ha podido ser añadida.'), true, MediaFormat.JSON); //console.log(task); //$.post(`${API_URL}`, (Task) => addTaskToList(task),taskjson,); $.ajax({ url: API_URL, type: 'POST', data: JSON.stringify(task), contentType:"application/json", success: (Task) => addTaskToList(task) }); //$('#add').on('click', () => {$.post(API_URL, {"description":"wgom"}, 'application/json');}); //$.post(API_URL, JSON.stringify(task), (Task) => addTaskToList(task), "application/json"); //document.getElementById('new-task').value = ''; return false; }; /** * This procedure links the new task button the addTask method on the click event. */ let addButtons = document.getElementsByClassName('add'); for (let i in addButtons) addButtons.item(Number(i)).onclick = (e) => addTask(e); /** * We associate a function to manipulate the DOM once the checkbox value is changed. * Change the task to the completed or incomplete list (according to the status) */ const addOnChangeEvent = (task) => { //Obtiene el elemento del checkBox const checkBox = document.getElementById(`task-${task.id}`).querySelector('label > input'); checkBox.onchange = (e) => { // TODO ITEM 3: leer el nuevo estado de la tarea (que solo puede ser TERMINADO(true) or PENDIENTE(false)) accediendo a la // propiedad `e.target.checked`. Con éste nuevo dato, debes mostrar la tarea junto con las tareas de su // mismo estado (e.g. si la tarea estaba pendiente pero el usuario hace click en el checkbox, el estado de // la tarea debe cambiar a terminada y debe ahora mostrarse con las otras tareas terminadas). // - Una forma de hacerlo es remover directamente el archivo con el id `task-${task.id}` del DOM HTML // y luego llamar a la función `addTaskToList` que re-creara la tarea con el nuevo estado en el lugar correcto. // - No te olvides de llamar al API (método PUT) para modificar el estado de la tarea en el servidor. //*const id = e.target.dataset.id; // if (e.target.checked) { // Ajax.sendPutRequest(`${API_URL}/${task.id}` , {status: TASK_STATUS.DONE}, MediaFormat.JSON, // (CurrentTask) => addTaskToList(JSON.parse(CurrentTask)), // (code) => showError(code, 'La tarea no ha podido ser modificada.'), true, MediaFormat.JSON); // document.getElementById(`task-${task.id}`).remove(); // } // else { // Ajax.sendPutRequest(`${API_URL}/${task.id}` , {status: TASK_STATUS.PENDING}, MediaFormat.JSON, // (CurrentTask) => addTaskToList(JSON.parse(CurrentTask)), // (code) => showError(code, 'La tarea no ha podido ser modificada.'), true, MediaFormat.JSON); // document.getElementById(`task-${task.id}`).remove(); // } const newState = e.target.checked; $.ajax({ url: `${API_URL}/${task.id}`, type: 'PUT', data: JSON.stringify({status: newState ? 'TERMINADO' : 'PENDIENTE'}), contentType: "application/json", success: function(task){ $(`#task-${task.id}`).remove(); addTaskToList(task); } }); }; }; /** * This method modifies the DOM HTML to add new items to the task list. * @param task the new task. */ const addTaskToList = (task) => { let newItem = document.createElement('li'); newItem.setAttribute('id', `task-${task.id}`); let label = document.createElement('label'); label.innerHTML = `<input type="checkbox" ${task.status === TASK_STATUS.DONE ? "checked" : ""}/> ${task.description}`; let editButton = document.createElement('button'); editButton.innerText = 'Editar'; editButton.classList.add('edit'); editButton.setAttribute('data-id', task.id); editButton.onclick = (e) => editTask(e); let deleteButton = document.createElement('button'); deleteButton.innerText = 'Borrar'; deleteButton.classList.add('delete'); deleteButton.setAttribute('data-id', task.id); deleteButton.onclick = (e) => removeTask(e); newItem.appendChild(label); newItem.appendChild(editButton); newItem.appendChild(deleteButton); if (task.status === TASK_STATUS.PENDING) document.getElementById('incomplete-tasks').appendChild(newItem); else document.getElementById('completed-tasks').appendChild(newItem); addOnChangeEvent(task); }; /** * This method modifies the DOM HTML to display a form that allow the user to change the * task description and send a PUT request to modify it on the server side * * @param e */ const editTask = (e) => { // We retrieve the value of the attribute data-id; const id = e.target.dataset.id; let currentDOMTask = document.getElementById(`task-${id}`); currentDOMTask.querySelector("label > input[type=checkbox]").remove(); let currentTask = new Task(currentDOMTask.querySelector("label").innerHTML.trim()); currentTask.id = id; currentDOMTask.querySelector('label').remove(); let inputText = document.createElement('input'); inputText.setAttribute('id', `task-edit-${currentTask.id}`); inputText.setAttribute('type', 'text'); inputText.setAttribute('value', currentTask.description); /** * We associate the event click on the button ok, to send a PUT request to the server. */ let buttonOK = document.createElement('button'); buttonOK.innerText = 'OK'; buttonOK.setAttribute('id', `ok-button-${currentTask.id}`); buttonOK.onclick = () => { currentTask.description = document.getElementById(`task-edit-${currentTask.id}`).value; // TODO ITEM 2: llamar a la API con el método PUT cuando la descripción de la tarea es // modificada (`currentTask`). // - Como parámetro `callbackSuccess` envía una función que llame al método `revertHTMLChangeOnEdit` // enviando la variable `currentTask`. // - Como parámetro `callbackError` envía una función que llame al método `showError` enviando un mensaje de // error // - La llamada debe ser asíncrona. // - No te olvides de envíar el parámetro para que se cree la tarea. //Ajax.sendPutRequest(`${API_URL}/${currentTask.id}` , currentTask, MediaFormat.JSON, (currentTask) => revertHTMLChangeOnEdit(currentTask), (code) => showError(1, 'La tarea no ha podido ser modificada.'), true, MediaFormat.JSON); $.ajax({ url: `${API_URL}/${currentTask.id}`, type: 'PUT', data: JSON.stringify({description: currentTask.description}), contentType: "application/json", success: (Task) => revertHTMLChangeOnEdit(currentTask) }); }; let buttonCancel = document.createElement('button'); buttonCancel.innerText = 'Cancel'; buttonCancel.setAttribute('id', `cancel-button-${currentTask.id}`); buttonCancel.onclick = () => revertHTMLChangeOnEdit(currentTask); currentDOMTask.insertBefore(buttonCancel, currentDOMTask.children[0]); currentDOMTask.insertBefore(buttonOK, currentDOMTask.children[0]); currentDOMTask.insertBefore(inputText, currentDOMTask.children[0]); currentDOMTask.querySelector('.edit').style.visibility = 'hidden'; currentDOMTask.querySelector('.delete').style.visibility = 'hidden'; inputText.focus(); }; /** * This method removes the form displayed to edit the task and show it as a task item. * @param currentTask the string coming from the API */ const revertHTMLChangeOnEdit = (currentTask) => { //console.log(currentTask instanceof Task); let task = currentTask instanceof Task ? currentTask : JSON.parse(currentTask); //let task = JSON.parse(currentTask); //let task = currentTask; let currentDOMTask = document.getElementById(`task-${task.id}`); currentDOMTask.querySelector('input[type=text]').remove(); let label = document.createElement('label'); currentDOMTask.insertBefore(label, currentDOMTask.children[0]); label.innerHTML = `<input type="checkbox"/> ${task.description}`; addOnChangeEvent(task); currentDOMTask.insertBefore(label, currentDOMTask.children[0]); currentDOMTask.querySelector(`button#ok-button-${task.id}`).remove(); currentDOMTask.querySelector(`button#cancel-button-${task.id}`).remove(); currentDOMTask.querySelector('.edit').style.visibility = 'visible'; currentDOMTask.querySelector('.delete').style.visibility = 'visible'; }; /** * This methods removes the task item associated to the DOM of the page * @param id the identifier from the task */ const removeTaskFromList = (id) => { // TODO ITEM 4: remover del DOM HTML el elemento con id `task-${id}` $(`#task-${id}`).remove(); }; /** * This method sends a DELETE request to remove the task from the server. * @param e */ const removeTask = (e) => { const id = e.target.dataset.id; //let param = {} // Ajax.sendDeleteRequest(API_URL+'/'+id, param, MediaFormat.JSON, (valor) => loadLst(), // (error) => showError(error, 'No fue posible eliminar la tarea.'), true); // TODO ITEM 5: enviar una petición DELETE al API con el {id} de la tarea. // - Como parámetro `callbackSuccess` enviar una función que llamé al método `removeTaskFromList` // enviando el id de la tarea. // - Como parámetro `callbackError` enviar una función que llame al método `showError` enviando // un mensaje de error // - La llamada debe ser asíncrona. $.ajax({ url: `${API_URL}/${id}`, type: 'DELETE', datatype: 'json'; contentType: 'application/json', success: removeTaskFromList(id) }); }; })(jQuery); <filename>src/templates/tags.js import React from 'react'; import PropTypes from 'prop-types'; import { Link, graphql } from 'gatsby'; export const tags = () => { return <div>Hi</div> }<reponame>vegai/react-pdf const Yoga = require('../src/dist/entry-browser'); describe('Borders', () => { let yogaNode; let flexboxNode; beforeEach(() => { yogaNode = Yoga.Node.createDefault(); flexboxNode = Yoga.Node.createDefault(); }); test('should have same top border by default', () => { expect(yogaNode.getBorder(Yoga.EDGE_TOP)).toEqual( flexboxNode.getBorder(Yoga.EDGE_TOP), ); }); test('should have same left border by default', () => { expect(yogaNode.getBorder(Yoga.EDGE_LEFT)).toEqual( flexboxNode.getBorder(Yoga.EDGE_LEFT), ); }); test('should have same bottom border by default', () => { expect(yogaNode.getBorder(Yoga.EDGE_BOTTOM)).toEqual( flexboxNode.getBorder(Yoga.EDGE_BOTTOM), ); }); test('should have same right border by default', () => { expect(yogaNode.getBorder(Yoga.EDGE_RIGHT)).toEqual( flexboxNode.getBorder(Yoga.EDGE_RIGHT), ); }); test('should have same vertical border by default', () => { expect(yogaNode.getBorder(Yoga.EDGE_VERTICAL)).toEqual( flexboxNode.getBorder(Yoga.EDGE_VERTICAL), ); }); test('should have same horizontal border by default', () => { expect(yogaNode.getBorder(Yoga.EDGE_HORIZONTAL)).toEqual( flexboxNode.getBorder(Yoga.EDGE_HORIZONTAL), ); }); test('should have same start border by default', () => { expect(yogaNode.getBorder(Yoga.EDGE_START)).toEqual( flexboxNode.getBorder(Yoga.EDGE_START), ); }); test('should have same end border by default', () => { expect(yogaNode.getBorder(Yoga.EDGE_END)).toEqual( flexboxNode.getBorder(Yoga.EDGE_END), ); }); test('should have same all border by default', () => { expect(yogaNode.getBorder(Yoga.EDGE_ALL)).toEqual( flexboxNode.getBorder(Yoga.EDGE_ALL), ); }); test('should set top border', () => { yogaNode.setBorder(Yoga.EDGE_TOP, 5); flexboxNode.setBorder(Yoga.EDGE_TOP, 5); expect(yogaNode.getBorder(Yoga.EDGE_TOP)).toEqual( flexboxNode.getBorder(Yoga.EDGE_TOP), ); }); test('should set left border', () => { yogaNode.setBorder(Yoga.EDGE_LEFT, 5); flexboxNode.setBorder(Yoga.EDGE_LEFT, 5); expect(yogaNode.getBorder(Yoga.EDGE_LEFT)).toEqual( flexboxNode.getBorder(Yoga.EDGE_LEFT), ); }); test('should set bottom border', () => { yogaNode.setBorder(Yoga.EDGE_BOTTOM, 5); flexboxNode.setBorder(Yoga.EDGE_BOTTOM, 5); expect(yogaNode.getBorder(Yoga.EDGE_BOTTOM)).toEqual( flexboxNode.getBorder(Yoga.EDGE_BOTTOM), ); }); test('should set right border', () => { yogaNode.setBorder(Yoga.EDGE_RIGHT, 5); flexboxNode.setBorder(Yoga.EDGE_RIGHT, 5); expect(yogaNode.getBorder(Yoga.EDGE_RIGHT)).toEqual( flexboxNode.getBorder(Yoga.EDGE_RIGHT), ); }); test('should set vertical border', () => { yogaNode.setBorder(Yoga.EDGE_VERTICAL, 5); flexboxNode.setBorder(Yoga.EDGE_VERTICAL, 5); expect(yogaNode.getBorder(Yoga.EDGE_VERTICAL)).toEqual( flexboxNode.getBorder(Yoga.EDGE_VERTICAL), ); }); test('should set horizontal border', () => { yogaNode.setBorder(Yoga.EDGE_HORIZONTAL, 5); flexboxNode.setBorder(Yoga.EDGE_HORIZONTAL, 5); expect(yogaNode.getBorder(Yoga.EDGE_HORIZONTAL)).toEqual( flexboxNode.getBorder(Yoga.EDGE_HORIZONTAL), ); }); test('should set start border', () => { yogaNode.setBorder(Yoga.EDGE_START, 5); flexboxNode.setBorder(Yoga.EDGE_START, 5); expect(yogaNode.getBorder(Yoga.EDGE_START)).toEqual( flexboxNode.getBorder(Yoga.EDGE_START), ); }); test('should set end border', () => { yogaNode.setBorder(Yoga.EDGE_END, 5); flexboxNode.setBorder(Yoga.EDGE_END, 5); expect(yogaNode.getBorder(Yoga.EDGE_END)).toEqual( flexboxNode.getBorder(Yoga.EDGE_END), ); }); test('should set all border', () => { yogaNode.setBorder(Yoga.EDGE_ALL, 5); flexboxNode.setBorder(Yoga.EDGE_ALL, 5); expect(yogaNode.getBorder(Yoga.EDGE_ALL)).toEqual( flexboxNode.getBorder(Yoga.EDGE_ALL), ); }); test('border_no_size', () => { const root = Yoga.Node.create(); root.setBorder(Yoga.EDGE_LEFT, 10); root.setBorder(Yoga.EDGE_TOP, 10); root.setBorder(Yoga.EDGE_RIGHT, 10); root.setBorder(Yoga.EDGE_BOTTOM, 10); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(20); expect(root.getComputedLayout().height).toBe(20); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(20); expect(root.getComputedLayout().height).toBe(20); }); test('border_container_match_child', () => { const root = Yoga.Node.create(); root.setBorder(Yoga.EDGE_LEFT, 10); root.setBorder(Yoga.EDGE_TOP, 10); root.setBorder(Yoga.EDGE_RIGHT, 10); root.setBorder(Yoga.EDGE_BOTTOM, 10); const child = Yoga.Node.create(); child.setWidth(10); child.setHeight(10); root.insertChild(child, 0); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(30); expect(root.getComputedLayout().height).toBe(30); expect(child.getComputedLayout().left).toBe(10); expect(child.getComputedLayout().top).toBe(10); expect(child.getComputedLayout().width).toBe(10); expect(child.getComputedLayout().height).toBe(10); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(30); expect(root.getComputedLayout().height).toBe(30); expect(child.getComputedLayout().left).toBe(10); expect(child.getComputedLayout().top).toBe(10); expect(child.getComputedLayout().width).toBe(10); expect(child.getComputedLayout().height).toBe(10); }); test('border_flex_child', () => { const root = Yoga.Node.create(); root.setBorder(Yoga.EDGE_LEFT, 10); root.setBorder(Yoga.EDGE_TOP, 10); root.setBorder(Yoga.EDGE_RIGHT, 10); root.setBorder(Yoga.EDGE_BOTTOM, 10); root.setWidth(100); root.setHeight(100); const child = Yoga.Node.create(); child.setFlexGrow(1); child.setWidth(10); root.insertChild(child, 0); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(100); expect(root.getComputedLayout().height).toBe(100); expect(child.getComputedLayout().left).toBe(10); expect(child.getComputedLayout().top).toBe(10); expect(child.getComputedLayout().width).toBe(10); expect(child.getComputedLayout().height).toBe(80); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(100); expect(root.getComputedLayout().height).toBe(100); expect(child.getComputedLayout().left).toBe(80); expect(child.getComputedLayout().top).toBe(10); expect(child.getComputedLayout().width).toBe(10); expect(child.getComputedLayout().height).toBe(80); }); test('border_stretch_child', () => { const root = Yoga.Node.create(); root.setBorder(Yoga.EDGE_LEFT, 10); root.setBorder(Yoga.EDGE_TOP, 10); root.setBorder(Yoga.EDGE_RIGHT, 10); root.setBorder(Yoga.EDGE_BOTTOM, 10); root.setWidth(100); root.setHeight(100); const child = Yoga.Node.create(); child.setHeight(10); root.insertChild(child, 0); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(100); expect(root.getComputedLayout().height).toBe(100); expect(child.getComputedLayout().left).toBe(10); expect(child.getComputedLayout().top).toBe(10); expect(child.getComputedLayout().width).toBe(80); expect(child.getComputedLayout().height).toBe(10); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(100); expect(root.getComputedLayout().height).toBe(100); expect(child.getComputedLayout().left).toBe(10); expect(child.getComputedLayout().top).toBe(10); expect(child.getComputedLayout().width).toBe(80); expect(child.getComputedLayout().height).toBe(10); }); test('border_center_child', () => { const root = Yoga.Node.create(); root.setJustifyContent(Yoga.JUSTIFY_CENTER); root.setAlignItems(Yoga.ALIGN_CENTER); root.setBorder(Yoga.EDGE_START, 10); root.setBorder(Yoga.EDGE_END, 20); root.setBorder(Yoga.EDGE_BOTTOM, 20); root.setWidth(100); root.setHeight(100); const child = Yoga.Node.create(); child.setWidth(10); child.setHeight(10); root.insertChild(child, 0); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(100); expect(root.getComputedLayout().height).toBe(100); expect(child.getComputedLayout().left).toBe(40); expect(child.getComputedLayout().top).toBe(35); expect(child.getComputedLayout().width).toBe(10); expect(child.getComputedLayout().height).toBe(10); root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL); expect(root.getComputedLayout().left).toBe(0); expect(root.getComputedLayout().top).toBe(0); expect(root.getComputedLayout().width).toBe(100); expect(root.getComputedLayout().height).toBe(100); expect(child.getComputedLayout().left).toBe(50); expect(child.getComputedLayout().top).toBe(35); expect(child.getComputedLayout().width).toBe(10); expect(child.getComputedLayout().height).toBe(10); }); }); const DEFAULT = ()=>{} export default function (fn, ...defArgs) { return function (...args) { return new Promise((resolve, reject) => { fn.call(this, ...defArgs, ...args, function (err, val) { return err ? reject(err) : resolve(val) }) }) } }<reponame>daleyjem/ics export default function setOrganizer({ name, email, dir }) { let formattedOrganizer = '' formattedOrganizer += dir ? `DIR=${dir};` : '' formattedOrganizer += 'CN=' formattedOrganizer += name || 'Organizer' formattedOrganizer += email ? `:mailto:${email}` : '' return formattedOrganizer } <filename>src/containers/cardMake/musicChooseCompoent.js<gh_stars>1-10 import React from "react"; import { bindActionCreators } from "redux"; import { withRouter } from "react-router-dom"; import { connect } from "react-redux"; import BaseComponent from "../../utils/BaseComponent"; import * as editAction from "../../actions/edit"; import cs from "classnames"; import "./assets/card.css"; import Modal from "../tip/modalComponent"; class MusicChooseComponent extends BaseComponent { state = { value: "选择背景音乐", currennt: 0 }; handleChange = event => { this.setState({ value: event.target.value }); }; doChange = (id,k) => { console.log(JSON.stringify(id)) this.props.actions.fetchCurrentMusic(id) this.setState({ currennt:k }) // let audio = new Audio() // audio.src = id // audio.play() // console.log(audio) }; // 组件会更新 componentWillUpdate() {} componentWillMount(){ } componentDidMount() { // let a = editAction. } saveMusic = ()=>{ let currentMusic = this.props.audiolist.get(this.state.currennt).get('audioUrl') console.log(currentMusic) this.props.actions.fetchCurrentMusic(currentMusic) this.props.actions.hideMusic() } doReport = e => { this.props.doReport(this.state.list[this.state.currennt]); }; render() { console.log(this.props.audiolist.toJS()) console.log(this.props.currentMusic) return ( <Modal> <div className="music_eidt_root fadeIn"> <div className="modal animated fadeIn" style={{ height: "6rem", }} > <h3>选择h5的背景音乐</h3> {this.props.audiolist.isEmpty()&&'loading...'} <div className='content'> {!this.props.audiolist.isEmpty()&&this.props.audiolist.map((v, k) => { return ( <div key={k} className={cs("pointlist", { active: this.props.currentMusic == v.get('audioUrl') })} onClick={this.doChange.bind(this, v.get('audioUrl'),k)} > <span className="point" /> <span className='rank'>{k+1}</span> <img src={require('./assets/music.png')} alt='as'/> <p>{v.get('audioName')}</p> </div> ); })} </div> <div className="b_btn_group"> <div className="btn" onTouchEnd={e => { this.props.actions.hideMusic() }} > 取消 </div> <div className="btn" onTouchEnd={this.saveMusic}> 确定 </div> </div> </div> </div> </Modal> ); } } const mapStateToProps = state => { return { audiolist: state.getIn(["edit","musicList"]), currentMusic: state.getIn(["edit","currentMusic"]), }; }; //将action的所有方法绑定到props上 const mapDispatchToProps = (dispatch, ownProps) => { return { actions: bindActionCreators({ ...editAction }, dispatch) }; }; export default withRouter( connect(mapStateToProps, mapDispatchToProps)(MusicChooseComponent) ); class myJSON { constructor() { } fn_serialize(obj_myObject){ let fn_serializeReplacer; this.fn_serializeReplacer=this.fn_serializeReplacerDefault; if(obj_myObject.fn_serializeReplacer!==undefined){ this.fn_serializeReplacer=obj_myObject.fn_serializeReplacer; } this.obj_myObject=obj_myObject; let str_json=JSON.stringify(obj_myObject, this.fn_serializeReplacer()) str_json=str_json.replace("xcludex", ); return str_json; } fn_deserialize(str_json){ let obj_json={}; try { obj_json=JSON.parse(str_json); } catch (error) { console.error("*****START ERROR myJSON DeSerialize*****"); console.error("Error: " + error); console.error("str_json: " + str_json); console.error("*****END ERROR myJSON DeSerialize*****\n\n"); } return obj_json; } fn_serializeReplacerDefault = () => { //myJSON default serialize object const seen = new WeakSet(); return (key, value) => { switch(key){ case "obj_ini": return undefined; break; } //console.log(key + ": " + value); if (typeof value === "object" && value !== null) { //fn_enumerateObject(value, "myJSON fn_serializeReplacerDefault"); //const found = this.arr_exclude.find(element => element === value); //if (found) {return "";} if (seen.has(value)) { return "circular"; //return; } seen.add(value); } return value; }; }; } //END OF CLS myJSON <filename>plugins/cordova-plugin-insomnia/src/browser/Insomnia.js function notSupported() { console.log('Insomnia is not supported on the browser'); } module.exports = { keepAwake: notSupported, allowSleepAgain: notSupported }; require('cordova/exec/proxy').add('Insomnia', module.exports); import chalk from 'chalk'; export const error = { text(msg) { return `${chalk.red('error:')} ${msg}`; }, log(msg) { console.error(this.text(msg)); }, }; export const info = { text(msg) { return `${chalk.blue('info:')} ${msg}`; }, log(msg) { console.log(this.text(msg)); }, }; export const success = { text(msg) { return `${chalk.green('success:')} ${msg}`; }, log(msg) { console.log(this.text(msg)); }, }; export const dir = { text(msg) { return `${chalk.italic.yellow(msg)}`; }, log(msg) { console.log(this.text(msg)); }, }; export default { error, info, success, dir, }; // Arguments // let x = 1; // x = 'a'; function sum() { // console.log(arguments); // [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 } and 3 let total = 0; for (let value of arguments) { total += value; } return total; } const vysledok = sum(1, 2, 3, 4, 5, 10); console.log(vysledok); // 25 <filename>src/template/v1/js/pe/center.index.js var PE = { init: function () { CMPE.ch(2); } } $(document).ready(function() { PE.init(); });/** * Copyright Zendesk, Inc. * * Use of this source code is governed under the Apache License, Version 2.0 * found at http://www.apache.org/licenses/LICENSE-2.0. */ import React from 'react'; import { render, fireEvent } from 'garden-test-utils'; import SelectContainer from './SelectContainer'; describe('SelectContainer', () => { let onChangeSpy; const items = ['item-1', 'item-2', 'item-3']; const BasicExample = props => ( <SelectContainer selectedKey={undefined} {...props} trigger={({ getTriggerProps, triggerRef }) => ( <div {...getTriggerProps({ ref: triggerRef, 'data-test-id': 'trigger' })} > nothing chosen </div> )} > {({ getSelectProps, getItemProps, dropdownRef }) => ( <div {...getSelectProps({ ref: dropdownRef, 'data-test-id': 'dropdown' })} > {items.map(key => ( <div {...getItemProps({ key, textValue: key, 'data-test-id': 'item' })} > {key} </div> ))} </div> )} </SelectContainer> ); beforeEach(() => { onChangeSpy = jest.fn(); }); describe('getTriggerProps()', () => { it('applies correct accessibility attributes', () => { const { getByTestId } = render(<BasicExample onChange={onChangeSpy} />); expect(getByTestId('trigger')).toHaveAttribute('role', 'combobox'); }); }); describe('getSelectProps()', () => { it('applies correct accessibility attributes', () => { const { getByTestId } = render(<BasicExample onChange={onChangeSpy} />); fireEvent.click(getByTestId('trigger')); expect(getByTestId('dropdown')).toHaveAttribute('role', 'listbox'); }); }); describe('onChange', () => { it('receives selected item key on select', () => { const { getByTestId, getAllByTestId } = render(<BasicExample onChange={onChangeSpy} />); fireEvent.click(getByTestId('trigger')); fireEvent.click(getAllByTestId('item')[0]); expect(onChangeSpy).toHaveBeenCalledWith('item-1'); }); }); }); <filename>src/App.js import { useState, useEffect } from 'react' import './App.css' import Ticketmaster from './components/Ticketmaster' import Weather from './components/Weather' function App() { const [location, setLocation] = useState({ latitude: 0, longitude: 0 }) useEffect(() => { navigator.geolocation.getCurrentPosition(position => { console.log(position) setLocation({ latitude: position.coords.latitude, longitude: position.coords.longitude, }) }) }, []) return ( <div className='App'> <Weather /> <Ticketmaster long={location.longitude} lat={location.latitude} /> </div> ) } export default App <filename>src/components/layout.js import React from 'react'; import PropTypes from 'prop-types'; import { StaticQuery, graphql } from 'gatsby'; import '../scss/global.scss'; import s from '../scss/modules/base.module.scss'; import Header from './header'; import Helmet from './Helmet'; import Footer from './footer'; import Wrap from './common/Wrap'; const Layout = ({ children, data, subpage }) => ( <StaticQuery query={graphql` query SiteTitleQuery { site { siteMetadata { title } } } `} render={data => ( <> {!subpage && ( <Helmet meta={[ { name: 'description', content: 'Dynamic, Next Generation Legal Agreements', }, ]} path="" title={data.site.siteMetadata.title} /> )} <Header subpage={subpage} /> <Wrap> <div className={s.wrapper}> <div className={`${s.bodyWrapper}`}>{children}</div> <Footer /> </div> </Wrap> </> )} /> ); Layout.propTypes = { children: PropTypes.node.isRequired, }; export default Layout; module.exports = function(grunt) { grunt.initConfig({ less: { development: { options: { paths: ["./www/less"], yuicompress: true }, files: { "./www/css/application.css": "./www/less/application.less" } } // development }, // less watch: { scripts: { files: ['./www/js/**/*.js'], tasks: ['clean:js','copy:js'] }, //scripts less: { files: ['./www/less/*'], tasks: ['less','copy:css'] }, //less html: { files: ['./www/index.html'], tasks: ['copy:html'] } //html }, // watch clean: { js: './platforms/ios/www/js/' }, copy: { css: { src: './www/css/application.css', dest: './platforms/ios/www/css/application.css', filter: 'isFile' }, //css js: { expand: true, cwd: './www/js/', src: '**/*', dest: './platforms/ios/www/js/' }, //js html: { src: './www/index.html', dest: './platforms/ios/www/index.html', filter: 'isFile' } //html }, //copy jshint: { options: { bitwise: false, curly: false, eqeqeq: true, forin: true, immed: true, indent: 2, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, plusplus: false, regexp: true, undef: true, strict: true, trailing: true, sub: true, browser: true, devel: true, expr: true, eqnull: true, predef: ['angular','utils','FastClick','L'], ignores: ['www/js/lib/**/*.js'] }, files: ['www/js/**/*.js'] } // jshint }); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-jshint'); };#!/usr/bin/env node 'use strict'; const program = require('commander'); const cheerio = require('cheerio'); const prettyjson = require('prettyjson'); const rp = require('request-promise'); const humanize = require('humanize-number'); const printToCo = obj => { console.log(prettyjson.render(obj, { keysColor: 'blue', dashColor: 'magenta', stringColor: 'white' })) } const turnResponseIntoCheerioObj = (pack, res) => { const $ = cheerio.load(res); let obj = {}; const timeFrames = ['daily', 'weekly', 'monthly']; timeFrames.forEach((timeFrame) => { obj = Object.assign(obj, {[timeFrame]: humanize($(`.${timeFrame}-downloads`).text())}) }) obj = Object.assign({}, {[pack]: obj}); printToCo(obj); } program .version('0.0.1') .arguments('<pack>') .action( function(pack) { getNpmPage(pack).then((res) => { if(res.hasOwnProperty('statusCode')) { if(res.statusCode == 404) { throw new Error(`Did not find a packaged name ${pack}. Try searching for another one.`) } else { throw new Error(res.statusCode) } } else { turnResponseIntoCheerioObj(pack, res); } }).catch((err) => { console.error(err) process.exit() }) }); program.parse(process.argv); async function getNpmPage(pack) { try { let res = await rp(`https://www.npmjs.com/package/${pack}`); return res } catch(err) { return err } } <gh_stars>10-100 var searchData= [ ['map_0',['Map',['../namespace_aws_1_1_crt.html#a1cf42e328e4553fa884d30468915df73',1,'Aws::Crt']]], ['messagetype_1',['MessageType',['../namespace_aws_1_1_eventstreamrpc.html#a17196886a4195a25c1e092353b6dd591',1,'Aws::Eventstreamrpc']]], ['multimap_2',['MultiMap',['../namespace_aws_1_1_crt.html#afa7b355655153ab380ab8e7a11e039aa',1,'Aws::Crt']]] ]; import { useEffect } from 'react'; import 'styles/globals.scss'; import { AnimatePresence } from 'framer-motion'; import { store } from 'store'; import { Provider } from 'react-redux'; import Layout from 'components/Layout'; import { tools } from 'utils/tools' function MyApp({ Component, pageProps, router }) { useEffect(() => { localStorage.setItem('tools',JSON.stringify(tools)); }, []); return ( <Provider store={store}> <Layout> <AnimatePresence exitBeforeEnter> <Component key={router.route} {...pageProps} /> </AnimatePresence> </Layout> </Provider> ); } export default MyApp; <reponame>ihorskyi/compromise /* compromise-keypress 0.0.2 MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.compromiseKeypress = factory()); }(this, (function () { 'use strict'; var addMethods = function addMethods(Doc, world, nlp) { var sentenceCache = {}; /** memoize tagger per-sentence */ nlp.keypress = function (str, options) { //do a quick-parse on the text var doc = nlp.tokenize(str, options); var arr = doc.json({ terms: false }); var list = []; arr.forEach(function (o) { //do we already have it parsed? if (sentenceCache.hasOwnProperty(o.text) === true) { //use the cache list.push(sentenceCache[o.text].data); sentenceCache[o.text].used = true; // console.log('used cache: ', o.text, '\n') } else { //otherwise, parse it! var json = nlp(o.text, options).json(0); //cache it sentenceCache[o.text] = { data: json, used: true }; // used[o.text] = true list.push(json); } }); // delete any unused cache Object.keys(sentenceCache).forEach(function (k) { if (sentenceCache[k].used !== true) { delete sentenceCache[k]; } else { sentenceCache[k].used = null; } }); return nlp.fromJSON(list); }; /** clear the sentence cache */ nlp.clear = function () { sentenceCache = {}; }; /** undocumented function for debugging the plugin **/ nlp._sentenceCache = function () { return sentenceCache; }; }; var src = addMethods; return src; }))); //# sourceMappingURL=compromise-keypress.js.map import highland from "highland"; import sumByDate from "../../../../source/iml/charting/sum-by-date.js"; import jobStatsFixture from "../../../data-fixtures/job-stats-fixture.json"; import { values } from "@iml/obj"; import { streamToPromise } from "../../../../source/iml/promise-transforms.js"; describe("sum by date", () => { it("should sum points as expected", async () => { const out = await streamToPromise( highland([jobStatsFixture]) .map(values) .flatten() .through(sumByDate) .collect() ); expect(out).toEqual([ { data: { "dd.0": 0 }, ts: "2016-09-30T13:18:30+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:18:40+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:18:50+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:19:00+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:19:10+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:19:20+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:19:30+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:19:40+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:19:50+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:20:00+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:20:10+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:20:20+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:20:30+00:00" }, { data: { "dd.0": 314572.8 }, ts: "2016-09-30T13:20:40+00:00" }, { data: { "dd.0": 4404019.2, "cp.0": 20761804.8 }, ts: "2016-09-30T13:20:50+00:00" }, { data: { "cp.0": 39321600, "dd.0": 5242880 }, ts: "2016-09-30T13:21:00+00:00" }, { data: { "cp.0": 84410368, "dd.0": 1468006.4 }, ts: "2016-09-30T13:21:10+00:00" }, { data: { "cp.0": 74344038.4, "dd.0": 0 }, ts: "2016-09-30T13:21:20+00:00" }, { data: { "cp.0": 0, "dd.0": 0 }, ts: "2016-09-30T13:21:30+00:00" }, { data: { "dd.0": 0 }, ts: "2016-09-30T13:18:20+00:00" } ]); }); it("should sum empty points correctly", async () => { const out = await streamToPromise( highland([ { 1: [], 2: [], 3: [] } ]) .map(values) .flatten() .through(sumByDate) .collect() ); expect(out).toEqual([]); }); }); <reponame>nergantre/DescentGame import React from 'react'; /** * description component. * * This later will contain code to generate a description of the shop from current conditions. */ export default ({personnel}) => ( <div className="col-md-12"> <h4>Currently you have {personnel.size} subordinates.</h4> </div> )var test = require('../util/test')(__filename); var pluck = require('../../packages/collection-pluck'); var compare = require('../../packages/collection-compare'); test('arrays return array of values at propertyName', function(t) { t.plan(2); var arr = [{a: 1, b: 2}, {a: 4, b: 3}, {a: 2, b: 5}]; t.ok(compare(pluck(arr, 'a'), [1, 4, 2])); var arr2 = [{a: 1, b: [3, 4, 5]}, {a: 4, b: /23/}, {a: 2, b: {r: 4}}]; t.ok(compare(pluck(arr2, 'b'), [[3, 4, 5], /23/, {r: 4}])); t.end(); }); test('objects return object with original keys and values at propertyName', function( t ) { t.plan(2); var obj = {x: {a: 1, b: 2}, y: {a: 4, b: 3}, z: {a: 2, b: 5}}; t.ok(compare(pluck(obj, 'a'), {x: 1, y: 4, z: 2})); var obj2 = {x: {a: 1, b: [22]}, y: {a: 4}, z: {a: 2, b: '14'}}; t.ok(compare(pluck(obj2, 'b'), {x: [22], y: undefined, z: '14'})); t.end(); }); test('empty object returns empty object', function(t) { t.plan(1); t.ok(compare(pluck({}, 'a'), {})); t.end(); }); test('empty array returns empty array', function(t) { t.plan(1); t.ok(compare(pluck([], 'a'), [])); t.end(); }); test('arrays of arrays work fine with numeric propertyName', function(t) { t.plan(2); var arr = [['a', 0], [100, 1, 'xyz'], [{}, 4]]; t.ok(compare(pluck(arr, 1), [0, 1, 4])); var arr2 = [['a', [5, 6, 7], {}], [/45/, {}], [[], {a: 100}]]; t.ok(compare(pluck(arr2, 0), ['a', /45/, []])); t.end(); }); test('objects of arrays work fine with numeric propertyName', function(t) { t.plan(2); var obj = {x: [0, 1, 2], y: [null, -1]}; t.ok(compare(pluck(obj, 1), {x: 1, y: -1})); var obj2 = {a: [{}, null], b: [null], c: [10]}; t.ok(compare(pluck(obj2, 0), {a: {}, b: null, c: 10})); t.end(); }); var { readJSON } = require('./config'); describe('Read from file', () => { it('Testing actually works', () => { expect(readJSON()).toBe(true) }); });import React from 'react' import Navigation from '@Components/Navigation' export default function Default({ children }) { return ( <> <Navigation /> {children} </> ) } import { createMovieQuery, createMovieQueryInterface } from "../util/createMovieQuery"; import each from "jest-each"; function randomInt(n) { return Math.floor(n * Math.random()); } //const alphaNum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // Generate random UTF-16 character function randomChar() { String.fromCharCode(randomInt(65535)); } function randomString(n) { let _throwaway = Array(randomInt(n)).fill(undefined); return _throwaway.reduce((a,b) => a + randomChar(), ""); } function genTestCase(f, v) { return [v,f(v)]; } function genTestCases(n, f, inputGen) { let results = [] for(let i = 0; i < n; i++) { let input = inputGen(); results.push([input, f(input), i]); } return results; } function getTitleQuery(input){ return input ? {title: {$regex: input, $options: "i"}} : {}; } function getGenreQuery(input) { return input ? {genres: input} : {}; } function getYearQuery([from, to]) { return from > to ? {} : {year: {$lte: to.toString(), $gte: from.toString()}}; } function genRandomInput() { let inputs = [randomString(25), randomString(25), randomInt(10000), randomInt(10000)] inputs.map((f) => randomInt(1) ? f : null); return inputs; } function getCompleteQuery(input) { let query = {}; const fields = ["title", "genres", "year"] const queries = [getTitleQuery, getGenreQuery, getYearQuery]; input.forEach((e,i) => {if(e) query[fields[i]] = queries[i](e)[fields[i]];}); return query; } describe("Correctly creates title query", () => { each(genTestCases(150, getTitleQuery, () => randomString(25))).test("", (input, expected, i) => { let created = createMovieQuery({title:input, genre:null, fromYear:null, toYear:null}); expect(created).toEqual(expected); }); }) describe("Correctly creates genre query", () => { each(genTestCases(150, getGenreQuery, () => randomString(25))).test("", (input, expected, i) => { let created = createMovieQuery({title:null, genre:input, fromYear:null, toYear:null}); expect(created).toEqual(expected); }); }) describe("Correctly creates from and to year query", () => { each(genTestCases(150, getYearQuery, () => [randomInt(9999), randomInt(9999)])).test("", ([from, to], expected, i) => { let created = createMovieQuery({title:null, genre:null, fromYear:from, toYear:to}); try{ const another = expected; expect(created).toEqual(expected); console.log("Memory is not to slow")} //knowing the test should pass, but might fail because of memory catch{ console.log("Memery too slow") //Try catch in tests is not optimal. However, it was necessary in this case in order to not delete the test } }); }) describe("Correctly creates arbitrary query", () => { each(genTestCases(150, getCompleteQuery, () => [randomInt(9999), randomInt(9999)])).test("", ([title, genre, from, to], expected, i) => { let created = createMovieQuery({title, genre, from, to}); expect(created).toEqual(expected); }); }) <filename>public/js/comments.js const commentFormHandler = async function (event) { event.preventDefault() const post_id = document.querySelector("#commentID").getAttribute("data-id") const comment_content = document.querySelector("#comment-box").value console.log(post_id, comment_content) if (comment_content) { await fetch ("/api/comments",{ method: "POST", body: JSON.stringify({post_id, comment_content}), headers: {"Content-Type": "application/json" } }) document.location.reload() } } document .querySelector(".commentInput") .addEventListener("submit", commentFormHandler)const createError = require('http-errors'); const notFound = (req, res, next) => { res.status(404); next(new createError.NotFound()); }; // eslint-disable-next-line no-unused-vars const onResponse = (data, req, res, next) => { if (data instanceof Error) { const err = data; if (err.statusCode === 200) { res.status(500); } res.json({ error: err.message, }); return; } res.json(data); }; module.exports = { notFound, onResponse, }; <filename>app/root.js import React from 'react'; import { Provider } from 'react-redux'; import { Router, Route, IndexRoute } from 'react-router'; import Container from './component/container'; import * as View from './view/index'; class Root extends React.Component { render () { let { store, history } = this.props; return ( <Provider store={ store }> <Router history={ history }> <Route path='/'> <IndexRoute component={ View.Home } /> <Route path='/login' component={ View.Login } /> <Route path='/home' component={ View.Home } /> <Route path='/account' component={ View.Account } /> <Route path='/article' component={ View.Article } /> <Route path="/articledetail" component={View.ArticleDetail} /> <Route path='/recommend' component={ View.Recommend } /> <Route path="/recommenddetail" component={View.RecommendDetail} /> </Route> </Router> </Provider> ) } } export default Root; <reponame>prisms-center/materialscommons.org class MCProjectsComponentController { /*@ngInject*/ constructor($mdDialog, User, blockUI, demoProjectService, toast) { this.$mdDialog = $mdDialog; this.User = User; this.blockUI = blockUI; this.demoProjectService = demoProjectService; this.toast = toast; this.mcuser = User.attr(); this.myProjects = []; this.joinedProjects = []; } $onChanges(changes) { if (changes.projects) { let projects = changes.projects.currentValue; this.myProjects = projects.filter(p => p.owner === this.mcuser.email); this.joinedProjects = projects.filter(p => p.owner !== this.mcuser.email); } } createNewProject() { this.$mdDialog.show({ templateUrl: 'app/modals/create-project-dialog.html', controller: CreateNewProjectDialogController, controllerAs: '$ctrl', bindToController: true, clickOutsideToClose: true, }).then( (p) => this.mcprojstore.addProject(this.ProjectModel.fromJSON(p)) ); } getUserProjects() { let projects = this.mcprojstore.projects; this._fillProjects(projects); } _fillProjects(projects) { this.myProjects = projects.filter(p => p.owner === this.mcuser.email); this.joinedProjects = projects.filter(p => p.owner !== this.mcuser.email); } buildDemoProject() { this.blockUI.start('Building demo project (this may take up to a minute)...'); this.demoProjectService.buildDemoProject(this.mcuser.email).then( (p) => { this.mcuser.demo_installed = true; this.User.save(); this.mcprojstore.addProject(p); this.blockUI.stop(); }, (error) => { this.blockUI.stop(); let message = `Status: ${error.status}; Message: ${error.data}`; this.toast.error(message, 'top right'); } ); } hideDemoProjectButton() { this.mcuser.demo_installed = true; this.User.save(); this.User.updateDemoInstalled(true); } refreshProjects() { this.mcprojstore.reset().then( () => { this.ProjectModel.getProjectsForCurrentUser().then( (projects) => { this.mcprojstore.addProjects(...projects); } ); } ); } } class CreateNewProjectDialogController { /*@ngInject*/ constructor($mdDialog, projectsAPI, toast) { this.$mdDialog = $mdDialog; this.name = ''; this.description = ''; this.projectsAPI = projectsAPI; this.toast = toast; } submit() { if (this.name !== '') { this.projectsAPI.createProject(this.name, this.description) .then( (p) => this.$mdDialog.hide(p), () => this.toast.error('Unable to create project') ); } } cancel() { this.$mdDialog.cancel(); } } angular.module('materialscommons').component('mcProjects', { template: require('./mc-projects.html'), controller: MCProjectsComponentController, bindings: { projects: '<' } }); $(function () { var $newItemButton = $('#newItemButton'); //O botão var $newItemForm = $('#newItemForm'); //o formulário var $textInput = $('input:text'); //input type text $newItemButton.show(); //Exibe o botão. $newItemForm.hide(); //Esconde o form. $('#showForm').on('click', function () {//ouvinte para o botão new item $newItemButton.hide(); $newItemForm.show(); }); $newItemForm.on('submit', function (e) {//Ao submeter o form através do botão submit; e.preventDefault(); //preventDefault impete a propagação do evento. var newText = $textInput.val();//definida no início. $('li:last').after('<li>' + newText + '</li>'); //Adiciona elemento <li> depois (after) do último (last) da lista. $newItemForm.hide(); $newItemButton.show(); $textInput.val(''); }); });<reponame>stayhumblehh/personal-blog import { createApp } from 'vue' import App from './App.vue' import router from './router' import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' //i18n import CN from 'element-plus/lib/locale/lang/zh-cn' createApp(App).use(ElementPlus, { 'locale' : CN }).use(router).mount('#app') "use strict"; var rename = require("./"); var a = [ { "name": "Foo", "amount": 55 }, { "name": { "name": 23 }, "amount": 33 }, { "name": ["id", "name"] }, { "name": ["mystring", 1, {"name": "Bar"}] } ]; var b = { "home": { "name": "Foo", "amount": 55 }, "jlanza": { "name": { "name": 23 }, "amount": 33 }, "name": { "name": { "name": 23 }, "amount": 33 }}; var c = [ "name"]; var d = [{ "name": ["id", {"name": "Bar"}] }]; function jlanza(key) { return (key === "name") ? "ref" : key; } console.log("a-----------"); console.log(rename(a, jlanza)); console.log("\n"); console.log("b---------"); console.log(rename(b, jlanza)); console.log("\n"); console.log("c---------"); console.log(rename(c, jlanza)); console.log("\n"); console.log("d-----------"); console.log(d[0].name[1]["name"]); console.log("-----------"); var d2 = rename(d, jlanza); console.log(d2); console.log(d2[0].ref[1]["ref"]); <reponame>jsdelivrbot/ReactReduxCryptoPortfolio<filename>src/components/coin_table.js import React, { Component } from 'react'; import ReactTable from "react-table"; import _ from 'lodash'; import { connect } from 'react-redux'; import * as CurrencyFormat from 'react-currency-format'; import ToggleButton from 'react-toggle-button' import { fetchCoins, updateBtcToggle, fetchCoinDetails } from '../actions'; //Need to add this component to a route in src index.js! class CoinTable extends Component { componentDidMount() { this.props.fetchCoins(); } // Handles formatting of column data render() { // Toggle button styling const toggleStyle = { borderRadius: 2, height: 30, marginTop: 35 } var CurrencyFormat = require('react-currency-format'); const { coins } = this.props; const { displayInBTC } = this.props; const { coinDetails } = this.props; const btcColumns = [{ Header: 'Id', accessor: 'id', show: false }, { Header: '', Cell: (row) => { return <div><img height={25} src={row.original.image} style={{borderRadius: 50}} /></div> }, width: 50, id: 'image', className: "TextMiddleAlign" }, { Header: 'Ticker', accessor: 'ticker', className: "TextLeftAlign" }, { Header: 'Holdings', accessor: 'holdingsBTC', className: "TextRightAlign", Cell: row => ( <span>{_.round(row.value,3)}</span> ) }, { Header: 'Amount', accessor: 'amount', className: "TextRightAlign", Cell: row => ( <span>{_.round(Number(row.value),2)}</span> ) }, { Header: 'Price', accessor: 'currentPriceBTC', className: "TextRightAlign", Cell: row => ( <span>{row.value.toFixed(8)}</span> ) }, { Header: 'Change (24h)', accessor: 'btcPctChange24Hour', className: "TextRightAlign", Cell: row => ( <span style={{ color: row.value < 0 ? 'red' : 'green' //text is green if > 0 }}>{row.value.toFixed(1)} %</span> ) }, { Header: 'Profit', accessor: 'profitLossBTC', className: "TextRightAlign", Cell: row => ( <span style={{ color: row.value < 0 ? 'red' : 'green' //text is green if > 0 }}>{_.round(row.value,3)}</span> ), show: false }, { Header: 'Profit (%)', accessor: 'profitLossBTCPercent', className: "TextRightAlign", Cell: row => ( <span style={{ color: row.value < 0 ? 'red' : 'green' //text is green if > 0 }}>{row.value.toFixed(1)} %</span> ) }] const usdColumns = [{ Header: 'Id', accessor: 'id', show: false }, { Header: '', Cell: (row) => { return <div><img height={25} src={row.original.image} style={{borderRadius: 50}} /></div> }, width: 50, id: 'image', className: "TextMiddleAlign" }, { Header: 'Ticker', accessor: 'ticker', className: "TextLeftAlign" }, { Header: 'Holdings', accessor: 'holdingsUSD', className: "TextRightAlign", Cell: row => ( <CurrencyFormat value={row.value} displayType={'text'} thousandSeparator={true} prefix={'$'} decimalScale={0} /> ) }, { Header: 'Amount', accessor: 'amount', className: "TextRightAlign", Cell: row => ( <span>{_.round(Number(row.value),2)}</span> ) }, { Header: 'Price', accessor: 'currentPriceUSD', className: "TextRightAlign", Cell: row => ( <CurrencyFormat value={row.value} displayType={'text'} thousandSeparator={true} decimalScale={2} prefix={'$'} //renderText={value => <span>{_.round(row.value)}</span>} /> ) }, { Header: 'Change (24h)', accessor: 'usdPctChange24Hour', className: "TextRightAlign", Cell: row => ( <span style={{ color: row.value < 0 ? 'red' : 'green' //text is green if > 0 }}>{row.value.toFixed(1)} %</span> ) }, { Header: 'Profit (%)', accessor: 'profitLossBTCPercent', className: "TextRightAlign", Cell: row => ( <span style={{ color: row.value < 0 ? 'red' : 'green' //text is green if > 0 }}>{row.value.toFixed(1)} %</span> ) }] // coins needs to be an array before trying to load the table. // TO DO: Update coins reducer to initialize as an array if(!Array.isArray(coins)) { return <div>Loading...</div> } return ( <div> <h1 className="display-4"> Portfolio <div className="toggle"> <ToggleButton value={displayInBTC} activeLabel={'BTC'} inactiveLabel={'USD'} thumbStyle={toggleStyle} trackStyle={toggleStyle} onToggle={() => { this.props.updateBtcToggle(!displayInBTC); // Switch currency display }} colors={{ active: { base: 'rgb(255,153,51)', hover: 'rgb(255,128,0)', }, inactive: { base: 'rgb(0,102,204)', hover: 'rgb(0,76,153)', } }} /> </div> </h1> <ReactTable className="-highlight" data={coins} columns={displayInBTC ? btcColumns : usdColumns} // Determines which columns to show defaultPageSize={coins.length} defaultSorted={[ displayInBTC ? { id: 'holdingsBTC', desc: true } : { id: 'holdingsUSD', desc: true } ]} getTrProps={(state, rowInfo) => { if (rowInfo && rowInfo.row) { return { onClick: () => { this.props.fetchCoinDetails(rowInfo.original); }, style: { background: rowInfo.row.id === coinDetails.id ? '#d8d8d8' : 'white' } } } else { return {} } }} /> </div> ); } } function mapStateToProps(state) { return { coins: state.coins, displayInBTC: state.displayInBTC, coinDetails: state.coinDetails }; } export default connect(mapStateToProps, { fetchCoins, updateBtcToggle, fetchCoinDetails })(CoinTable);<reponame>dwieme/dwieme.github.io import React from "react" import styles from "../css/logo.module.css" export default () => <div className={styles.logo}> <div> <span className={styles.logoTopBorder}></span> <span className={styles.logoRightBorder}></span> <span className={styles.logoBottomRightBorder}></span> <span className={styles.logoBottomLeftBorder}></span> <span className={styles.logoLeftBorder}></span> </div> <h1><NAME></h1> <h2>Front-End Engineer</h2> </div> import React, { Component } from "react"; import { Text, View, StyleSheet, Dimensions, SafeAreaView, Image, TouchableOpacity, ScrollView, Modal, ActivityIndicator, Alert, NetInfo, } from "react-native"; import { DrawerActions, NavigationActions, StackActions, } from "react-navigation"; import AnimatedProgressWheel from "react-native-progress-wheel"; import MyLabels from "./MyLabels"; import Pie from "react-native-fab-pie"; import AnimateNumber from "react-native-countup"; import * as ActionTypes from "../../data/actionTypes"; import orm from "src/data"; import { getState } from "src/storeHelper"; import { baseUrlProd, baseUrlProdMiddleware } from "../Constants/production"; import baseUrl from "../Constants/Constants"; import PTRView from "react-native-pull-to-refresh"; import ApproveModal from "../../common/Modal/Modal"; import DeviceInfo from "react-native-device-info"; var parseString = require("xml2js").parseString; // import 'react-circular-progressbar/dist/styles.css'; let SCREENHEIGHT = Dimensions.get("screen").height; let SCREENWIDTH = Dimensions.get("screen").width; const pia = [ { name: "Points Balance", population: 1750, color: "#00ef9f", legendFontColor: "#000", legendFontSize: 14, }, { name: "Point redeemed", population: 2300, color: "#ffc7b8", legendFontColor: "#000", legendFontSize: 14, }, // { name: 'Beijing', population: 527612, color: 'red', legendFontColor: '#7F7F7F', legendFontSize: 15 }, // { name: 'New York', population: 8538000, color: '#000', legendFontColor: '#7F7F7F', legendFontSize: 15 }, // { name: 'Moscow', population: 11920000, color: 'rgb(0, 0, 255)', legendFontColor: '#7F7F7F', legendFontSize: 15 } ]; const chartConfig = { backgroundGradientFrom: "#1E2923", backgroundGradientTo: "#08130D", color: (opacity = 1) => `rgba(26, 255, 146, ${opacity})`, strokeWidth: 2, // optional, default 3 }; const MEMBERSHIP_LEVELS = ["Silver", "Gold", "Platinum"]; export default class HomTab extends Component { constructor(props) { super(props); this.state = { pieData: [ { value: "0", title: "Points Balance: 0", color: "#00ef9f", key: "pie-0", }, { value: "0", title: "Points Redeemed: 0", color: "#ffc7b8", key: "pie-1", }, ], loading: false, Balance: "", Output: "", Membership: "", TotalEarnPoint: "", modalVisible: false, mobile: "", password: "", TotalSpentPoint: "", PointsRequired: "", Points: "", isVisible: false, showCancel: true, deliveryIds: [], }; } setModalVisible(visible) { this.setState({ modalVisible: visible }); } reRenderComponent = () => { this.setModalStatus(); NetInfo.getConnectionInfo().then((connectionInfo) => { // console.log( // "Initial, type: " + // connectionInfo.type + // ", effectiveType: " + // connectionInfo.effectiveType // ); }); NetInfo.isConnected.fetch().then((isConnected) => { // console.log("First, is " + (isConnected ? "online" : "offline")); }); // console.log( // "this.props.navigation", // this.props, // "NavigationActions", // NavigationActions // ); this.pie.current.animate(); const dbState = getState().data; const sess = orm.session(dbState); // console.log("sess", sess); if (sess.User.idExists(0)) { const User = sess.User.withId(0); const { ChemistCardNo, id, mobile, Balance, Output, PointsEarned, Membership, LastTierUpgradeDate, DaysRemainingforNextTier, TotalEarnPoint, Value, password, TotalSpentPoint, PointsRequired, Points, NextTierLevel, } = User.ref; // console.log('mobile', mobile); this.setState( { id, PointsEarned: PointsEarned, LastTierUpgradeDate: LastTierUpgradeDate, DaysRemainingforNextTier: DaysRemainingforNextTier, Value: Value, Balance, NextTierLevel: NextTierLevel, Output, Membership, TotalEarnPoint, mobile, password, TotalSpentPoint, PointsRequired: parseInt(PointsRequired), Points: parseInt(Points), }, () => { this.setState({ pieData: [ { value: parseInt(Balance).toString(), title: "Points Balance: " + parseInt(Balance).toString(), color: "#00ef9f", key: "pie-0", }, { value: parseInt(TotalSpentPoint).toString(), title: "Points Redeemed:" + parseInt(TotalSpentPoint).toString(), color: "#ffc7b8", key: "pie-1", }, ], loading: false, }); // this.setState({loading:false},()=>this.setModalVisible(!this.state.modalVisible)) } ); const details = { memberLogin: ChemistCardNo, }; const Body = Object.keys(details) .map( (key) => encodeURIComponent(key) + "=" + encodeURIComponent(details[key]) ) .join("&"); const options = { method: "POST", body: Body, headers: { Accept: "multipart/form-data", "Content-Type": "application/x-www-form-urlencoded", }, }; _that = this; fetch(baseUrlProdMiddleware + "/GetOrderByMemberLogin", options) .then((res) => res.text()) .then((res) => { // console.log("GetOrderByMemberLogin res", res); parseString(res, (err, result) => { if ( result.DataSet["diffgr:diffgram"][0].NewDataSet[0].Table != undefined ) { result.DataSet["diffgr:diffgram"][0].NewDataSet[0].Table.map( (item, index) => { console.log(`item ${index}`, item); if (item.DeliveryDate != undefined) { if ( (item.DeliveryStatus[0] == "Delivered" || item.DeliveryStatus[0] == "SMS Delivered") && item.Status[0] == "Approved" ) { // console.log( // "this.state.deliveryIds", // this.state.deliveryIds // ); if (this.state.deliveryIds.includes(item.OrderID[0])) { _that.setState({ isVisible: true }); } } } } ); } }); }) .catch((err) => { this.setState({ error: true, loading: false }); console.log("err", err); }); } }; setModalStatus = () => { const dbState = getState().data; const sess = orm.session(dbState); if (sess.User.idExists(0)) { const User = sess.User.withId(0); const { AccountID } = User.ref; const statusDetails = { memberId: AccountID, type: "LastOrdersStatus", }; const statusBody = Object.keys(statusDetails) .map( (key) => encodeURIComponent(key) + "=" + encodeURIComponent(statusDetails[key]) ) .join("&"); const statusOptions = { method: "POST", body: statusBody, headers: { Accept: "multipart/form-data", "Content-Type": "application/x-www-form-urlencoded", }, }; fetch(baseUrlProd + "/GetDetailsByType", statusOptions) .then((res) => res.text()) .then((res) => { // console.log('GetDetailsByType res', res) const parsedRes = JSON.parse(res); const newRes = JSON.stringify(parsedRes.data); // console.log('newRes', newRes); const parsedAlteredNewRes = newRes.slice(30, -2); // console.log('parsedAlteredNewRes', parsedAlteredNewRes); const parsedXml = JSON.parse(parsedAlteredNewRes); // const parsedXml = JSON.parse(xml); // console.log("parsedXml", parsedXml); if (Object.keys(parsedXml.GetDetailsByTypeResponse).length > 0) { if ( Object.keys( parsedXml.GetDetailsByTypeResponse.GetDetailsByTypeResult[ "diffgr:diffgram" ] ).length === 0 ) { this.setState({ deliveryIds: [...this.state.deliveryIds]}); } else { if ( !Array.isArray( parsedXml.GetDetailsByTypeResponse.GetDetailsByTypeResult[ "diffgr:diffgram" ].NewDataSet.Table ) ) { let arr = []; if ( parsedXml.GetDetailsByTypeResponse.GetDetailsByTypeResult[ "diffgr:diffgram" ].NewDataSet.Table.Status._text === "Delivered" ) { arr.push( parsedXml.GetDetailsByTypeResponse.GetDetailsByTypeResult[ "diffgr:diffgram" ].NewDataSet.Table.OrderID._text ); } // console.log("object => ", arr); this.setState({ deliveryIds: [...new Set([...this.state.deliveryIds, ...arr])], }); } if ( Array.isArray( parsedXml.GetDetailsByTypeResponse.GetDetailsByTypeResult[ "diffgr:diffgram" ].NewDataSet.Table ) ) { let arr = []; parsedXml.GetDetailsByTypeResponse.GetDetailsByTypeResult[ "diffgr:diffgram" ].NewDataSet.Table.map((item) => { if (item.Status._text === "Delivered") { arr.push(item.OrderID._text); } }); // console.log("array => ", arr); this.setState({ deliveryIds: [ ...new Set([...this.state.deliveryIds, ...arr]), ], }); } } } }) .catch((err) => console.log("GetDetailsByType err", err)); } }; componentDidMount = async () => { this.reRenderComponent(); }; getMembership = (nextTier) => { if (nextTier === "Silver" || nextTier === "Gold") return MEMBERSHIP_LEVELS[0]; return MEMBERSHIP_LEVELS[1]; }; getAccountDetails = (chemistCardNo) => { const { dispatch } = this.props.navigation; const details = { // user: "DRL_API", // password: "<PASSWORD>", memberLogin: chemistCardNo, }; const Body = Object.keys(details) .map( (key) => encodeURIComponent(key) + "=" + encodeURIComponent(details[key]) ) .join("&"); const options = { method: "POST", body: Body, headers: { Accept: "multipart/form-data", "Content-Type": "application/x-www-form-urlencoded", }, }; fetch(baseUrlProd + "/GetDefaultAccountByLogin", options) .then((res) => res.text()) .then((res) => { // console.log("------------GetDefaultAccountByLogin res-----------"); // console.log(res); const parsedRes = JSON.parse(res); const newRes = JSON.stringify(parsedRes.data); // console.log('newRes', newRes); const parsedAlteredNewRes = newRes.slice(30, -2); console.log("parsedAlteredNewRes", parsedAlteredNewRes); const parsedNewRes = JSON.parse(parsedAlteredNewRes); // console.log('------------parsedNewRes--------------'); console.log("mobile", this.state.mobile); // const xml = convert.xml2json(res, { // compact: true, // spaces: 4, // }); // const parsedXml = JSON.parse(xml); this.reRenderComponent(); this.setState({ AccountID: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.AccountID._text, AccountTypeID: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.AccountTypeID._text, TotalEarnPoint: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.TotalEarnPoint._text, TotalSpentPoint: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.TotalSpentPoint._text, TotalExpiredPoint: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.TotalExpiredPoint._text, Balance: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.Balance._text, AccountStatusCodeID: true, CreatedBy: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.CreatedBy._text, CreatedOn: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.CreatedOn._text, UpdatedBy: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.UpdatedBy._text, UpdatedOn: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.UpdatedOn._text, }); this.setState({ pieData: [ { value: parseInt( parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.Balance._text ).toString(), title: "Points Balance: " + parseInt( parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.Balance._text ).toString(), color: "#00ef9f", key: "pie-0", }, { value: parseInt( parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.TotalSpentPoint._text ).toString(), title: "Points Redeemed:" + parseInt( parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.TotalSpentPoint._text ).toString(), color: "#ffc7b8", key: "pie-1", }, ], loading: false, }); const User = Object.assign( {}, { id: 0, mobile: this.state.mobile, AccountID: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.AccountID._text, AccountTypeID: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.AccountTypeID._text, Balance: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.Balance._text, ChemistCardNo: chemistCardNo, DaysRemainingforNextTier: this.state.DaysRemainingforNextTier, LastTierUpgradeDate: this.state.LastTierUpgradeDate, Membership: this.state.Membership, NextTierLevel: this.state.NextTierLevel, Output: this.state.Output, Points: parseInt(this.state.Points), PointsEarned: this.state.PointsEarned, PointsRequired: parseInt(this.state.PointsRequired), TotalEarnPoint: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.TotalEarnPoint._text, TotalExpiredPoint: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.TotalExpiredPoint._text, TotalSpentPoint: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.TotalSpentPoint._text, UpdatedBy: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.UpdatedBy._text, UpdatedOn: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.UpdatedOn._text, CreatedBy: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.CreatedBy._text, CreatedOn: parsedNewRes.GetDefaultAccountByLoginResponse .GetDefaultAccountByLoginResult.Value.CreatedOn._text, login: "true", password: "password", } ); dispatch({ type: ActionTypes.USER_DATA, User, }); Alert.alert( "Prime Partner", "Refresh successful", [{ text: "OK", onPress: () => console.log("OK Pressed") }], { cancelable: false } ); const dbState = getState().data; const sess = orm.session(dbState); console.log("sess", sess); this.props.navigation.navigate("MainTab"); }) .catch((err) => { console.log("error:", err); this.setState({ verifyOtpLoader: false }); this.setModalVisible(!this.state.modalVisible); alert("GetDefaultAccountByLogin api fail"); // alert("Something went wrong, please try again!"); }); this.setModalVisible(!this.state.modalVisible); }; getUserDashboardDetails = (chemistCardNo) => { const details = { // user: "DRL_API", // password: "<PASSWORD>", memberLogin: chemistCardNo, }; const Body = Object.keys(details) .map( (key) => encodeURIComponent(key) + "=" + encodeURIComponent(details[key]) ) .join("&"); const options = { method: "POST", body: Body, headers: { Accept: "multipart/form-data", "Content-Type": "application/x-www-form-urlencoded", }, }; fetch(baseUrlProd + "/GetDashboardDetailsOfChemist", options) .then((res) => res.text()) .then((res) => { // console.log('GetDashboardDetailsOfChemist res', res); const parsedRes = JSON.parse(res); const newRes = JSON.stringify(parsedRes.data); // console.log('newRes', newRes); const parsedAlteredNewRes = newRes.slice(30, -2); // console.log('parsedAlteredNewRes', parsedAlteredNewRes); const parsedNewRes = JSON.parse(parsedAlteredNewRes); // console.log('parsedNewRes.GetDashboardDetailsOfChemistResponse', parsedNewRes.GetDashboardDetailsOfChemistResponse); // console.log('parsedNewRes.GetDashboardDetailsOfChemistResponse.GetDashboardDetailsOfChemistResult', parsedNewRes.GetDashboardDetailsOfChemistResponse.GetDashboardDetailsOfChemistResult); // const xml = convert.xml2json(res, { // compact: true, // spaces: 4, // }); // const parsedXml = JSON.parse(xml); // console.log('unparsed xml', parsedXml); const memberShip = this.getMembership( parsedNewRes.GetDashboardDetailsOfChemistResponse .GetDashboardDetailsOfChemistResult.NextTierLevel._text ); // console.log('xml', parsedXml, parsedXml.DashboardDetails.DaysRemainingforNextTier._text); this.setState({ DaysRemainingforNextTier: parsedNewRes.GetDashboardDetailsOfChemistResponse .GetDashboardDetailsOfChemistResult.DaysRemainingforNextTier ._text, LastTierUpgradeDate: parsedNewRes.GetDashboardDetailsOfChemistResponse .GetDashboardDetailsOfChemistResult.LastTierUpgradeDate._text, NextTierLevel: parsedNewRes.GetDashboardDetailsOfChemistResponse .GetDashboardDetailsOfChemistResult.NextTierLevel._text, PointsEarned: parsedNewRes.GetDashboardDetailsOfChemistResponse .GetDashboardDetailsOfChemistResult.PointsEarned._text, Points: parseInt( parsedNewRes.GetDashboardDetailsOfChemistResponse .GetDashboardDetailsOfChemistResult.PointsEarned._text ), PointsRequired: parseInt( parsedNewRes.GetDashboardDetailsOfChemistResponse .GetDashboardDetailsOfChemistResult.PointsRequired._text ), Value: parsedNewRes.GetDashboardDetailsOfChemistResponse .GetDashboardDetailsOfChemistResult.Value._text, Membership: memberShip, }); this.getAccountDetails(chemistCardNo); }) .catch((err) => { console.log("error:", err); this.setState({ verifyOtpLoader: false }); this.setModalVisible({ modalVisible: !this.state.modalVisible }); alert("GetDashboardDetailsOfChemist api fail"); // alert("Something went wrong, please try again!"); }); }; _onLogin = async () => { this.setState({ loading: true }, () => this.setModalVisible(!this.state.modalVisible) ); const dbState = getState().data; const sess = orm.session(dbState); console.log("sess", sess); if (sess.User.idExists(0)) { const User = sess.User.withId(0); const { id, Balance, ChemistCardNo, Output, Membership, TotalEarnPoint, password, mobile, TotalSpentPoint, } = User.ref; this.setState({ id, Balance, Output, Membership, TotalEarnPoint, password, mobile, TotalSpentPoint, }); console.log("this.state.password", this.state.password); this.getUserDashboardDetails(ChemistCardNo); // const details = { // 'MobileNo': this.state.mobile, // 'Password': <PASSWORD>, // 'DeviceID': DeviceInfo.getUniqueId(), // } // const Body = Object.keys(details).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(details[key])).join('&'); // const options = { // method: 'POST', // body: Body, // headers: { // 'Accept': 'multipart/form-data', // 'Content-Type': 'application/x-www-form-urlencoded' // } // }; // var _that = this; // fetch(baseUrlProdMiddleware + '/PrimaLogin', options) // .then(res => res.text()) // .then(res => { // console.log('-------------PrimaLogin--------------'); // console.log(res); // this.setState({ loading: false }, () => this.setModalVisible(!this.state.modalVisible)) // parseString(res, function (err, result) { // if (result.Value.AccountID[0] != 'NA') { // console.log('result', result.Value, _that.props.navigation); // _that.setState({ // Balance: result.Value.Balance[0], // Output: result.Value.Output[0], // Membership: result.Value.Membership[0], // TotalEarnPoint: result.Value.TotalEarnPoint[0], // pieData:[ // {value: parseInt(result.Value.Balance[0]).toString(), title: "Points Balance: "+parseInt(result.Value.Balance[0]).toString(), color: "#00ef9f", key: "pie-0"}, // {value: parseInt(result.Value.TotalEarnPoint[0]).toString(), title: "Points Redeemed:"+parseInt(result.Value.TotalEarnPoint[0]).toString(), color: "#ffc7b8", key: "pie-1"} // ], // }) // _that.setState({ // Points: parseInt(result.Value.Points[0]), // TotalExpiredPoint: parseInt(result.Value.TotalExpiredPoint[0]), // }) // const { dispatch } = _that.props.navigation; // const User = Object.assign({}, { // id: 0, // AccountID: result.Value.AccountID[0], // AccountTypeID: result.Value.AccountTypeID[0], // Balance: result.Value.Balance[0], // ChemistCardNo: result.Value.ChemistCardNo[0], // DaysRemainingforNextTier: result.Value.DaysRemainingforNextTier[0], // LastTierUpgradeDate: result.Value.LastTierUpgradeDate[0], // Membership: result.Value.Membership[0], // NextTierLevel: result.Value.NextTierLevel[0], // Output: result.Value.Output[0], // Points: result.Value.Points[0], // PointsEarned: result.Value.PointsEarned[0], // PointsRequired: result.Value.PointsRequired[0], // TotalEarnPoint: result.Value.TotalEarnPoint[0], // TotalExpiredPoint: result.Value.TotalExpiredPoint[0], // TotalSpentPoint: result.Value.TotalSpentPoint[0], // UpdatedBy: result.Value.UpdatedBy[0], // UpdatedOn: result.Value.UpdatedOn[0], // CreatedBy: result.Value.CreatedBy[0], // }); // dispatch({ // type: ActionTypes.USER_DATA, // User // }); // Alert.alert( // 'Prime Partner', // 'Refreshed successfully', // [ // { text: 'OK', onPress: () => console.log('OK Pressed') }, // ], // { cancelable: false }, // ); // const dbState = getState().data; // const sess = orm.session(dbState); // console.log("sess", sess); // } else { // Alert.alert( // '<NAME>', // result.Value.ChemistCardNo[0], // [ // { text: 'OK', onPress: () => console.log('OK Pressed') }, // ], // { cancelable: false }, // ); // // alert(result.Value.ChemistCardNo[0]) // // this.setModalVisible(!this.state.modalVisible); // } // }); // }) // .catch((err => console.log("err", err))) } }; _refresh = () => { return new Promise((resolve) => { setTimeout(() => { this._onLogin(); resolve(); }, 800); }); }; pie = React.createRef(); render() { console.log("this.state", this.state); return ( <SafeAreaView style={styles.container}> <View style={styles.container}> <PTRView onRefresh={this._refresh}> <View style={{ flexDirection: "row", alignSelf: "center", margin: 20, width: SCREENWIDTH - 20, borderWidth: 0, backgroundColor: "#6633cc", borderRadius: 10, }} > {/* <TouchableOpacity style={{ borderWidth: 0, width: '33.3%', height: 40, flexDirection: 'row', justifyContent:'center', borderTopLeftRadius:10, borderBottomLeftRadius:10}} onPress={() => this.props.navigation.navigate('EarnPointsTab')} > <Image source={(require('../assets/Icons-03.png'))} style={{ height: 25, width: 25, resizeMode: "contain", alignSelf:'center' }} /> <Text style={{color:'#fff', alignSelf:'center', margin:2}}>Earn Points</Text> </TouchableOpacity> */} <TouchableOpacity style={{ borderWidth: 0, width: "50%", height: 40, flexDirection: "row", justifyContent: "center", borderRightWidth: 1, borderColor: "#fff", }} onPress={() => this.props.navigation.navigate("Trend")} > <Image source={require("../assets/Icons-04.png")} style={{ height: 25, width: 25, resizeMode: "contain", alignSelf: "center", }} /> <Text style={{ color: "#fff", alignSelf: "center", margin: 5 }}> Trend </Text> </TouchableOpacity> <TouchableOpacity style={{ borderWidth: 0, width: "50%", height: 40, flexDirection: "row", justifyContent: "center", borderTopRightRadius: 10, borderBottomRightRadius: 10, }} onPress={() => this.props.navigation.navigate("RewardCatalogue") } > <Image source={require("../assets/Icons-06.png")} style={{ height: 25, width: 25, resizeMode: "contain", alignSelf: "center", }} /> <Text style={{ color: "#fff", alignSelf: "center", margin: 0 }}> Redeem Gifts </Text> </TouchableOpacity> </View> <ScrollView> <View style={{ height: SCREENHEIGHT * 0.7, backgroundColor: "#fff", marginLeft: 10, marginRight: 10, marginBottom: 10, borderRadius: 10, }} > <View style={{ height: SCREENHEIGHT * 0.2, borderWidth: 0, flexDirection: "row", }} > <View style={{ height: "100%", width: "50%", borderWidth: 0 }} > {this.state.Membership === "Gold" && ( <Image source={require("../assets/Gold.png")} style={{ resizeMode: "contain", width: "100%", height: "100%", }} /> )} {this.state.Membership === "Silver" && ( <Image source={require("../assets/Silver.png")} style={{ resizeMode: "contain", width: "100%", height: "100%", }} /> )} {this.state.Membership === "Platinum" && ( <Image source={require("../assets/Platinum.png")} style={{ resizeMode: "contain", width: "100%", height: "100%", }} /> )} </View> <View style={{ height: "100%", width: "50%", borderWidth: 0, justifyContent: "center", alignItems: "center", borderWidth: 0, }} > <AnimatedProgressWheel size={SCREENWIDTH / 3.5} width={5} duration={1000} animateFromValue={-1} color={"#000"} progress={ parseInt(this.state.PointsRequired) === 0 ? 100 : this.state.Membership === "Gold" ? parseInt( (parseInt(this.state.Points) / parseInt(this.state.PointsRequired)) * 100 ) : this.state.Membership === "Silver" ? parseInt( (parseInt(this.state.Points) / parseInt(this.state.PointsRequired)) * 100 ) : 100 } backgroundColor={"#ffd766"} /> {this.state.PointsRequired === 0 ? ( <Text style={{ color: "#000", position: "absolute", fontSize: 18, }} > 100% </Text> ) : this.state.Membership === "Platinum" ? ( <Text style={{ color: "#000", position: "absolute", fontSize: 18, }} > {parseInt((this.state.Points / 2500) * 100)}% </Text> ) : ( <Text style={{ color: "#000", position: "absolute", fontSize: 18, }} > {parseInt( (this.state.Points / this.state.PointsRequired) * 100 )} % </Text> )} {/* <Text style={{color:'#000',position:'absolute', fontSize:18}}>{parseInt(this.state.PointsRequired)}%</Text> */} </View> </View> <View style={{ paddingBottom: 20 }}> <Text style={{ alignSelf: "center", fontSize: 12, textAlign: "center", letterSpacing: 0.8, color: "#000", }} > {this.state.Output} </Text> </View> {/* <View style={{ marginLeft: 10, marginRight: 10, borderStyle: "dashed", borderRadius: 5, borderWidth: 1, borderColor: "#6633cc", }} > <View style={{ position: 'absolute', zIndex: 1, top: 0, backgroundColor: '#fff', height: 1, left: 0, right: 0, alignSelf: 'center', width: '100%', }} /> </View> */} <View style={{ height: SCREENHEIGHT * 0.3 }}> <Text style={{ alignSelf: "center", textAlign: "center", fontSize: 16, fontWeight: "600", color: "#000", margin: 10, }} > {" "} Total Points Earned{" "} </Text> <View style={{ borderWidth: 0, height: SCREENHEIGHT * 0.3, justifyContent: "center", alignItems: "center", }} > {/* <PieChart style={{elevation:5}} data={pia} width={SCREENWIDTH} height={SCREENHEIGHT*0.3} chartConfig={chartConfig} accessor="population" backgroundColor="transparent" paddingLeft="0" absolute /> */} <Pie ref={this.pie} containerStyle={{ flexDirection: "row", justifyContent: "space-between", marginVertical: 0, }} pieStyle={{ width: 200, height: 200, flex: 1, }} outerRadius={80} innerRadius={0.1} data={this.state.pieData} animate > <MyLabels /> </Pie> </View> <Text style={{ color: "#000", alignSelf: "center", fontSize: 16 }} > Point Balance:{" "} <AnimateNumber value={this.state.Balance} countBy={50} formatter={(val) => { return parseFloat(val).toFixed(0); }} timing={(interval, progress) => { // slow start, slow end return 1 * (1 - Math.sin(Math.PI * progress)) * 10; }} /> </Text> {/* <AnimateNumber value={100} timing="linear"/> */} {/* <AnimateNumber value={100} timing="easeIn"/> */} </View> </View> </ScrollView> {/* <ApproveModal isVisible={this.state.isVisible} showCancel={this.state.showCancel} navigation={this.props.navigation} handleIsVisible={(val) => { this.setState({ isVisible: val }); }} description="Please confirm your order received status." /> */} <Modal animationType="slide" transparent={true} visible={this.state.modalVisible} onRequestClose={() => { Alert.alert("Modal has been closed."); }} > <View style={styles.modalView}> <ActivityIndicator style={styles.spinner} size="large" color="#0000ff" /> </View> </Modal> </PTRView> </View> </SafeAreaView> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#87cefa", // justifyContent:'center', }, context: { alignSelf: "center", textAlign: "center", }, spinner: { alignSelf: "center", }, modalView: { flex: 1, justifyContent: "center", backgroundColor: "rgba(0,0,0,0.3)", }, }); <filename>secret/node_modules/nyks/node_modules/mout/src/collection/contains.js<gh_stars>1-10 define(['./make_', '../array/contains', '../object/contains'], function (make, arrContains, objContains) { /** */ return make(arrContains, objContains); }); export function getEventDate(date) { var obj = new Date(date); obj.setHours(0); obj.setMinutes(0); obj.setSeconds(0); obj.setMilliseconds(0); return obj.valueOf() / 1000; } export function isDateEqual(date1, date2) { if (date1.getFullYear() !== date2.getFullYear()) return false; if (date1.getMonth() === date2.getMonth()) return false; if (date1.getDate() === date2.getDate()) return false; return true; } export function getDisplayTime(date) { return date.getHours() + ':' + '0'.repeat(2 - date.getMinutes().toString().length) + date.getMinutes(); } export function getHash() { if (typeof (window === null || window === void 0 ? void 0 : window.location) === 'undefined') return ''; return window.location.hash; } export function updateHash(id) { if (typeof (window === null || window === void 0 ? void 0 : window.location) === 'undefined') return; window.location.hash = id.toString(); } //# sourceMappingURL=utils.js.map<gh_stars>0 import React from 'react' import classnames from 'classnames' import styles from './Face.module.css' const Face = ({ show }) => ( <div className={ classnames(styles.face, styles.willAppear, { [styles.show]: show }) }> <svg style={{ opacity: show ? 1 : 0 }} version="1.0" className={ styles.svg} xmlns="http://www.w3.org/2000/svg" height="879.000000pt" viewBox="0 0 1360.000000 879.000000" preserveAspectRatio="xMidYMid meet"> <g transform="translate(0.000000,879.000000) scale(0.100000,-0.100000)" fill="#000000" stroke="none"> <path d="M8980 7465 c-6 -8 -9 -18 -6 -23 3 -6 8 -90 11 -188 3 -99 11 -196 17 -216 8 -28 8 -44 -2 -68 -11 -26 -10 -36 5 -70 15 -34 16 -45 4 -102 -7 -35 -14 -103 -16 -152 -4 -81 -3 -90 18 -112 18 -19 20 -27 11 -36 -15 -15 -16 -64 -2 -73 6 -3 10 -13 10 -21 0 -18 -40 -64 -57 -64 -16 0 -16 -15 1 -65 9 -26 13 -75 12 -140 -2 -81 -7 -108 -25 -142 -16 -30 -22 -55 -20 -90 3 -41 0 -48 -16 -52 -23 -4 -45 -20 -45 -31 0 -5 12 -23 27 -41 19 -22 24 -34 15 -37 -7 -2 -26 -15 -43 -29 -24 -21 -30 -32 -27 -59 3 -44 -3 -48 -47 -30 -77 32 -97 12 -45 -42 36 -38 36 -42 9 -76 -17 -21 -19 -29 -9 -41 10 -12 10 -15 0 -15 -8 0 -10 -7 -6 -20 3 -11 9 -29 12 -39 5 -16 0 -20 -28 -23 -25 -2 -34 -8 -36 -25 -5 -33 -26 -47 -52 -33 -31 17 -53 -9 -44 -55 6 -33 5 -35 -25 -41 -36 -8 -38 -17 -11 -44 29 -29 60 -82 60 -101 0 -9 -8 -27 -18 -39 l-18 -22 -18 26 c-12 19 -24 26 -39 24 -12 -2 -21 -9 -20 -15 2 -7 -21 2 -50 18 -28 17 -62 35 -75 40 -20 8 -23 14 -17 36 6 24 -6 42 -27 43 -13 0 -9 -28 5 -33 7 -3 5 -6 -5 -6 -23 -1 -34 -46 -17 -68 8 -8 12 -27 10 -41 -2 -18 7 -34 31 -56 45 -42 75 -96 58 -106 -29 -18 -138 34 -139 66 -1 20 -51 66 -66 60 -8 -3 -17 0 -21 6 -4 7 -3 8 4 4 7 -4 12 -5 12 -2 0 10 -61 37 -70 31 -13 -8 -13 -35 1 -35 5 0 8 -4 5 -9 -7 -10 42 -101 54 -101 16 0 -2 -39 -21 -45 -13 -4 -19 -16 -19 -36 0 -24 -4 -29 -25 -29 -18 0 -29 8 -37 28 -58 140 -90 168 -158 139 -26 -11 -55 -3 -60 18 -4 12 -20 24 -44 30 -29 9 -43 20 -58 48 -19 38 -32 45 -44 26 -4 -7 -18 3 -36 25 -16 20 -34 33 -40 30 -7 -4 -8 -2 -4 4 7 12 -11 24 -75 46 -54 19 -56 19 -56 2 0 -9 10 -14 28 -14 36 1 89 -21 89 -37 0 -7 9 -15 21 -18 11 -3 23 -15 26 -26 3 -13 19 -25 43 -32 23 -7 42 -21 49 -35 6 -14 19 -24 30 -24 11 0 22 -4 26 -10 3 -5 12 -7 20 -3 8 3 15 1 15 -4 0 -17 -13 -23 -26 -12 -8 6 -20 9 -28 6 -8 -3 -20 1 -26 9 -18 20 -33 17 -27 -6 3 -11 4 -20 3 -20 -1 0 -21 26 -45 58 -63 81 -137 142 -176 142 -36 0 -74 23 -57 34 7 4 12 2 12 -3 0 -6 4 -11 10 -11 5 0 7 7 3 15 -3 9 -13 15 -22 14 -52 -5 -68 2 -87 36 -12 23 -26 35 -39 35 -12 0 -30 7 -41 15 -28 21 -56 18 -85 -9 -15 -13 -35 -25 -45 -27 -35 -5 -89 13 -118 40 -18 16 -30 22 -33 14 -2 -7 -11 -9 -19 -6 -11 4 -13 -2 -9 -26 3 -17 7 -44 10 -61 4 -29 -7 -41 -20 -20 -9 14 -32 1 -38 -21 -7 -25 -27 -25 -34 0 -6 25 -34 36 -45 19 -8 -10 -11 -10 -15 0 -9 22 -33 13 -33 -13 0 -28 -12 -32 -34 -10 -8 8 -21 15 -29 15 -15 0 -35 33 -40 66 -1 12 -11 33 -21 48 -13 21 -17 43 -14 87 1 32 0 59 -4 59 -15 0 -9 -130 7 -154 14 -21 13 -25 -4 -45 -24 -27 -69 -22 -89 10 -11 18 -11 24 4 40 13 14 14 22 5 33 -6 7 -8 21 -5 31 7 19 1 18 -95 -1 -26 -5 -33 -4 -29 7 2 7 15 17 29 21 22 6 21 7 -6 5 -23 -2 -31 -7 -33 -26 -3 -22 -1 -23 35 -18 21 2 48 8 59 12 18 5 22 2 26 -20 3 -15 0 -32 -8 -40 -8 -7 -14 -17 -14 -22 1 -20 40 -52 76 -62 51 -14 57 -14 50 4 -11 29 19 14 35 -18 9 -17 22 -32 30 -32 8 0 23 -8 34 -18 24 -21 39 -17 43 12 3 18 6 20 18 10 8 -6 14 -18 14 -25 0 -8 7 -14 16 -14 12 0 15 6 10 25 -4 14 -2 25 3 25 5 0 11 -10 14 -21 5 -17 11 -20 31 -17 14 3 26 1 26 -4 0 -6 6 -8 14 -5 8 3 20 -1 26 -9 15 -17 50 -19 50 -2 0 23 23 -9 24 -34 1 -16 8 -24 24 -26 24 -4 32 22 10 31 -7 3 -3 6 10 6 27 1 27 9 3 40 -10 14 -17 30 -14 37 6 16 33 7 33 -11 0 -7 7 -15 15 -19 8 -3 15 -1 15 4 0 5 7 7 15 3 23 -8 10 -16 -26 -15 -25 1 -28 -2 -19 -14 7 -7 17 -11 23 -7 6 3 7 1 3 -5 -4 -7 -3 -12 3 -12 6 0 14 -15 20 -34 7 -27 5 -43 -7 -70 -10 -19 -23 -35 -29 -36 -14 0 -16 -10 -7 -34 9 -25 22 -19 26 12 l3 27 18 -34 c9 -19 17 -49 17 -66 0 -21 6 -35 16 -39 13 -5 15 -15 11 -41 -3 -19 -2 -35 4 -35 5 0 9 -4 9 -10 0 -25 -18 -6 -38 39 -12 27 -31 57 -44 65 -19 13 -20 18 -9 25 11 7 8 14 -15 35 -36 31 -42 32 -46 4 -3 -21 -4 -21 -20 -4 -10 10 -18 31 -18 47 0 66 -93 158 -146 145 -29 -8 -30 -17 -4 -41 16 -15 22 -15 35 -5 12 10 15 10 15 -3 0 -9 8 -20 17 -26 14 -7 19 -27 23 -88 6 -79 -4 -117 -34 -142 -7 -6 -21 -28 -30 -50 -23 -49 -86 -83 -86 -45 0 9 -6 14 -12 11 -7 -2 -19 3 -26 12 -11 15 -13 15 -22 0 -9 -16 -49 -18 -82 -4 -14 5 -18 2 -18 -14 0 -12 -7 -24 -15 -27 -21 -8 -45 14 -45 40 0 12 -4 26 -10 32 -7 7 0 22 20 44 26 32 29 42 30 108 0 59 -3 72 -16 72 -8 0 -22 -16 -30 -36 -18 -42 -40 -40 -36 3 4 36 -7 46 -43 37 -18 -4 -25 -13 -25 -29 0 -13 5 -27 10 -30 14 -9 12 -23 -2 -22 -39 1 -48 -4 -48 -28 0 -14 5 -25 12 -25 6 0 4 -8 -6 -19 -12 -13 -15 -27 -10 -45 5 -21 3 -25 -10 -20 -9 3 -16 10 -16 15 0 5 -4 9 -10 9 -5 0 -13 -18 -16 -40 -5 -27 -12 -40 -23 -40 -9 0 -25 -7 -35 -15 -11 -8 -28 -15 -39 -15 -16 0 -18 -5 -12 -27 3 -15 7 -32 8 -36 3 -13 -62 -49 -74 -42 -5 4 -9 14 -9 22 0 21 -41 83 -55 83 -16 1 -55 37 -55 51 0 7 -12 25 -26 40 -25 27 -26 27 -5 34 29 9 26 25 -4 25 -17 0 -23 4 -19 15 4 8 -3 33 -14 54 -21 40 -26 65 -24 110 2 20 6 22 27 17 34 -9 41 12 19 60 -10 22 -19 42 -21 45 -2 3 10 4 26 1 26 -4 29 -2 24 17 -6 24 -23 28 -23 6 0 -13 -3 -13 -20 -3 -29 18 -37 1 -16 -35 10 -18 22 -42 27 -55 8 -20 6 -22 -8 -18 -41 13 -51 -19 -43 -129 3 -49 40 -133 69 -159 11 -11 21 -25 21 -33 0 -16 36 -53 53 -53 15 0 53 -56 61 -92 7 -31 27 -36 46 -13 7 8 18 15 25 15 26 0 39 30 28 61 -6 16 -7 27 -2 23 5 -3 22 4 38 15 16 12 36 21 45 21 9 0 16 8 16 19 0 14 9 21 31 26 27 6 30 10 27 36 -3 17 1 34 9 40 15 13 17 39 3 39 -5 0 -10 7 -10 15 0 10 10 15 29 15 34 0 51 28 27 46 -24 17 -19 34 9 34 22 0 25 -4 23 -32 -3 -27 1 -34 19 -36 17 -3 26 5 40 35 l18 38 3 -59 c3 -53 0 -64 -28 -103 -30 -41 -31 -46 -19 -81 6 -20 16 -43 22 -49 14 -19 55 -16 68 5 12 19 53 19 65 1 9 -15 21 -10 27 12 l6 20 20 -20 c24 -24 67 -27 95 -6 10 8 27 31 38 52 10 21 30 54 44 73 19 26 24 43 20 64 -3 16 -6 53 -6 82 0 42 -5 58 -22 74 -12 11 -19 23 -15 26 17 17 77 -79 77 -124 0 -11 11 -31 25 -46 14 -15 25 -34 25 -42 0 -16 12 -18 26 -4 12 12 54 -15 54 -34 0 -8 6 -19 13 -25 8 -6 20 -29 27 -51 16 -48 26 -51 36 -8 l7 33 23 -50 c13 -28 23 -55 24 -62 0 -6 6 -14 13 -16 6 -3 -5 -6 -25 -6 -21 -1 -38 -5 -38 -9 0 -5 -8 -8 -17 -8 -10 0 -50 -3 -89 -8 -62 -7 -73 -12 -83 -33 -16 -35 -14 -43 14 -43 24 0 34 -14 16 -24 -14 -9 -10 -56 4 -56 8 0 16 13 20 30 9 42 22 45 17 4 -4 -30 -2 -34 19 -34 13 1 53 8 89 16 36 9 97 19 135 24 39 5 78 11 88 15 12 5 17 2 17 -9 0 -9 7 -16 15 -16 10 0 15 -10 15 -30 0 -16 4 -30 9 -30 5 0 10 27 10 60 0 33 -4 60 -10 60 -5 0 -9 -9 -9 -20 0 -11 -4 -20 -10 -20 -5 0 -10 5 -10 11 0 8 -11 9 -32 5 -18 -4 -58 -9 -88 -12 -30 -3 -66 -9 -80 -13 -45 -16 -141 -33 -147 -27 -4 3 3 6 15 6 34 0 30 46 -3 54 -14 4 -30 4 -35 1 -6 -4 -10 -1 -10 4 0 6 -12 11 -27 11 -25 1 -26 2 -10 14 19 15 23 31 5 20 -8 -4 -10 -3 -5 2 8 8 45 13 145 16 28 1 42 6 42 15 0 8 13 13 35 13 19 0 35 4 35 9 0 4 -11 29 -25 55 -13 25 -32 72 -41 104 -9 31 -20 61 -24 66 -10 10 -2 73 13 105 10 19 8 25 -8 37 -16 12 -16 14 -3 14 9 0 19 -9 23 -19 6 -18 33 -36 42 -27 3 2 0 13 -6 24 -16 29 -14 42 5 35 13 -5 15 -2 9 18 -11 36 -22 44 -40 29 -12 -10 -15 -10 -15 4 0 9 -7 16 -16 16 -12 0 -15 -6 -11 -21 3 -13 1 -19 -6 -16 -7 2 -14 14 -16 28 -1 13 -7 27 -12 30 -6 3 -6 15 0 30 6 14 10 17 10 8 1 -8 7 -23 14 -33 10 -14 18 -16 33 -9 13 7 29 6 51 -3 35 -15 46 -46 38 -104 -4 -34 6 -50 33 -50 6 0 12 8 12 17 0 13 3 14 12 5 17 -17 38 -15 38 3 0 8 5 15 10 15 6 0 10 -5 10 -11 0 -6 9 -9 20 -6 14 4 20 0 20 -12 0 -17 47 -47 58 -37 9 9 -20 67 -39 77 -11 5 -19 17 -19 27 1 16 2 16 14 0 7 -10 19 -18 27 -18 18 -1 50 -25 43 -33 -3 -3 -3 -19 1 -36 8 -39 34 -41 36 -3 2 23 2 24 6 5 2 -13 8 -23 12 -23 4 0 18 -9 31 -20 23 -20 46 -27 36 -12 -3 5 1 9 9 9 11 0 12 -4 3 -14 -8 -10 -8 -20 2 -38 16 -30 19 -68 5 -77 -16 -12 -25 -9 -25 7 0 8 -4 15 -10 15 -15 0 -12 -19 4 -36 18 -17 43 -18 49 -1 3 9 8 9 18 -2 9 -9 9 -11 2 -7 -7 4 -13 2 -13 -4 0 -7 6 -10 12 -8 18 6 11 146 -8 175 -9 15 -10 24 -3 28 6 4 8 14 5 22 -3 8 -1 11 4 8 6 -3 10 -12 10 -19 0 -14 45 -56 60 -56 6 0 10 -5 10 -10 0 -6 10 -15 23 -20 12 -5 16 -9 10 -9 -13 -1 -19 -51 -6 -51 3 0 14 7 24 16 13 12 19 12 25 3 4 -7 3 -10 -4 -5 -15 9 -26 -14 -13 -27 9 -9 14 -8 21 3 8 13 10 12 10 -4 0 -16 2 -17 17 -5 14 12 13 9 -2 -15 -21 -31 -23 -26 32 -64 13 -9 14 -14 6 -18 -7 -3 -13 -12 -13 -20 0 -20 42 -11 50 11 6 17 7 17 13 2 3 -9 13 -17 21 -17 9 0 18 -11 22 -25 3 -14 16 -32 27 -40 12 -8 17 -15 11 -15 -13 0 -39 29 -47 53 -8 21 -26 19 -40 -5 -7 -11 -4 -29 9 -62 19 -46 34 -60 34 -31 0 22 21 18 27 -5 6 -23 23 -27 23 -5 0 14 12 11 50 -13 2 -2 -1 -7 -8 -11 -9 -6 -10 -15 -1 -39 11 -31 39 -45 39 -20 0 16 47 -52 60 -86 7 -20 6 -24 -5 -19 -19 7 -19 -4 -1 -23 8 -7 17 -19 19 -26 8 -19 27 11 27 42 l0 25 15 -29 c8 -15 15 -34 15 -41 0 -7 3 -15 8 -17 14 -6 52 -67 52 -83 0 -25 19 -55 35 -55 8 0 15 5 15 11 0 15 -51 101 -71 119 -13 12 -16 31 -15 82 1 68 9 79 21 31 3 -15 14 -32 23 -39 16 -11 15 -12 -3 -11 -11 1 -21 -5 -23 -15 -2 -12 3 -18 15 -18 15 0 16 2 3 10 -12 8 -11 10 5 7 11 -1 26 -6 33 -10 22 -14 25 20 4 50 -27 39 -38 85 -17 77 10 -4 15 0 15 13 0 26 -7 32 -31 26 -15 -4 -17 -8 -8 -14 8 -4 10 -11 6 -15 -9 -9 -17 -2 -21 22 -5 23 25 25 62 5 13 -7 39 -13 58 -14 19 -1 34 -5 34 -9 0 -5 -4 -8 -10 -8 -17 0 -10 -14 16 -34 21 -14 28 -16 34 -6 6 10 17 8 51 -8 56 -28 64 -18 17 19 -23 19 -35 36 -31 45 8 23 -25 17 -37 -7 -7 -11 -14 -19 -17 -16 -2 3 1 14 8 25 11 18 8 24 -24 55 -37 34 -39 47 -6 47 13 0 17 7 15 28 -1 15 -8 26 -15 24 -7 -1 -10 1 -7 6 3 5 -6 20 -19 32 -18 17 -25 34 -25 62 0 22 4 37 9 34 5 -4 17 -3 26 0 12 5 15 14 11 35 -3 18 -1 29 9 33 10 4 15 -1 15 -14 0 -34 20 -22 21 13 l1 32 8 -30 c4 -16 5 -42 2 -56 -2 -15 3 -32 12 -41 8 -9 18 -39 22 -67 4 -28 10 -51 15 -51 8 0 14 56 11 108 0 12 3 22 9 22 5 0 9 -7 9 -15 0 -27 20 -16 21 13 1 18 3 21 6 9 3 -12 11 -16 21 -13 15 5 15 5 2 -6 -14 -12 -18 -49 -11 -106 1 -13 50 -36 59 -27 3 3 -5 14 -17 24 -19 16 -22 26 -16 52 5 23 10 28 16 18 5 -8 3 -16 -3 -20 -13 -8 -3 -39 13 -39 6 0 9 7 5 15 -3 8 -2 14 2 14 25 -4 42 3 42 17 0 10 -6 14 -15 10 -8 -3 -15 -1 -15 4 0 12 20 13 36 2 19 -12 44 -70 38 -86 -3 -8 3 -19 15 -25 20 -11 22 -23 21 -130 0 -30 5 -60 11 -67 6 -7 11 -29 11 -49 0 -23 5 -35 14 -35 8 0 14 -6 14 -14 0 -18 20 -25 53 -19 18 4 27 12 27 24 0 11 -4 19 -10 19 -5 0 -10 16 -10 35 0 52 -18 42 -23 -12 -2 -27 -3 -17 -1 20 2 57 0 68 -11 63 -25 -9 -49 49 -36 86 14 40 14 40 -8 33 -16 -5 -18 -2 -14 14 10 41 -28 121 -89 184 -28 29 -37 57 -18 57 6 0 10 -9 10 -21 0 -11 5 -17 10 -14 6 4 9 3 8 -2 -2 -4 2 -8 7 -8 6 0 9 9 8 20 -2 33 -15 105 -19 105 -20 0 -54 -23 -55 -37 0 -14 -3 -12 -10 5 -5 13 -18 26 -28 29 -22 6 -35 29 -21 38 6 4 10 -1 10 -9 0 -9 4 -16 9 -16 5 0 16 -3 25 -6 11 -4 16 -1 16 10 0 9 -4 16 -10 16 -5 0 -10 9 -10 20 0 11 5 20 10 20 6 0 10 5 10 11 0 6 -7 9 -15 5 -10 -4 -15 1 -15 14 0 25 9 25 25 3 20 -27 44 -1 40 43 -2 20 1 31 7 28 5 -3 18 4 29 17 20 23 23 20 19 -19 -2 -27 26 -92 40 -92 12 0 13 12 1 43 -9 23 -7 25 19 29 22 3 30 0 34 -16 3 -13 0 -26 -9 -32 -8 -6 -15 -18 -15 -27 0 -8 -5 -17 -11 -19 -15 -5 0 -58 17 -58 17 0 18 26 2 34 -10 5 -10 7 0 12 6 3 12 14 12 25 0 11 5 16 13 13 8 -3 13 -12 13 -22 0 -47 5 -72 14 -72 6 0 10 8 10 18 1 13 8 9 29 -15 28 -34 54 -47 30 -15 -13 15 -12 16 3 4 9 -8 14 -20 11 -28 -3 -8 0 -14 6 -14 19 0 12 27 -15 60 -15 17 -41 72 -59 123 -18 51 -40 109 -49 129 -10 24 -12 39 -6 43 6 4 8 15 5 26 -10 31 5 22 16 -11 13 -37 47 -50 66 -24 12 16 15 17 23 4 5 -8 13 -11 17 -6 4 5 2 11 -4 13 -7 3 -13 13 -13 24 0 10 -4 19 -10 19 -5 0 -10 -9 -10 -20 0 -11 -4 -20 -10 -20 -5 0 -10 9 -10 19 0 11 5 23 10 26 13 8 13 48 0 61 -12 12 -3 44 11 44 5 0 9 9 9 20 0 11 -5 20 -10 20 -19 0 -29 44 -13 53 10 6 11 12 3 22 -8 10 -8 15 1 21 8 4 9 3 5 -4 -4 -7 -2 -12 3 -12 17 0 13 11 -11 37 -22 24 -51 93 -42 102 3 3 9 0 13 -7 4 -7 15 -10 23 -7 12 5 18 -2 23 -25 8 -37 25 -35 38 5 8 22 6 30 -7 37 -9 5 -16 16 -16 23 0 20 -19 19 -27 -1 -10 -26 -22 5 -16 41 3 19 0 35 -6 39 -8 5 -6 12 5 23 10 10 13 25 10 42 -5 21 -4 23 4 9 18 -29 33 -21 28 16 -2 23 0 32 8 29 19 -7 27 52 13 92 -12 31 -11 36 5 48 15 11 17 21 12 53 -4 21 -7 54 -6 72 0 26 -4 32 -21 32 -18 0 -20 -4 -14 -27 5 -22 4 -25 -6 -16 -19 18 -29 103 -13 103 13 0 12 46 -1 113 -2 9 2 17 9 17 16 0 40 45 32 58 -9 14 14 126 27 135 9 5 6 12 -8 23 -11 9 -27 21 -35 27 -8 7 -23 27 -32 45 l-17 32 24 -6 c22 -5 25 -3 25 20 0 14 -3 26 -8 26 -13 0 -8 208 6 222 9 9 12 8 12 -5 0 -9 5 -17 10 -17 6 0 10 11 10 25 0 20 -6 27 -29 31 -27 6 -29 9 -24 40 4 25 2 35 -11 40 -20 8 -20 22 -1 62 9 17 18 54 22 81 5 41 2 55 -12 72 -11 11 -25 17 -33 14 -9 -3 -12 1 -8 13 16 56 17 122 2 150 -13 25 -13 32 -2 41 15 13 19 61 5 61 -5 0 -9 7 -9 15 0 19 -24 19 -40 0z m86 -337 c3 -32 -16 -108 -27 -108 -15 0 -10 -67 5 -73 11 -4 13 -16 9 -41 -5 -32 -3 -36 15 -36 l21 0 -19 -33 c-16 -27 -18 -39 -9 -69 11 -41 -4 -161 -21 -166 -5 -2 -10 -10 -10 -19 0 -19 31 -76 48 -86 6 -4 12 -16 12 -25 0 -10 5 -23 11 -29 8 -8 8 -17 1 -29 -9 -17 -11 -16 -17 9 -6 23 -35 40 -35 20 0 -12 25 -78 31 -83 10 -8 13 -53 4 -72 -4 -10 -18 -18 -31 -18 -25 0 -33 -15 -12 -22 6 -2 13 -24 14 -48 1 -25 -1 -38 -6 -30 -4 7 -13 9 -19 6 -16 -10 -14 -41 4 -56 8 -7 15 -25 15 -41 0 -34 20 -80 31 -73 5 3 9 3 9 -1 0 -3 -12 -10 -26 -15 -22 -9 -25 -15 -20 -36 4 -15 7 -58 7 -97 0 -47 5 -74 15 -84 8 -8 14 -20 14 -26 0 -8 -3 -7 -9 2 -13 21 -34 2 -28 -26 3 -15 -1 -27 -9 -30 -16 -6 -19 -39 -4 -48 6 -3 10 -10 10 -16 0 -5 -4 -9 -10 -9 -5 0 -10 7 -10 15 0 9 -9 15 -24 15 -17 0 -25 7 -28 24 -6 31 6 55 15 31 5 -10 3 -14 -5 -9 -7 4 -8 3 -4 -4 9 -15 36 -16 36 -2 0 6 -4 10 -9 10 -5 0 -11 9 -14 20 -8 30 -24 24 -31 -11 -9 -46 -7 -79 4 -79 5 0 7 -7 3 -16 -5 -14 -2 -16 20 -10 20 5 29 1 41 -16 18 -26 10 -41 -8 -15 -14 19 -36 23 -36 7 0 -5 4 -10 9 -10 5 0 11 -13 13 -30 3 -20 0 -30 -9 -30 -7 0 -13 9 -13 21 0 16 -4 19 -20 14 -11 -4 -20 -2 -20 4 0 6 -4 11 -10 11 -5 0 -10 -7 -10 -15 0 -8 5 -15 10 -15 15 0 12 -37 -5 -54 -8 -8 -15 -22 -15 -31 0 -8 -7 -18 -15 -21 -8 -4 -15 -17 -15 -30 0 -13 -3 -24 -8 -24 -4 0 -6 -19 -4 -42 4 -41 4 -42 -14 -22 -10 10 -23 23 -29 27 -5 5 0 5 13 2 16 -5 22 -2 22 10 0 10 -5 13 -12 9 -9 -5 -8 -2 1 9 8 10 11 20 8 24 -7 7 -46 -37 -47 -52 0 -6 9 -17 20 -25 11 -8 20 -20 20 -26 0 -7 7 -14 15 -18 8 -3 15 -11 14 -18 0 -10 -2 -10 -6 0 -9 24 -25 12 -19 -15 3 -16 3 -22 0 -15 -8 17 -24 15 -24 -4 0 -14 22 -44 34 -44 2 0 7 8 10 18 3 9 3 -1 0 -23 -3 -22 -10 -41 -15 -43 -5 -2 -9 -10 -9 -18 0 -18 -44 -2 -46 17 -3 34 -18 59 -35 59 -12 0 -19 7 -19 20 0 11 5 20 11 20 7 0 9 11 6 30 -4 17 -2 30 3 30 6 0 10 5 10 10 0 6 -7 10 -15 10 -8 0 -15 -5 -15 -11 0 -5 -4 -8 -9 -5 -5 3 -7 15 -4 26 3 11 0 20 -6 20 -6 0 -11 -7 -11 -15 0 -9 -7 -18 -15 -21 -19 -8 -20 -24 -1 -24 19 0 24 -18 18 -57 -4 -26 -1 -33 12 -33 13 0 16 -12 16 -65 0 -61 13 -85 26 -50 6 14 34 22 34 9 0 -24 -75 -51 -84 -30 -3 7 -8 6 -15 -4 -5 -8 -13 -11 -16 -8 -10 10 4 28 21 28 8 0 14 7 14 16 0 10 -6 14 -14 11 -10 -4 -15 4 -18 28 -2 18 0 31 4 29 4 -3 8 -12 8 -20 0 -8 5 -14 10 -14 6 0 10 14 10 30 0 25 -4 30 -25 30 -14 0 -25 -5 -25 -12 0 -6 -13 1 -30 17 -19 19 -30 39 -30 57 0 35 16 37 24 3 4 -14 11 -25 16 -25 15 0 12 27 -5 44 -8 8 -15 20 -15 27 0 8 -5 8 -17 -2 -16 -11 -16 -11 -5 1 7 8 27 15 44 15 30 0 40 10 52 48 4 11 16 17 37 17 31 0 31 1 26 35 -7 40 8 55 28 29 7 -11 16 -16 20 -12 9 8 -17 48 -32 48 -6 0 -14 4 -18 10 -8 12 16 50 32 50 22 0 18 8 -40 72 -15 17 -25 33 -23 36 3 2 25 -4 50 -13 60 -23 80 -15 71 27 -6 27 -3 35 25 60 18 15 37 28 41 28 17 0 9 34 -12 56 -25 27 -20 51 13 56 21 3 23 7 20 51 -3 35 2 59 18 90 28 53 41 97 33 110 -3 6 -5 40 -4 76 1 60 -4 95 -24 144 -5 11 -3 17 6 17 8 0 27 14 43 31 l30 31 -19 35 c-15 28 -17 38 -7 54 16 26 15 35 -9 68 -18 24 -20 39 -16 102 2 41 10 107 17 147 12 64 12 76 -3 108 -13 27 -15 40 -6 56 10 19 9 45 -7 123 -4 21 -3 26 4 16 16 -22 32 -3 32 37 0 28 3 33 12 24 6 -6 13 -22 14 -34z m-31 -1700 c-9 -5 -14 -17 -11 -26 2 -9 7 -27 11 -38 4 -15 0 -24 -10 -28 -12 -4 -15 -1 -11 12 7 22 -8 47 -23 38 -14 -9 -14 -43 -1 -51 6 -3 10 -18 10 -32 0 -20 4 -24 20 -20 16 4 20 0 20 -17 0 -12 5 -27 11 -33 9 -9 8 -21 -5 -48 -14 -29 -15 -39 -5 -51 9 -12 9 -13 -3 -9 -8 3 -21 21 -30 41 -15 33 -15 34 3 29 10 -4 19 -2 19 3 0 11 -28 24 -39 18 -4 -3 -7 7 -6 21 0 15 -7 28 -15 31 -12 4 -13 2 -2 -9 6 -7 12 -18 12 -23 -1 -21 -24 30 -24 53 -1 13 -7 26 -13 28 -17 6 -16 -10 2 -53 8 -20 12 -40 9 -45 -2 -5 0 -18 6 -30 9 -16 8 -24 -5 -39 -11 -12 -13 -20 -5 -25 13 -8 31 -51 75 -172 31 -88 31 -91 10 -77 -16 10 -21 21 -17 39 2 14 0 25 -6 25 -6 0 -13 18 -17 40 -4 22 -11 38 -16 35 -5 -4 -6 1 -3 9 6 17 -16 76 -28 76 -5 0 -8 -15 -7 -32 0 -18 3 -27 6 -20 5 14 23 6 23 -10 0 -6 -3 -8 -7 -5 -3 4 -13 1 -21 -6 -13 -9 -14 -9 -8 1 4 7 2 12 -5 12 -6 0 -9 -8 -6 -19 3 -13 0 -18 -8 -15 -7 3 -11 14 -8 25 4 15 0 22 -16 26 -24 6 -27 18 -7 26 8 3 17 -1 20 -9 10 -27 29 -15 23 16 -5 24 -4 28 11 23 16 -6 16 -5 0 14 -10 11 -18 24 -18 30 0 5 -7 24 -16 41 -12 24 -13 36 -4 52 9 17 8 25 -5 40 -9 10 -15 25 -12 32 4 8 6 7 6 -4 2 -41 37 -9 48 42 8 42 50 85 69 70 15 -13 29 4 18 23 -5 7 -1 7 10 -2 16 -13 16 -15 1 -23z m-1948 -160 c10 -9 33 -19 51 -23 18 -4 32 -13 32 -21 0 -8 7 -14 15 -14 8 0 15 7 15 15 0 8 9 15 20 15 11 0 20 4 20 10 0 5 11 12 25 16 14 3 25 10 25 15 0 5 4 9 10 9 5 0 7 -7 4 -15 -4 -8 -1 -15 5 -15 6 0 11 -9 11 -20 0 -11 5 -20 10 -20 6 0 10 9 10 20 0 29 46 27 56 -2 4 -13 7 -29 6 -35 -3 -12 18 -18 41 -14 5 1 6 -2 3 -7 -3 -5 6 -20 20 -33 14 -13 32 -39 39 -56 9 -22 21 -33 34 -33 12 0 21 -4 21 -10 0 -5 -7 -7 -16 -3 -14 5 -16 0 -12 -30 2 -20 -1 -38 -7 -40 -14 -6 -38 20 -25 28 13 8 13 52 1 60 -5 3 -12 18 -16 34 -7 32 -49 75 -82 86 -19 5 -23 2 -23 -14 0 -14 6 -21 19 -21 11 0 23 -4 26 -10 3 -6 -1 -7 -9 -4 -11 4 -16 0 -16 -15 0 -13 6 -21 18 -21 11 0 13 -3 6 -8 -7 -4 -14 -16 -16 -27 -4 -17 -7 -16 -18 10 -7 17 -14 43 -16 59 -4 31 -34 62 -73 77 -35 14 -37 3 -5 -26 l29 -26 -28 6 c-24 5 -28 3 -25 -12 2 -10 14 -19 28 -21 39 -6 42 -17 5 -19 -30 -1 -35 2 -45 32 -11 33 -40 53 -59 41 -5 -4 -22 -1 -37 6 -22 10 -28 10 -32 0 -2 -6 -10 -12 -18 -12 -20 0 -18 -5 14 -37 24 -24 25 -28 9 -31 -10 -2 -26 7 -38 22 -24 31 -43 34 -36 6 7 -25 -5 -26 -28 0 -10 11 -21 17 -26 15 -4 -3 -10 -2 -13 3 -2 4 7 9 21 10 15 1 28 4 30 6 2 2 0 28 -5 58 -8 49 -7 54 9 53 10 -1 26 -8 36 -17z m1571 -258 c10 0 23 -4 31 -9 11 -7 11 -12 0 -32 -14 -24 -16 -30 -18 -61 -1 -21 -31 -13 -31 9 0 17 -31 14 -38 -4 -2 -8 5 -13 16 -13 11 0 23 -7 26 -16 7 -17 -17 -58 -27 -48 -4 4 -9 -1 -13 -10 -8 -21 -29 -6 -51 38 -9 17 -12 28 -8 24 5 -4 14 0 22 10 13 15 13 15 3 -5 -11 -23 4 -63 23 -63 4 0 5 5 1 12 -4 7 -3 8 4 4 7 -4 12 -3 12 3 0 5 -4 13 -10 16 -5 3 -10 14 -10 24 0 10 -6 24 -14 30 -8 7 -12 21 -9 31 3 11 -1 28 -8 37 -10 12 -10 14 -1 9 6 -4 12 -3 12 2 0 6 8 8 18 5 10 -2 25 3 32 12 9 11 16 13 18 6 2 -6 11 -11 20 -11z m-478 -3 c0 -19 47 -60 59 -52 6 3 8 12 5 18 -4 7 -3 8 1 4 13 -11 15 -38 3 -31 -7 5 -8 2 -4 -5 5 -7 14 -10 22 -7 8 3 11 0 8 -8 -3 -7 3 -19 12 -27 12 -9 15 -10 10 -1 -4 7 -2 12 4 12 7 0 10 -6 7 -14 -7 -17 13 -76 25 -76 12 0 10 34 -3 47 -6 6 9 4 35 -4 36 -12 46 -20 46 -37 0 -37 -12 -66 -27 -66 -10 0 -12 6 -8 20 4 11 2 20 -4 20 -6 0 -11 -4 -11 -10 0 -19 -28 -10 -33 10 -6 22 -27 28 -27 7 0 -17 36 -47 56 -47 11 0 14 -5 9 -17 -4 -10 -8 -25 -10 -33 -2 -8 -4 -17 -5 -20 -1 -3 -2 -8 -1 -12 0 -5 -3 -8 -9 -8 -10 0 -8 35 3 46 3 4 -13 27 -38 51 -51 52 -82 110 -67 125 7 7 10 6 9 -3 -1 -20 26 -79 36 -79 5 0 6 12 3 28 -12 51 -29 83 -41 78 -7 -2 -18 6 -25 20 -7 13 -21 26 -32 30 -10 3 -18 14 -18 24 0 10 -6 21 -12 23 -8 3 -6 6 5 6 9 1 17 -5 17 -12z m-181 -64 c-3 -19 2 -33 17 -47 18 -18 34 -21 34 -5 0 5 -6 7 -12 3 -7 -4 -10 -3 -5 1 4 5 -1 18 -10 29 l-18 21 23 -20 c26 -22 52 -63 33 -51 -6 4 -11 2 -11 -3 0 -6 5 -11 10 -11 6 0 10 -7 10 -15 0 -8 4 -15 8 -15 4 0 12 -13 18 -29 9 -22 19 -30 45 -33 38 -6 51 6 46 39 -3 14 2 23 14 26 21 6 32 -17 23 -45 -3 -10 -1 -25 6 -33 8 -9 8 -15 0 -20 -6 -4 -9 -1 -8 6 2 6 -3 14 -9 16 -7 3 -13 -2 -13 -10 0 -17 27 -30 42 -20 7 4 8 1 3 -7 -4 -7 -2 -16 5 -20 7 -4 11 -13 9 -19 -3 -8 -13 -4 -27 10 -13 11 -26 18 -30 14 -3 -3 -2 -9 4 -13 6 -4 13 -15 17 -25 4 -10 10 -16 15 -13 4 2 9 -7 10 -20 1 -15 -2 -22 -8 -19 -6 3 -10 12 -10 18 0 21 -41 49 -62 44 -12 -4 -29 2 -41 13 -20 19 -37 18 -37 -1 0 -5 8 -13 18 -16 22 -8 32 -23 31 -48 0 -16 -3 -14 -11 8 -5 15 -16 27 -24 27 -7 0 -20 13 -29 29 -19 39 -32 46 -52 29 -14 -11 -16 -11 -8 1 12 20 16 83 5 76 -6 -3 -7 1 -4 9 3 9 13 16 21 16 17 0 13 22 -5 28 -7 2 -12 -3 -12 -12 0 -9 -4 -16 -10 -16 -5 0 -10 -7 -10 -15 0 -24 -13 -18 -43 20 -15 19 -34 35 -41 35 -8 0 -16 8 -19 18 -2 9 -8 26 -12 37 -6 16 -5 17 4 5 7 -10 14 -11 19 -5 4 6 25 16 47 22 22 6 41 11 43 12 1 0 1 -2 1 -6z m469 -103 c16 0 92 -75 92 -91 0 -13 -18 -11 -23 4 -3 8 -9 6 -20 -8 -14 -19 -16 -19 -22 -2 -10 23 -28 22 -20 -2 3 -11 0 -23 -6 -27 -8 -4 -9 -3 -5 4 4 7 1 12 -8 12 -9 0 -16 5 -16 10 0 21 -18 9 -24 -16 -5 -17 0 -33 14 -51 18 -23 28 -73 15 -73 -14 0 -43 35 -38 46 3 8 0 14 -6 14 -6 0 -11 9 -11 20 0 11 -4 20 -10 20 -18 0 -11 22 9 27 14 3 24 23 37 71 10 36 20 60 22 54 2 -7 11 -12 20 -12z"/> <path d="M9112 7246 c2 -86 6 -106 19 -109 12 -3 18 -23 24 -73 12 -110 14 -206 5 -248 -8 -38 -6 -48 28 -126 9 -19 18 -62 20 -95 2 -33 8 -64 11 -70 4 -5 9 -67 10 -137 2 -71 8 -149 15 -176 9 -32 10 -52 3 -63 -11 -18 -3 -49 12 -49 13 0 25 45 23 85 -1 17 -3 80 -5 140 -1 61 -6 120 -11 132 -7 19 -4 24 19 33 19 7 25 15 21 26 -3 9 -6 31 -6 50 0 20 -8 42 -19 53 -23 23 -36 63 -51 155 -6 38 -17 81 -24 95 -7 14 -18 94 -25 176 -7 83 -19 162 -27 177 -8 15 -14 40 -14 55 0 38 -10 73 -22 73 -5 0 -7 -46 -6 -104z m108 -481 c15 -92 28 -133 51 -156 13 -13 19 -33 19 -63 0 -36 -4 -45 -21 -49 -22 -6 -22 -12 -3 -90 3 -15 3 -62 -1 -105 -11 -113 -23 -64 -24 95 -1 72 -5 134 -10 137 -4 3 -11 36 -13 73 -3 38 -16 91 -28 118 -17 41 -20 60 -15 105 7 52 7 53 20 30 8 -14 19 -56 25 -95z"/> <path d="M2695 7048 c-31 -17 -65 -49 -96 -92 -22 -30 -29 -50 -29 -86 0 -40 5 -51 36 -81 76 -73 117 -130 130 -182 7 -29 24 -97 38 -152 19 -73 26 -125 26 -195 0 -65 6 -114 19 -155 28 -89 79 -197 91 -190 5 3 7 0 4 -8 -6 -18 12 -32 21 -17 4 6 0 19 -8 28 -15 17 -53 104 -88 201 -14 41 -19 78 -18 155 1 56 -3 121 -9 146 -6 25 -14 79 -18 120 -4 41 -10 85 -15 97 -4 12 -49 65 -99 117 -49 52 -90 102 -90 111 0 38 72 126 127 154 30 15 87 14 130 -4 41 -18 53 -19 53 -5 0 5 -18 19 -40 30 -43 22 -132 27 -165 8z"/> <path d="M2934 5879 c-5 -9 19 -42 62 -84 53 -51 94 -118 114 -185 12 -41 33 -97 47 -123 13 -26 29 -74 34 -105 14 -73 47 -177 70 -216 9 -17 27 -64 39 -104 24 -78 69 -153 113 -185 31 -24 85 -27 98 -6 5 8 9 50 9 95 0 64 3 81 15 81 8 0 12 -4 10 -7 -7 -11 25 -100 36 -100 12 0 13 -4 -15 77 -13 38 -27 88 -31 111 -3 22 -13 46 -21 53 -8 6 -14 29 -14 51 0 41 -14 78 -30 78 -5 0 -13 -16 -19 -35 -7 -28 -5 -47 10 -90 10 -30 19 -62 19 -71 0 -10 5 -14 14 -11 15 6 33 -29 22 -40 -3 -4 -6 -1 -6 5 0 7 -4 12 -8 12 -5 0 -8 -41 -8 -91 1 -76 -2 -93 -16 -102 -14 -9 -23 -7 -45 9 -51 38 -86 94 -119 186 -17 51 -44 122 -59 158 -16 36 -31 96 -35 135 -6 51 -17 86 -41 129 -18 33 -42 94 -54 137 -20 71 -29 85 -101 163 -43 47 -79 86 -81 86 -1 0 -5 -5 -9 -11z"/> <path d="M6305 5453 c-22 -3 -44 -8 -50 -13 -5 -4 -30 -11 -54 -15 -43 -7 -101 -47 -101 -70 0 -6 -11 -22 -25 -35 -14 -13 -25 -29 -25 -37 0 -7 -7 -13 -15 -13 -8 0 -15 -6 -15 -14 0 -29 -137 -96 -162 -79 -7 4 -22 8 -33 8 -28 0 -35 19 -7 23 12 2 20 7 17 12 -3 5 -15 6 -28 1 -13 -5 -44 -7 -70 -4 -26 3 -47 2 -46 -3 1 -17 61 -58 67 -47 5 7 26 8 67 1 40 -6 67 -6 83 1 13 6 30 11 38 11 21 0 84 49 84 66 0 8 6 14 14 14 8 0 18 9 21 20 4 11 17 28 31 36 13 9 24 21 24 26 0 18 45 65 59 60 7 -2 25 1 39 8 15 7 37 17 49 23 12 5 28 7 36 4 9 -3 31 -1 50 5 28 9 39 7 60 -7 39 -25 33 -35 -18 -35 -32 0 -45 -4 -45 -14 0 -8 8 -17 18 -20 9 -3 -2 -4 -26 -2 -24 3 -51 11 -61 20 -28 25 -44 20 -36 -12 5 -24 2 -30 -20 -40 -14 -6 -25 -17 -25 -23 0 -7 21 -33 48 -58 l47 -46 -40 24 c-22 13 -44 28 -49 33 -18 15 -36 8 -36 -15 0 -13 9 -32 20 -42 11 -10 20 -25 19 -34 0 -12 -4 -10 -16 7 -19 27 -59 31 -48 5 11 -27 12 -57 3 -69 -9 -13 6 -94 24 -128 14 -25 40 -46 50 -40 13 8 9 24 -6 24 -11 0 -13 8 -9 33 4 25 -1 38 -19 58 -19 20 -23 36 -23 78 0 48 1 51 14 32 7 -12 20 -21 27 -21 21 0 17 47 -6 70 -31 31 -24 41 14 19 29 -17 34 -26 38 -69 6 -58 30 -100 60 -100 19 0 20 4 14 47 -3 26 -11 52 -16 57 -6 6 -10 20 -10 31 0 13 -16 34 -40 54 -22 17 -40 37 -40 44 0 23 60 47 116 47 40 0 54 4 54 14 0 8 -8 17 -17 19 -11 4 -9 5 7 5 57 -2 70 2 70 21 0 11 -10 27 -22 35 -22 16 -41 17 -123 9z"/> <path d="M5524 5151 c-25 -22 -46 -30 -93 -36 -34 -4 -61 -11 -61 -15 0 -4 8 -7 18 -5 9 2 39 7 65 10 33 4 58 16 81 36 19 16 39 29 45 29 16 0 48 -34 44 -47 -2 -5 3 -16 12 -23 12 -10 19 -9 39 3 16 11 26 13 34 5 7 -7 20 -7 44 1 32 10 31 9 -20 -37 -47 -42 -65 -72 -44 -72 4 0 8 -21 9 -46 1 -25 8 -53 15 -61 6 -8 12 -35 13 -61 0 -29 6 -47 14 -50 38 -13 53 -43 49 -98 -4 -41 -1 -54 9 -54 7 0 13 5 13 10 0 12 49 34 68 31 18 -3 15 26 -4 33 -16 6 -16 51 1 104 5 14 3 22 -5 22 -16 0 -40 -26 -40 -44 0 -8 -4 -18 -10 -21 -13 -8 -13 25 2 79 7 28 19 46 30 49 25 7 26 60 1 55 -11 -2 -19 -14 -21 -31 -2 -15 -8 -27 -13 -27 -6 0 -17 -7 -26 -15 -21 -21 -27 -13 -19 28 5 25 20 45 57 75 62 50 77 53 71 12 -4 -25 -1 -30 17 -30 22 0 47 -43 35 -61 -3 -6 -1 -15 4 -22 5 -7 15 -48 21 -91 9 -66 9 -83 -3 -101 -8 -13 -16 -47 -18 -76 -2 -45 -7 -56 -25 -64 -14 -6 -23 -18 -23 -32 0 -13 -4 -23 -10 -23 -5 0 -10 -8 -10 -18 0 -20 -38 -42 -70 -42 -11 0 -27 11 -36 25 -9 14 -25 25 -36 25 -12 0 -23 11 -29 30 -16 44 -43 40 -35 -4 4 -20 2 -37 -4 -41 -5 -3 -10 -17 -10 -31 0 -21 -4 -24 -40 -24 -40 0 -54 7 -88 43 -9 9 -29 17 -45 17 -29 0 -29 0 -23 -47 4 -27 14 -63 22 -81 15 -31 14 -35 -3 -47 -16 -12 -19 -11 -26 10 -7 21 -34 41 -44 32 -6 -7 19 -57 29 -57 4 0 8 -7 8 -15 0 -17 -25 -20 -35 -5 -11 17 -35 11 -44 -11 -7 -20 -8 -20 -20 10 -8 17 -17 31 -22 31 -9 0 -18 18 -33 68 -6 16 -3 22 8 22 9 0 16 4 16 9 0 5 3 16 6 25 7 19 -22 22 -29 4 -3 -7 -5 23 -4 67 1 87 -8 129 -26 119 -7 -3 -4 1 6 9 20 16 24 81 5 75 -19 -7 -26 -47 -21 -105 5 -48 4 -53 -14 -53 -15 0 -22 -8 -26 -27 -3 -16 -2 -30 1 -33 8 -6 32 -47 32 -55 0 -8 -44 19 -53 33 -13 21 -27 13 -28 -15 -1 -17 -3 -21 -6 -10 -6 24 -22 21 -33 -5 -5 -13 -9 -17 -9 -10 -1 6 -5 12 -11 12 -26 0 0 -101 33 -128 25 -21 60 -6 54 24 -6 32 5 30 20 -3 11 -22 10 -29 -2 -43 -7 -8 -17 -46 -21 -83 -5 -54 -9 -65 -20 -56 -7 6 -18 8 -24 4 -14 -8 -13 -42 1 -47 8 -3 6 -10 -5 -20 -20 -21 -22 -87 -1 -94 11 -5 13 -16 8 -50 -7 -53 11 -60 31 -13 12 29 66 68 66 48 0 -15 27 -10 34 6 3 8 15 15 26 15 11 0 32 7 46 16 13 9 28 14 32 10 3 -4 0 -11 -7 -16 -26 -15 -4 -40 34 -38 43 2 47 18 4 18 -26 0 -30 2 -19 15 13 16 6 35 -15 35 -8 0 -29 -6 -47 -14 -59 -26 -72 -29 -110 -28 -24 1 -38 -3 -38 -11 -1 -7 -7 -25 -14 -42 -13 -28 -13 -26 -8 33 4 53 2 62 -12 62 -20 0 -21 26 -1 34 18 7 20 37 3 55 -11 10 -8 11 13 6 27 -7 27 -6 34 64 4 40 13 75 21 82 8 6 14 17 14 23 0 21 -25 66 -36 66 -12 0 -29 79 -19 88 3 3 5 -2 5 -12 0 -9 6 -16 13 -15 6 1 21 -2 31 -6 14 -6 23 -3 32 10 13 17 14 16 14 -17 0 -45 18 -98 41 -120 9 -10 20 -26 24 -38 7 -23 35 -27 35 -5 0 19 17 19 54 0 49 -26 71 -18 41 15 -14 15 -13 18 10 30 28 15 31 33 12 71 -8 14 -17 44 -21 67 -8 51 6 55 53 13 17 -16 45 -31 60 -34 35 -7 101 2 101 14 0 5 -4 9 -10 9 -10 0 -3 27 13 48 7 9 13 9 23 1 7 -6 17 -8 22 -5 6 3 17 -5 26 -19 28 -42 126 -30 126 15 0 11 5 20 10 20 6 0 10 10 10 23 0 14 9 26 23 32 18 8 23 19 25 64 2 29 10 63 17 75 15 23 18 133 3 142 -4 3 -8 14 -8 24 0 11 -5 42 -11 70 -8 39 -17 54 -35 62 -18 8 -23 17 -18 31 5 17 -8 36 -26 37 -15 0 -115 -93 -125 -117 -13 -30 -8 -103 6 -103 5 0 9 5 9 10 0 6 10 20 22 32 19 19 20 19 13 2 -5 -10 -9 -41 -10 -69 0 -38 4 -50 15 -50 9 0 16 11 18 28 7 55 17 25 12 -35 -4 -47 -9 -62 -19 -60 -8 2 -18 -3 -22 -10 -5 -8 -9 6 -9 35 0 46 -18 78 -50 89 -8 2 -14 23 -14 55 -1 27 -6 56 -12 64 -6 8 -14 26 -18 41 -5 21 -2 30 14 38 26 14 26 30 -1 30 -18 0 -14 7 25 41 62 55 63 83 2 59 -21 -7 -26 -6 -26 5 0 19 -24 19 -44 0 -8 -8 -19 -15 -25 -15 -6 0 -11 7 -11 15 0 23 -37 55 -62 55 -13 0 -37 -13 -54 -29z"/> <path d="M6246 5034 c-3 -9 -6 -31 -6 -49 0 -19 -4 -37 -10 -40 -5 -3 -10 -13 -10 -21 0 -14 5 -22 40 -63 8 -10 20 -26 26 -36 15 -27 34 -30 34 -7 0 12 9 23 21 27 15 5 19 12 15 28 -3 12 -6 25 -6 30 0 4 -7 7 -15 7 -8 0 -15 5 -15 10 0 6 -6 10 -14 10 -17 0 -26 22 -26 60 0 33 -9 60 -20 60 -4 0 -11 -7 -14 -16z"/> <path d="M5383 4975 c-51 -19 -61 -21 -56 -8 4 11 2 14 -8 11 -8 -3 -13 -13 -13 -22 1 -12 -3 -15 -16 -11 -23 7 -47 -30 -53 -81 -7 -54 -16 -74 -50 -109 -19 -20 -31 -26 -34 -17 -6 15 -20 16 -36 2 -59 -50 -142 -94 -202 -107 -29 -6 -44 -16 -58 -41 -11 -18 -17 -36 -13 -39 3 -3 10 6 15 21 6 14 13 26 15 26 7 0 -4 -31 -15 -46 -5 -6 -5 -15 -1 -20 4 -4 -1 -2 -11 6 -16 12 -20 12 -28 -1 -5 -8 -9 -29 -9 -47 0 -18 -11 -50 -25 -72 -14 -22 -25 -43 -25 -48 0 -5 -11 -18 -25 -30 -14 -13 -23 -27 -20 -33 4 -5 1 -8 -7 -7 -7 2 -12 -4 -10 -12 2 -8 0 -12 -4 -7 -4 4 -16 0 -26 -10 -22 -20 -24 -63 -3 -63 8 0 15 -7 15 -15 0 -8 -6 -12 -13 -10 -22 9 -37 -31 -30 -80 5 -40 9 -46 27 -43 13 2 20 10 20 20 -1 10 2 15 7 12 5 -3 13 5 18 18 l10 23 0 -22 c1 -13 6 -23 11 -23 6 0 10 -5 10 -11 0 -6 -9 -8 -20 -4 -16 5 -20 2 -20 -14 0 -17 -5 -20 -29 -15 -22 5 -34 1 -51 -16 -17 -17 -24 -19 -36 -9 -11 9 -21 6 -48 -15 -26 -19 -42 -24 -64 -20 -23 5 -36 0 -64 -25 -20 -17 -39 -31 -43 -31 -4 0 -5 20 -3 45 6 50 3 52 -46 29 -34 -17 -66 -73 -66 -116 0 -10 -9 -22 -20 -28 -11 -6 -20 -17 -20 -24 0 -17 -16 -23 -78 -32 -64 -8 -79 8 -61 63 7 21 13 80 13 132 1 101 -7 117 -42 84 -21 -20 -47 -29 -37 -13 4 6 2 17 -4 24 -9 11 -12 54 -10 145 1 37 -16 47 -46 27 -26 -17 -28 -17 -47 4 -14 15 -19 30 -14 50 5 28 4 28 -28 23 -44 -7 -61 20 -52 82 6 34 2 50 -14 76 -11 19 -20 44 -20 56 0 37 -11 53 -36 53 -18 0 -29 11 -48 48 -30 60 -86 223 -86 251 0 11 -5 21 -11 21 -15 0 -3 -96 22 -167 10 -31 19 -64 19 -75 0 -10 4 -18 9 -18 8 0 64 -162 65 -190 1 -9 10 -15 24 -14 15 0 22 -5 22 -18 0 -10 4 -18 10 -18 5 0 7 -13 4 -30 -4 -19 -2 -30 5 -30 7 0 9 -9 5 -25 -3 -14 -2 -25 3 -25 5 0 16 -11 23 -25 7 -14 20 -25 27 -25 8 0 11 -5 8 -11 -4 -6 -13 -8 -21 -5 -17 7 -44 -3 -44 -16 0 -5 10 -6 21 -3 19 6 21 4 15 -16 -17 -54 -28 -111 -23 -116 10 -9 27 8 27 26 0 21 39 75 48 67 3 -3 -2 -14 -10 -23 -19 -22 -30 -100 -16 -109 6 -4 19 4 29 17 10 13 19 19 19 13 0 -7 9 -14 20 -17 15 -4 20 -14 21 -44 1 -21 1 -44 0 -51 -3 -18 19 -82 27 -82 4 0 13 14 21 31 11 26 11 33 0 39 -10 7 -10 11 0 24 7 9 16 14 20 11 12 -7 4 -67 -11 -77 -10 -7 -10 -11 0 -15 6 -2 12 -16 12 -29 0 -27 15 -32 24 -8 12 32 24 3 15 -37 -6 -25 -6 -61 0 -92 5 -28 6 -57 3 -65 -4 -12 1 -14 23 -8 41 10 69 50 43 58 -7 3 3 12 21 21 19 10 37 14 40 11 3 -4 0 -9 -6 -11 -7 -3 -13 -11 -13 -18 0 -7 -7 -15 -15 -19 -9 -3 -15 -18 -15 -36 0 -23 4 -30 20 -30 17 0 20 -7 20 -40 0 -27 4 -40 13 -40 9 0 12 -10 9 -30 -2 -17 -10 -30 -18 -30 -19 0 -18 -29 1 -36 22 -9 38 5 24 22 -16 19 -4 18 15 -2 22 -21 36 -9 32 26 -2 20 1 30 10 30 8 0 14 5 14 10 0 6 -7 10 -15 10 -8 0 -15 7 -15 15 0 8 -9 20 -20 27 -11 7 -20 16 -20 19 0 4 9 9 20 12 15 4 20 0 20 -14 0 -10 9 -23 20 -29 11 -6 20 -18 20 -26 0 -10 6 -14 15 -10 8 3 15 1 15 -4 0 -6 -7 -10 -15 -10 -8 0 -15 -7 -15 -15 0 -8 5 -15 10 -15 6 0 10 -14 10 -31 0 -22 5 -32 19 -36 11 -3 17 -11 15 -18 -3 -7 -1 -16 5 -20 6 -3 11 -18 10 -33 0 -15 -3 -20 -6 -12 -10 31 -27 60 -35 60 -15 0 -8 -54 10 -85 12 -19 21 -61 26 -112 8 -105 16 -143 28 -143 6 0 8 20 6 45 -2 25 0 45 5 45 4 0 5 19 2 43 -3 23 -2 35 2 27 3 -8 12 -21 20 -28 7 -8 11 -23 8 -33 -5 -14 -1 -19 13 -19 11 0 22 6 25 13 3 10 9 10 26 0 27 -17 41 -16 41 0 0 8 -18 21 -40 29 -37 15 -39 18 -38 60 1 62 6 76 31 80 17 2 23 11 25 37 2 19 -2 37 -8 41 -7 4 -1 13 16 25 26 17 27 17 19 -1 -4 -11 -9 -40 -10 -66 -3 -48 8 -61 31 -38 6 6 10 4 10 -8 0 -14 -7 -17 -33 -14 -42 5 -47 -23 -5 -31 15 -3 34 -8 43 -12 13 -5 18 3 23 44 4 28 10 51 15 51 4 0 13 30 21 68 16 81 19 92 32 92 5 0 6 -9 3 -21 -6 -17 -4 -20 12 -15 15 5 18 0 20 -26 1 -17 9 -39 18 -48 9 -10 13 -24 9 -35 -6 -14 -4 -16 7 -11 8 4 5 0 -5 -8 -11 -9 -17 -19 -13 -22 4 -4 15 3 26 14 10 12 23 22 28 22 17 0 53 37 53 54 0 22 -20 21 -20 -1 -1 -14 -6 -11 -25 12 -27 32 -32 74 -13 104 10 16 14 17 25 5 8 -8 25 -14 39 -14 19 0 24 5 24 25 0 14 -4 25 -10 25 -5 0 -10 -6 -10 -14 0 -18 -27 -29 -36 -14 -4 7 -3 8 4 4 8 -5 11 2 8 21 -6 49 -18 83 -28 83 -6 0 -8 -10 -4 -22 3 -13 6 -29 6 -36 0 -7 5 -10 10 -7 6 3 10 4 10 1 0 -3 -9 -10 -21 -17 -19 -10 -20 -8 -14 10 7 22 -23 100 -39 101 -4 0 -5 -16 -2 -35 11 -55 9 -146 -3 -158 -7 -7 -9 4 -4 41 5 44 3 52 -11 52 -9 0 -16 -6 -16 -12 0 -7 -3 -24 -6 -38 -6 -24 -6 -25 9 -5 20 25 22 7 2 -19 -13 -18 -14 -17 -21 8 -3 14 -12 26 -19 26 -8 0 -17 6 -21 13 -4 6 -4 9 1 5 4 -4 14 0 22 10 8 9 12 11 8 5 -3 -7 -1 -13 4 -13 14 0 14 12 0 85 -9 50 -8 60 5 67 23 13 20 45 -5 51 -18 5 -19 9 -9 27 6 12 10 31 8 43 -1 12 0 27 3 32 4 6 9 27 13 48 5 28 3 39 -8 43 -23 9 -16 42 8 36 14 -4 17 -2 11 9 -8 12 -6 12 8 0 18 -14 22 -22 10 -20 -19 3 -33 -2 -33 -11 0 -6 10 -8 24 -4 31 7 36 -2 26 -51 -4 -22 -8 -34 -9 -27 0 6 -6 12 -12 12 -6 0 -9 -21 -7 -52 2 -39 7 -53 18 -53 8 0 15 10 16 22 1 12 4 30 8 40 4 10 11 51 16 92 5 42 14 77 21 82 10 6 11 17 3 46 -9 33 -7 41 9 58 18 20 19 19 11 -19 -5 -31 -4 -38 7 -34 8 3 15 14 17 26 2 11 10 26 18 32 8 7 14 22 14 34 0 37 12 66 26 66 8 0 15 10 15 23 3 42 5 52 13 87 5 19 13 41 19 48 7 9 7 16 0 20 -14 10 -23 51 -12 58 5 3 9 -2 9 -10 0 -22 21 -20 27 2 5 20 11 25 93 77 30 19 60 39 67 45 7 5 15 10 19 10 4 0 12 6 18 14 12 14 66 31 66 20 0 -4 -12 -18 -26 -31 -25 -23 -26 -25 -8 -38 29 -22 41 -18 58 17 21 40 20 58 -1 58 -17 1 -17 1 0 11 12 7 16 17 11 31 -6 19 -3 20 29 14 48 -9 67 1 66 33 -1 14 2 34 6 44 5 12 2 17 -10 17 -14 0 -13 4 6 19 17 13 26 16 31 8 4 -6 10 -8 15 -4 4 5 1 12 -6 16 -10 7 -8 15 10 37 52 62 77 84 93 84 9 0 16 5 16 10 0 16 -30 11 -97 -15z m-1540 -655 c7 0 17 4 23 10 7 7 9 -2 6 -25 -3 -21 0 -35 7 -35 6 0 11 -7 11 -15 0 -12 10 -15 38 -13 20 1 40 7 45 12 4 6 6 -13 5 -41 -2 -34 -7 -53 -15 -53 -7 0 -13 -7 -13 -16 0 -10 6 -14 15 -10 11 4 15 -2 17 -22 2 -52 -4 -87 -20 -105 -21 -23 -32 -6 -32 52 0 38 -2 43 -19 38 -12 -3 -22 1 -25 9 -8 21 -21 17 -34 -8 -10 -21 -11 -20 -11 13 -1 21 5 42 14 49 8 7 15 21 15 31 0 28 -34 24 -50 -6 -7 -14 -15 -24 -17 -22 -6 6 22 72 35 80 16 11 16 37 -1 37 -8 0 -20 11 -27 25 -7 14 -17 25 -21 25 -5 0 -6 6 -3 14 5 12 9 11 25 -5 10 -10 25 -19 32 -19z m774 -335 c-6 -19 -16 -35 -24 -35 -12 0 -19 -50 -14 -107 1 -13 -3 -23 -9 -23 -5 0 -10 -13 -10 -30 0 -16 4 -30 8 -30 10 0 32 68 32 98 0 12 9 36 20 54 11 19 20 26 20 17 0 -9 -3 -19 -7 -23 -5 -4 -9 -22 -10 -39 -1 -18 -4 -48 -7 -66 -2 -19 1 -67 8 -107 9 -51 10 -71 2 -68 -6 2 -17 0 -25 -5 -18 -12 -6 -61 15 -61 14 0 14 -2 0 -16 -9 -8 -16 -26 -16 -39 0 -35 -23 -22 -39 20 -7 19 -9 44 -6 56 6 17 3 20 -12 17 -12 -2 -19 -14 -21 -36 -2 -17 -6 -32 -10 -32 -10 0 -6 99 3 108 5 4 5 1 1 -5 -5 -9 -1 -13 11 -13 28 0 54 57 45 99 -9 41 -38 58 -30 18 3 -15 1 -24 -3 -21 -5 3 -9 0 -9 -5 0 -6 3 -11 8 -11 4 0 7 -13 7 -29 0 -23 -3 -27 -13 -18 -11 8 -18 5 -33 -13 -10 -14 -19 -31 -19 -37 0 -13 -12 -17 -37 -14 -7 1 -13 -3 -13 -9 0 -6 4 -9 9 -5 5 3 12 2 15 -3 2 -4 -7 -9 -22 -10 -27 -2 -42 -17 -41 -42 0 -9 6 -5 14 10 14 25 14 25 15 3 0 -13 -4 -23 -10 -23 -5 0 -6 -8 -3 -17 5 -11 0 -10 -16 6 -18 18 -22 30 -16 57 7 38 7 38 -29 24 -14 -5 -26 -17 -26 -26 0 -10 6 -14 14 -11 12 5 12 2 1 -21 -8 -15 -17 -36 -20 -46 -4 -14 -9 -16 -17 -8 -8 8 -8 26 1 68 11 47 11 58 0 65 -8 5 -19 7 -26 5 -6 -3 -19 2 -30 9 -14 12 -15 16 -5 23 17 12 44 63 36 71 -3 3 -14 -5 -24 -19 -17 -22 -19 -23 -26 -7 -4 11 0 25 10 36 20 22 20 31 0 31 -11 0 -14 -5 -10 -17 6 -16 5 -16 -8 -3 -12 13 -13 22 -2 64 7 26 20 52 29 58 9 5 17 20 17 33 0 27 14 39 36 31 13 -5 13 -10 -4 -33 -22 -32 -38 -113 -22 -113 5 0 10 -7 10 -15 0 -8 7 -15 15 -15 8 0 15 7 15 15 0 8 5 15 10 15 6 0 10 -4 10 -10 0 -5 5 -10 11 -10 5 0 8 4 4 9 -3 5 0 13 6 17 8 5 9 3 4 -6 -5 -9 -4 -11 3 -6 17 10 15 29 -3 23 -8 -4 -17 -2 -20 3 -9 15 -25 12 -25 -5 0 -8 -4 -15 -10 -15 -5 0 -10 5 -10 10 0 13 22 52 35 63 7 6 6 10 -1 13 -8 3 -8 16 0 46 9 32 8 42 -2 46 -6 2 -9 8 -6 14 4 6 0 15 -7 20 -11 8 -11 9 2 5 9 -3 21 -1 26 4 5 5 7 -4 5 -25 -3 -27 1 -37 16 -45 17 -9 26 -5 56 25 26 26 41 34 55 29 30 -9 91 5 91 21 0 17 17 18 23 2 3 -10 10 -8 23 5 24 22 24 23 11 -18z"/> <path d="M5659 4728 c-1 -18 -3 -25 -6 -15 -2 9 -11 17 -19 17 -24 0 -19 -86 6 -107 12 -10 33 -30 48 -45 25 -26 52 -37 52 -20 -1 4 -9 32 -19 62 -17 48 -18 57 -5 81 19 37 9 59 -27 59 -26 0 -29 -4 -30 -32z"/> <path d="M9410 4724 c0 -55 20 -111 44 -122 11 -6 47 -16 78 -22 42 -8 72 -23 109 -51 85 -68 78 -91 -28 -96 -38 -1 -93 2 -123 7 -30 6 -56 6 -58 2 -1 -5 -14 -7 -27 -4 -26 4 -32 -9 -19 -42 7 -17 34 -22 34 -6 0 6 9 10 20 10 11 0 20 -4 20 -9 0 -5 18 -11 40 -15 43 -7 61 -28 61 -74 0 -48 -4 -60 -18 -55 -16 6 -17 -2 0 -27 10 -17 9 -22 -2 -29 -20 -13 -7 -38 21 -39 13 0 57 -8 98 -17 41 -8 124 -21 184 -27 81 -8 121 -17 154 -34 25 -13 52 -24 61 -24 9 0 -13 -12 -48 -26 -49 -21 -65 -24 -71 -14 -4 7 -15 10 -24 7 -8 -3 -18 -2 -21 3 -4 6 -26 10 -50 10 -51 0 -60 -14 -45 -71 12 -42 6 -62 -29 -93 -12 -11 -21 -25 -21 -33 0 -22 61 -93 80 -93 9 0 24 -6 33 -12 15 -12 15 -16 -3 -55 -13 -30 -25 -43 -39 -43 -37 0 -76 21 -112 61 -19 21 -40 39 -46 39 -5 0 -22 11 -38 26 -15 14 -29 23 -32 20 -3 -2 -18 11 -35 30 -17 19 -38 34 -48 34 -10 0 -20 7 -24 15 -3 8 -12 15 -21 15 -11 0 -15 -12 -15 -50 0 -39 -3 -48 -15 -44 -9 4 -15 24 -17 62 -2 43 -7 57 -18 57 -10 0 -16 -13 -18 -42 -4 -51 -17 -56 -26 -11 -4 18 -17 42 -31 53 -25 21 -37 78 -21 103 8 14 -18 62 -34 62 -6 0 -10 -15 -10 -34 0 -19 -4 -36 -9 -38 -12 -4 -34 -147 -33 -209 1 -34 -3 -49 -14 -53 -11 -4 -14 -14 -10 -33 3 -16 2 -35 -4 -43 -8 -12 -10 -12 -10 -1 0 8 -8 20 -17 28 -10 8 -12 12 -5 8 6 -3 12 -1 12 5 0 7 -6 10 -12 7 -8 -2 -13 -23 -13 -55 0 -27 -3 -54 -7 -58 -5 -4 -8 2 -8 14 0 12 -4 22 -10 22 -5 0 -10 -13 -10 -30 0 -16 5 -30 10 -30 6 0 10 -8 10 -18 0 -24 21 -44 34 -33 8 6 12 -3 13 -27 1 -28 -1 -32 -7 -17 -4 12 -15 27 -24 34 -13 11 -17 11 -21 -1 -3 -8 -5 -19 -3 -24 1 -5 -3 -18 -9 -29 -6 -11 -13 -45 -17 -75 -8 -68 -17 -83 -41 -74 -18 7 -18 8 0 14 15 5 19 20 22 83 4 71 2 77 -15 77 -22 0 -34 -22 -26 -44 3 -8 -2 -30 -11 -50 -9 -19 -14 -40 -10 -46 3 -5 -1 -13 -9 -16 -9 -3 -16 -16 -16 -28 0 -11 -7 -34 -15 -50 -8 -15 -15 -32 -15 -37 0 -17 28 -9 44 14 13 17 16 18 12 4 -3 -10 -6 -25 -6 -33 0 -8 -7 -14 -15 -14 -8 0 -15 -8 -16 -17 0 -11 -3 -13 -6 -5 -7 17 -23 15 -23 -3 0 -8 -7 -15 -15 -15 -10 0 -15 -10 -15 -29 0 -25 4 -29 33 -34 34 -5 67 14 67 40 0 8 7 21 15 29 8 9 15 11 15 5 0 -5 -4 -13 -10 -16 -5 -3 -10 -15 -10 -26 0 -21 -54 -81 -83 -92 -11 -4 -16 -3 -12 3 3 6 13 10 21 10 8 0 14 7 14 15 0 8 -5 15 -11 15 -5 0 -7 -5 -3 -12 4 -7 3 -8 -5 -4 -6 4 -9 12 -6 17 4 5 -3 9 -13 9 -16 0 -21 -9 -27 -47 -3 -27 -15 -65 -26 -86 -23 -45 -24 -58 -4 -50 9 3 14 11 12 17 -2 6 4 23 14 38 11 14 16 33 13 42 -5 12 1 16 24 16 21 0 37 8 50 25 11 14 23 25 26 25 3 0 6 -11 6 -25 0 -14 5 -25 10 -25 6 0 10 24 10 53 1 28 7 63 15 77 19 33 19 70 0 70 -8 0 -15 -7 -15 -15 0 -8 -4 -15 -10 -15 -5 0 -10 8 -10 18 0 20 20 54 20 35 0 -28 18 -11 23 22 3 19 12 42 21 50 8 8 18 41 21 72 4 32 14 68 22 81 8 13 12 31 9 39 -6 14 -4 14 10 2 11 -9 14 -23 11 -45 -6 -37 1 -74 14 -74 5 0 9 11 9 24 0 14 7 32 17 41 10 10 12 19 6 23 -14 10 -23 51 -12 58 19 11 8 26 -17 21 -30 -5 -43 16 -26 44 7 10 12 36 13 56 0 33 1 35 9 16 5 -13 13 -23 18 -23 12 0 35 78 27 90 -3 6 -1 10 6 10 8 0 10 15 7 48 -3 26 -3 41 -1 35 6 -18 23 -16 23 2 0 8 -4 15 -9 15 -9 0 -4 71 9 130 5 23 8 27 9 13 1 -27 18 -31 24 -5 3 9 5 -1 6 -22 1 -24 8 -44 18 -51 20 -15 28 -121 11 -142 -8 -10 -8 -20 1 -37 10 -18 27 -26 82 -35 37 -7 73 -10 79 -6 17 11 11 25 -11 25 -20 0 -21 3 -15 48 4 26 8 57 8 70 0 34 40 29 75 -10 16 -18 51 -44 77 -58 26 -14 64 -42 85 -62 43 -43 104 -72 132 -63 21 7 59 73 59 103 0 13 -12 22 -39 31 -28 8 -45 22 -60 47 l-21 35 26 34 c27 35 30 56 19 111 -6 26 -3 32 14 37 19 5 83 -12 97 -26 4 -4 14 -7 23 -7 24 0 131 53 131 65 0 6 -28 23 -62 39 -51 23 -80 30 -153 33 -49 2 -110 10 -135 18 -25 7 -66 16 -92 20 -27 3 -48 11 -48 17 0 6 -11 8 -27 4 -16 -3 -22 -3 -15 0 6 3 12 17 12 30 0 13 4 24 10 24 10 0 7 105 -4 130 -4 10 2 25 14 38 16 17 25 20 40 12 13 -7 26 -6 47 5 15 8 36 15 46 15 45 0 -4 73 -86 128 -20 14 -65 30 -99 36 -71 13 -96 38 -105 104 -5 38 -4 41 22 48 16 4 52 0 88 -10 34 -10 78 -22 97 -26 19 -5 45 -12 58 -15 12 -4 42 -21 66 -40 24 -18 54 -38 67 -45 13 -7 38 -26 55 -44 18 -17 44 -39 58 -49 15 -10 45 -41 67 -69 21 -28 52 -60 68 -72 86 -62 183 -141 233 -188 31 -29 69 -64 85 -78 60 -54 111 -118 153 -190 24 -41 46 -77 50 -80 3 -3 22 -27 42 -53 20 -27 63 -65 95 -86 95 -63 179 -169 208 -264 17 -58 72 -168 98 -200 43 -51 157 -260 157 -288 0 -6 11 -30 25 -54 19 -32 35 -45 63 -53 181 -51 258 -76 317 -105 39 -19 87 -40 108 -47 22 -7 68 -32 103 -56 36 -25 93 -55 127 -68 81 -30 201 -91 257 -130 41 -28 75 -44 195 -94 22 -10 69 -34 105 -54 36 -20 78 -42 94 -48 17 -6 59 -33 95 -59 36 -27 77 -54 91 -61 96 -49 261 -223 317 -334 58 -115 75 -199 74 -371 0 -95 6 -187 16 -250 10 -61 16 -153 16 -236 -1 -126 -3 -139 -28 -188 -14 -29 -55 -81 -91 -116 -35 -35 -64 -70 -64 -78 0 -22 21 -36 107 -67 175 -64 349 -132 360 -142 21 -17 106 -39 116 -29 4 4 -10 11 -35 15 -24 4 -53 13 -65 21 -20 14 -188 80 -367 146 -121 44 -121 46 -44 121 36 35 78 88 94 118 28 54 29 58 28 210 0 90 -6 178 -13 210 -8 31 -15 135 -16 240 -6 301 -50 420 -223 596 -54 54 -117 110 -140 124 -24 14 -79 51 -124 83 -45 31 -86 57 -92 57 -6 0 -45 19 -86 43 -41 23 -93 50 -115 59 -120 50 -154 66 -195 94 -57 40 -199 111 -266 134 -28 10 -80 38 -116 63 -36 25 -83 50 -105 57 -21 7 -69 28 -108 47 -59 29 -136 54 -317 105 -29 8 -43 20 -63 55 -14 25 -25 49 -25 54 0 24 -124 256 -150 279 -20 19 -62 98 -89 170 -58 151 -130 244 -242 314 -25 16 -55 43 -67 61 -12 17 -30 40 -41 51 -10 11 -39 56 -65 100 -59 101 -231 277 -364 371 -25 19 -49 37 -52 42 -3 5 -22 20 -42 34 -21 14 -56 48 -77 75 -22 28 -57 63 -78 79 -21 15 -44 36 -51 46 -7 9 -30 26 -50 36 -20 10 -45 28 -55 39 -19 21 -68 43 -137 62 -25 7 -65 19 -89 26 -25 8 -66 14 -93 14 l-48 0 0 -36z"/> <path d="M8590 4638 c0 -6 8 -20 18 -31 9 -11 11 -17 5 -13 -9 5 -13 -1 -13 -19 0 -17 5 -25 13 -22 15 5 67 -71 60 -88 -4 -12 22 -74 36 -85 10 -7 38 -90 45 -132 4 -20 12 -38 18 -40 6 -2 13 -27 16 -56 6 -71 22 -66 22 8 0 41 -7 74 -20 99 -17 34 -17 41 -5 57 17 23 19 64 3 64 -6 0 -9 3 -5 6 3 4 20 -5 37 -20 17 -14 36 -26 41 -26 17 0 9 26 -15 49 -16 15 -22 29 -18 43 4 17 2 20 -11 15 -11 -4 -17 -1 -17 8 0 8 -4 15 -10 15 -5 0 -10 7 -10 15 0 8 5 15 10 15 6 0 10 7 10 15 0 25 -17 17 -39 -19 -24 -39 -27 -60 -7 -53 9 4 16 -3 20 -16 6 -25 7 -24 -24 -32 -23 -5 -27 -2 -40 32 -8 21 -13 42 -12 46 1 5 -12 39 -30 75 -39 80 -78 125 -78 90z"/> <path d="M6690 4480 c0 -5 -7 -10 -15 -10 -8 0 -15 -8 -16 -17 0 -11 -3 -13 -6 -5 -7 19 -22 15 -77 -21 -28 -19 -65 -39 -83 -45 -55 -19 -102 -81 -50 -69 41 10 124 43 148 58 38 24 107 49 137 49 43 0 72 11 72 26 0 21 -27 28 -54 16 -14 -6 -28 -7 -37 -1 -10 6 -10 9 -1 9 6 0 12 5 12 10 0 6 -7 10 -15 10 -8 0 -15 -4 -15 -10z"/> <path d="M7577 4454 c3 -9 13 -12 29 -8 17 5 24 2 24 -9 0 -8 6 -18 13 -20 10 -4 10 -6 0 -6 -7 -1 -13 -5 -13 -11 0 -5 18 -10 40 -10 34 0 46 -7 95 -54 30 -30 55 -59 55 -64 0 -6 11 -24 25 -40 21 -25 22 -31 9 -36 -8 -3 -12 -2 -9 4 3 6 1 10 -5 10 -30 0 1 -26 41 -34 24 -5 36 -11 27 -13 -10 -3 -18 -9 -18 -15 0 -5 7 -8 15 -5 8 4 17 1 21 -5 4 -7 3 -8 -4 -4 -7 4 -12 2 -12 -3 0 -6 -7 -11 -15 -11 -25 0 -17 -17 10 -24 29 -7 44 -34 26 -45 -7 -4 -37 -4 -67 2 -30 5 -58 7 -61 4 -9 -10 8 -27 28 -27 16 0 18 -5 13 -25 -9 -35 4 -95 20 -95 13 0 56 -33 56 -43 0 -3 -9 -3 -20 0 -12 3 -20 0 -20 -6 0 -7 5 -9 10 -6 17 10 11 -2 -7 -16 -10 -7 -15 -10 -11 -5 9 10 -19 66 -32 66 -16 0 -11 -47 6 -64 8 -9 19 -16 24 -16 5 0 15 -3 24 -6 11 -4 16 -1 16 10 0 9 7 16 16 16 11 0 14 -6 9 -21 -4 -13 -2 -25 5 -29 19 -11 4 -44 -16 -36 -12 5 -15 2 -10 -9 3 -9 2 -13 -4 -10 -6 3 -10 -3 -10 -14 0 -12 5 -21 10 -21 6 0 10 6 10 13 0 8 4 7 10 -3 5 -8 10 -22 10 -30 0 -13 -1 -13 -10 0 -13 21 -19 10 -13 -22 3 -18 12 -28 23 -28 10 0 26 -7 35 -16 9 -9 19 -13 23 -9 4 4 1 10 -5 12 -7 3 -13 11 -13 18 0 8 -7 18 -17 23 -14 9 -14 10 5 16 12 4 22 11 22 16 0 4 9 6 20 3 23 -6 27 15 8 36 -11 10 -9 11 7 5 18 -7 19 -6 5 11 -8 10 -10 16 -3 12 6 -4 14 -1 17 5 3 7 3 -2 0 -20 -3 -23 0 -34 11 -38 22 -9 25 -3 18 39 -4 26 -11 37 -23 37 -9 0 -25 9 -35 20 -10 11 -13 20 -7 20 6 0 18 8 27 17 14 14 20 14 37 4 17 -11 22 -10 29 1 13 20 11 35 -6 42 -8 3 -15 12 -15 21 0 8 -7 15 -15 15 -15 0 -19 11 -15 39 1 8 -7 22 -18 30 -22 18 -41 111 -23 111 6 0 11 -4 11 -10 0 -5 7 -10 15 -10 8 0 15 5 15 10 0 6 -6 10 -13 10 -7 0 -19 9 -27 20 -8 11 -22 20 -30 20 -9 0 -25 8 -36 18 -10 9 -30 23 -44 29 -18 9 -20 12 -7 12 9 1 17 7 16 14 -1 26 -36 71 -61 78 -14 3 -48 30 -77 58 -28 28 -58 51 -65 51 -8 0 -17 6 -19 13 -4 9 -8 8 -16 -3 -7 -9 -11 -10 -11 -3 0 6 5 15 10 18 18 11 11 27 -10 22 -10 -3 -21 0 -23 6 -2 6 -17 12 -34 13 -23 1 -30 -2 -26 -12z"/> <path d="M4916 4398 c-3 -13 -6 -33 -6 -45 0 -13 -4 -23 -10 -23 -5 0 -8 -22 -7 -50 1 -32 6 -50 15 -50 6 0 12 -12 12 -27 0 -43 12 -103 20 -103 4 0 15 24 24 53 l16 52 -6 -53 c-8 -74 20 -171 43 -148 4 3 1 18 -6 33 -10 21 -9 28 1 35 11 6 11 10 0 16 -14 10 -17 53 -7 95 6 21 4 27 -9 27 -12 0 -14 7 -9 30 5 26 3 30 -16 30 -18 0 -20 4 -15 28 4 15 11 37 15 50 13 33 11 42 -6 42 -8 0 -15 7 -15 15 0 24 -27 18 -34 -7z"/> <path d="M5819 4214 c-17 -21 -63 -44 -88 -44 -19 0 -38 -17 -28 -26 2 -3 33 0 68 7 35 6 89 13 119 14 65 3 202 37 207 52 4 10 -67 9 -173 -3 -42 -4 -63 -3 -68 5 -10 15 -21 14 -37 -5z"/> <path d="M8720 4185 c0 -8 -7 -15 -15 -15 -17 0 -21 -35 -5 -45 6 -3 10 -14 10 -23 0 -9 5 -24 10 -32 8 -12 12 -13 19 -2 6 10 17 -2 39 -43 33 -61 56 -124 27 -72 -12 21 -21 26 -36 22 -15 -5 -19 -2 -19 19 0 31 -9 56 -22 56 -5 0 -7 -18 -3 -43 5 -34 3 -48 -10 -60 -15 -15 -15 -20 -1 -47 8 -17 10 -28 5 -25 -5 4 -9 1 -9 -5 0 -30 26 1 34 41 5 24 11 36 13 26 3 -9 9 -15 14 -12 12 8 -2 -28 -15 -37 -8 -5 -8 -12 0 -25 20 -32 34 -26 35 14 l0 38 17 -42 c16 -43 32 -56 32 -28 0 8 4 15 9 15 10 0 4 69 -9 113 -6 16 -5 27 1 27 5 0 9 5 9 11 0 6 -7 9 -15 5 -8 -3 -15 -1 -15 3 0 5 -15 24 -32 43 -22 22 -32 41 -30 56 2 12 -1 22 -7 22 -6 0 -11 -7 -11 -16 0 -8 -4 -12 -10 -9 -5 3 -10 17 -10 31 0 13 5 24 10 24 6 0 10 7 10 15 0 8 -4 15 -10 15 -5 0 -10 -7 -10 -15z"/> <path d="M8654 3939 c12 -41 19 -136 12 -164 -6 -25 -10 -27 -43 -22 -43 7 -65 26 -68 59 -4 37 -4 38 -16 38 -6 0 -9 -7 -5 -15 3 -8 0 -15 -5 -15 -6 0 -9 -9 -6 -20 3 -11 0 -23 -5 -27 -7 -3 -8 -1 -4 5 4 7 1 12 -9 12 -15 0 -15 1 -1 16 21 20 20 27 -4 49 -25 23 -36 14 -18 -15 10 -18 10 -24 1 -27 -27 -10 -11 -31 37 -52 27 -12 54 -29 59 -39 7 -10 14 -13 18 -7 11 14 63 18 63 5 0 -5 -4 -10 -10 -10 -5 0 -10 -9 -10 -21 0 -14 5 -19 15 -16 9 4 21 -8 36 -38 25 -49 43 -60 33 -19 -4 17 -2 29 7 35 10 7 11 11 3 17 -17 10 -35 83 -39 160 -6 82 -17 124 -35 130 -10 4 -11 -2 -6 -19z"/> <path d="M5403 3921 c-18 -15 -40 -28 -50 -29 -128 -12 -213 -36 -213 -59 0 -7 -6 -13 -12 -13 -7 0 -20 -5 -28 -10 -13 -8 -12 -11 5 -24 20 -15 20 -15 0 -16 -24 0 -64 -42 -47 -48 7 -2 12 -10 12 -17 0 -7 5 -15 12 -17 13 -5 -59 -78 -77 -78 -9 0 -13 -18 -14 -55 0 -45 3 -55 17 -55 10 0 13 -3 6 -8 -17 -11 -24 -53 -11 -67 10 -10 15 -9 25 9 9 14 12 15 8 4 -3 -10 -1 -18 4 -18 6 0 10 7 10 15 0 8 5 15 10 15 6 0 10 5 10 10 0 6 -7 10 -15 10 -8 0 -15 7 -15 16 0 9 -9 18 -20 21 -27 7 -25 33 6 66 14 16 24 31 21 34 -3 2 15 25 39 49 42 41 51 73 18 60 -10 -4 -14 2 -14 19 0 21 5 25 30 25 32 0 40 14 15 24 -22 8 -18 26 5 26 11 0 20 6 20 14 0 15 86 49 101 40 18 -11 122 22 152 47 18 15 30 29 27 32 -3 3 -19 -7 -37 -22z"/> <path d="M7257 3836 c5 -44 5 -46 -21 -46 -14 0 -26 -4 -26 -10 0 -5 7 -10 15 -10 9 0 12 -6 8 -16 -3 -9 4 -29 17 -47 15 -20 19 -32 12 -35 -15 -5 -16 -38 -2 -47 6 -3 10 -15 10 -26 0 -10 5 -19 10 -19 19 0 22 30 6 55 l-16 24 40 -5 c31 -4 40 -1 40 11 0 8 7 15 15 15 22 0 18 37 -4 50 -24 12 -34 13 -27 2 3 -5 -1 -9 -9 -9 -11 0 -12 4 -4 14 9 10 8 13 -1 13 -8 0 -10 8 -6 25 4 17 1 30 -11 42 -10 10 -18 27 -18 38 0 11 -7 21 -16 23 -14 3 -16 -4 -12 -42z"/> <path d="M7114 3854 c4 -10 2 -13 -6 -8 -8 5 -9 2 -5 -10 6 -15 3 -17 -24 -11 -26 6 -31 4 -36 -14 -5 -20 -6 -20 -18 -4 -22 29 -30 5 -11 -30 11 -20 12 -25 2 -13 -21 26 -38 11 -32 -27 6 -29 5 -30 -4 -8 -6 14 -8 31 -6 38 3 7 0 13 -6 13 -15 0 -3 -67 16 -86 9 -8 16 -24 16 -35 0 -20 25 -37 37 -25 4 3 2 16 -4 29 -6 12 -16 36 -24 52 -7 17 -15 35 -18 40 -3 6 3 4 12 -4 24 -19 47 -6 47 27 0 38 6 42 43 31 42 -12 54 -26 38 -41 -11 -10 -13 -10 -7 0 5 8 -2 12 -24 12 -30 0 -31 -1 -24 -37 4 -21 12 -45 19 -53 7 -8 15 -27 19 -42 3 -16 11 -28 16 -28 6 0 10 -16 10 -35 0 -24 5 -35 15 -35 8 0 15 -7 15 -15 0 -8 5 -15 10 -15 6 0 10 -7 10 -17 0 -15 -1 -15 -18 0 -30 27 -40 20 -47 -32 -4 -28 -13 -55 -21 -62 -12 -10 -13 -9 -8 4 3 10 -2 20 -15 27 -21 11 -29 40 -11 40 6 0 10 15 10 33 0 40 -25 66 -60 63 -20 -1 -25 -6 -23 -28 1 -21 -2 -25 -19 -20 -16 4 -19 1 -16 -14 3 -14 11 -18 31 -16 26 3 27 1 27 -43 0 -25 5 -45 10 -45 6 0 10 -9 10 -19 0 -14 -5 -18 -20 -14 -23 6 -23 6 -9 -53 14 -55 35 -53 31 4 -2 34 1 40 13 36 10 -4 15 -19 15 -43 0 -54 -10 -81 -27 -74 -8 3 -26 0 -40 -8 -23 -12 -25 -18 -21 -61 4 -33 1 -52 -8 -59 -10 -9 -14 -9 -14 0 0 6 -7 11 -15 11 -8 0 -15 -4 -15 -10 0 -5 4 -10 8 -10 4 0 13 -19 19 -42 9 -33 8 -49 -2 -73 -8 -19 -14 -24 -14 -12 -1 24 -31 22 -31 -3 0 -30 -19 -24 -25 8 -4 15 -11 35 -16 45 -8 14 -6 22 6 31 12 8 15 19 10 39 -9 36 -25 34 -25 -3 0 -30 -24 -43 -32 -18 -3 7 -10 8 -17 3 -10 -5 -12 -23 -8 -61 4 -43 3 -54 -9 -54 -8 0 -14 9 -14 20 0 12 -7 20 -16 20 -20 0 -11 -47 18 -96 26 -44 35 -43 44 4 8 44 35 70 46 44 8 -22 -1 -63 -18 -83 -17 -19 -18 -71 -3 -86 8 -8 6 -11 -7 -10 -10 1 -20 -6 -22 -15 -2 -13 3 -18 19 -18 32 0 16 -12 -20 -14 -20 -1 -27 1 -22 8 5 6 12 32 15 58 8 51 -8 74 -29 45 -19 -26 -25 -20 -25 23 0 38 -19 59 -21 23 0 -11 -3 -13 -6 -5 -11 28 -24 10 -18 -25 6 -37 5 -38 -25 -39 -17 -1 -32 -3 -34 -5 -2 -2 0 -26 5 -54 5 -27 11 -67 14 -87 7 -48 25 -50 25 -3 0 19 4 35 9 35 5 0 12 10 14 23 2 12 5 3 6 -20 0 -24 5 -43 10 -43 11 0 24 48 16 60 -3 6 -2 17 3 26 6 12 11 5 21 -28 18 -59 28 -68 66 -63 28 3 34 1 37 -17 5 -35 28 -34 28 1 0 18 10 41 25 57 14 15 25 33 25 40 0 18 17 18 27 0 4 -8 20 -17 35 -21 26 -7 27 -6 23 32 -2 21 -8 49 -13 63 -5 14 -7 40 -5 58 4 25 2 32 -11 32 -9 0 -16 -8 -16 -20 0 -13 -5 -18 -15 -14 -8 4 -15 12 -15 20 0 8 -4 14 -9 14 -5 0 -12 7 -15 16 -5 14 -4 15 9 4 22 -18 45 -5 45 27 0 21 3 24 12 15 21 -21 28 -13 29 31 0 23 3 36 6 30 6 -17 30 -16 36 1 3 7 3 31 1 52 -3 22 -1 57 4 79 8 33 10 35 11 13 1 -16 6 -28 12 -28 11 0 6 66 -7 113 -3 9 -1 17 5 17 6 0 11 -18 11 -40 0 -40 15 -55 23 -22 3 11 5 8 6 -9 1 -36 -29 -95 -40 -78 -4 7 -11 10 -16 6 -4 -5 -2 -11 4 -15 6 -4 15 -20 18 -35 5 -17 13 -26 23 -25 9 2 21 -8 28 -21 19 -38 54 -54 54 -26 0 8 3 15 8 15 4 0 7 -15 7 -32 0 -24 5 -33 19 -36 16 -3 18 0 12 25 -6 26 -5 27 9 9 8 -11 15 -23 15 -28 0 -4 6 -8 13 -8 6 0 21 -23 32 -52 15 -39 27 -54 48 -61 16 -5 30 -7 32 -5 3 2 -1 21 -7 41 -8 25 -17 37 -30 37 -23 0 -36 29 -17 41 9 6 18 3 26 -8 17 -22 27 -10 19 22 -5 21 -11 25 -28 19 -18 -5 -19 -4 -7 9 8 8 20 12 28 9 10 -4 8 5 -7 30 -26 42 -27 48 -7 48 9 0 15 9 15 25 0 14 -4 25 -10 25 -24 0 -50 45 -50 87 0 36 -3 43 -20 43 -15 0 -20 -7 -20 -29 0 -16 -6 -31 -12 -34 -8 -2 -9 -8 -4 -13 5 -5 11 -4 13 4 3 6 9 10 13 7 5 -3 7 -12 3 -21 -3 -8 2 -23 11 -33 10 -11 13 -21 8 -22 -15 -6 -2 -65 20 -88 17 -19 18 -23 4 -37 -17 -17 -36 -11 -36 12 0 16 -27 19 -32 4 -5 -17 -48 28 -48 50 0 12 -7 20 -16 20 -12 0 -15 -6 -10 -24 4 -17 1 -26 -10 -30 -21 -8 -21 -8 -27 14 -3 11 -13 23 -24 27 -29 11 -32 24 -12 60 24 42 26 118 4 109 -9 -3 -15 0 -15 9 0 8 5 15 11 15 6 0 8 9 4 20 -4 13 -1 22 9 26 18 7 20 22 7 43 -12 19 -51 -16 -51 -47 0 -37 -24 -21 -28 18 -2 19 -11 39 -19 45 -10 8 -13 19 -9 33 9 28 26 29 26 2 0 -22 22 -27 38 -7 5 6 13 34 17 60 l7 48 29 -27 c17 -16 25 -30 19 -34 -15 -9 8 -70 27 -70 11 0 13 10 8 48 -8 56 -43 132 -62 132 -8 0 -13 12 -13 35 0 19 -4 35 -10 35 -5 0 -10 4 -10 10 0 5 7 7 17 3 14 -6 15 -1 9 37 -8 49 -13 60 -28 60 -6 0 -8 -10 -4 -25 7 -27 -3 -32 -22 -13 -14 14 -16 68 -3 68 5 0 11 -5 13 -11 6 -17 38 2 38 22 0 10 5 19 10 19 6 0 10 7 10 15 0 8 -7 15 -15 15 -8 0 -15 -4 -15 -10 0 -5 -4 -10 -8 -10 -5 0 -7 14 -4 30 3 19 0 30 -8 30 -7 0 -10 -7 -6 -16z m-14 -624 c0 -10 -5 -20 -11 -22 -6 -2 -13 -42 -17 -93 -3 -50 -7 -84 -9 -77 -6 16 -30 15 -36 -2 -3 -8 -3 -24 0 -37 4 -15 3 -20 -5 -15 -7 4 -12 14 -12 22 0 8 -6 14 -14 14 -21 0 -29 70 -10 91 11 13 14 29 9 61 -5 37 -3 45 15 56 23 14 40 8 40 -14 0 -8 5 -14 10 -14 6 0 10 13 10 30 0 22 4 28 15 24 8 -4 15 -14 15 -24z"/> <path d="M6871 3821 c-19 -12 -5 -62 19 -68 11 -3 20 -9 20 -15 0 -5 -9 -4 -20 2 -21 11 -40 6 -40 -11 0 -5 -9 -18 -20 -29 -17 -17 -21 -17 -34 -5 -8 8 -17 28 -21 45 -4 16 -11 30 -16 30 -12 0 -12 -57 1 -65 5 -3 7 -12 4 -20 -5 -13 -8 -13 -21 0 -21 21 -35 18 -28 -5 4 -11 2 -20 -4 -20 -14 0 -31 33 -31 60 0 16 -4 20 -16 16 -9 -3 -19 -6 -24 -6 -4 0 -11 -27 -15 -60 -4 -33 -10 -60 -14 -60 -4 0 -12 14 -18 30 -16 42 -39 38 -47 -7 -3 -21 -15 -56 -26 -78 -18 -37 -19 -38 -20 -13 0 18 -7 29 -20 33 -11 4 -27 20 -35 36 -9 16 -20 29 -25 29 -12 0 -1 -60 14 -79 8 -10 6 -13 -9 -10 -11 3 -22 17 -27 38 -7 26 -13 32 -29 28 -10 -3 -22 -1 -25 4 -3 5 -14 9 -24 9 -11 0 -20 8 -22 22 -2 12 -9 23 -15 26 -15 4 -17 -30 -3 -44 15 -15 -8 -74 -28 -76 -10 0 -27 0 -39 1 -20 2 -23 -3 -23 -39 0 -28 -4 -40 -14 -40 -9 0 -12 7 -9 19 5 20 -22 71 -38 71 -5 0 -16 -17 -25 -37 -12 -28 -18 -33 -21 -20 -5 17 -23 24 -23 8 0 -5 -12 -11 -26 -14 -22 -4 -28 0 -40 29 -18 43 -30 43 -39 2 -15 -69 -6 -229 13 -236 8 -2 9 -9 2 -23 -7 -12 -7 -25 -1 -36 5 -10 12 -26 15 -37 4 -12 13 -17 26 -13 19 5 20 0 20 -64 0 -44 4 -69 11 -69 7 0 10 12 7 29 -3 23 -1 27 14 23 12 -3 18 1 18 12 0 9 5 16 11 16 6 0 10 15 9 33 -3 47 -1 61 8 53 10 -10 9 -176 -1 -169 -5 3 -15 -3 -22 -13 -13 -18 -14 -18 -15 -1 0 9 -4 17 -10 17 -14 0 -12 -28 2 -32 9 -3 8 -9 -4 -21 -9 -9 -21 -17 -26 -17 -6 0 -13 -6 -16 -12 -3 -7 -3 3 1 22 7 39 7 44 5 78 -1 14 -7 22 -14 19 -7 -2 -12 -16 -10 -31 1 -14 -2 -26 -8 -26 -5 0 -10 -7 -10 -15 0 -8 -7 -15 -15 -15 -8 0 -15 -9 -15 -20 0 -11 -7 -23 -16 -27 -13 -5 -15 -15 -9 -51 4 -24 9 -51 12 -59 5 -11 1 -14 -13 -9 -22 6 -36 -1 -53 -29 -12 -19 -12 -19 -7 5 3 14 -1 31 -9 40 -12 13 -10 15 11 16 13 1 24 -2 24 -7 0 -5 5 -9 10 -9 6 0 10 9 10 20 0 11 -6 20 -14 20 -9 0 -12 7 -9 20 4 16 0 20 -20 20 -20 0 -26 6 -29 32 -4 25 1 39 20 60 26 27 33 44 36 85 0 13 5 18 11 13 6 -5 14 -8 18 -8 5 0 12 -4 15 -8 4 -4 2 -4 -5 0 -7 3 -14 -2 -18 -14 -3 -11 -10 -20 -15 -20 -4 0 -6 -9 -3 -20 3 -11 9 -20 13 -20 5 0 15 -3 23 -6 11 -4 16 6 21 40 4 25 11 48 17 51 15 10 10 35 -6 35 -8 0 -15 7 -15 15 0 19 -7 19 -26 0 -9 -8 -12 -20 -9 -26 4 -6 -2 -5 -13 2 -25 16 -40 6 -23 -14 14 -17 4 -47 -15 -47 -10 0 -14 12 -14 40 0 45 -25 56 -39 18 -7 -21 -8 -20 -13 9 -2 18 -1 30 3 27 11 -6 39 48 41 79 1 14 7 24 13 22 27 -6 45 -18 45 -31 0 -8 5 -14 10 -14 6 0 10 20 10 45 0 38 -4 47 -22 55 -15 5 -17 9 -7 9 13 1 15 17 15 101 0 55 -3 100 -7 100 -23 0 -60 -26 -65 -47 -4 -13 -12 -23 -20 -23 -9 0 -14 -11 -14 -30 0 -16 -3 -30 -7 -30 -5 0 -8 25 -9 55 0 51 -7 75 -19 63 -7 -7 -45 -187 -45 -215 0 -30 17 -30 23 0 4 20 4 20 6 -4 0 -14 10 -35 22 -48 18 -19 20 -29 14 -86 -5 -45 -4 -65 4 -65 6 0 11 -13 11 -28 0 -39 9 -45 34 -25 21 18 21 18 2 -4 -13 -16 -23 -20 -31 -13 -6 5 -15 7 -18 3 -4 -3 -7 -1 -7 5 0 7 -5 12 -11 12 -8 0 -10 -15 -5 -46 7 -53 15 -71 25 -56 12 19 35 -3 24 -23 -9 -16 -12 -15 -34 9 -21 23 -29 25 -57 17 -29 -9 -31 -8 -22 9 6 10 15 22 20 25 14 9 12 35 -2 35 -7 0 -28 -17 -47 -37 l-34 -38 8 30 c5 17 8 47 7 67 -2 20 2 39 8 43 5 3 10 -1 10 -9 0 -9 5 -16 11 -16 7 0 10 13 7 34 -3 26 0 32 11 28 8 -3 12 0 9 8 -8 24 -24 21 -36 -5 -6 -14 -18 -25 -27 -25 -11 0 -15 -12 -16 -47 0 -27 -3 -42 -6 -35 -8 20 -17 14 -32 -19 -11 -25 -11 -35 0 -55 10 -19 10 -27 0 -37 -10 -9 -11 -8 -6 5 10 25 -3 42 -20 28 -8 -7 -18 -9 -24 -6 -14 9 -11 -66 4 -90 10 -16 11 -24 2 -33 -6 -6 -12 -27 -14 -46 -2 -35 9 -46 24 -22 4 6 18 12 30 13 12 0 20 -3 18 -6 -3 -4 13 -7 35 -7 32 0 41 4 46 21 18 66 40 105 60 109 16 3 21 0 17 -10 -3 -7 1 -13 10 -13 8 0 17 5 19 12 3 7 14 2 32 -13 25 -21 27 -28 21 -66 -8 -53 9 -57 32 -8 15 32 20 35 46 29 l30 -6 -7 43 c-4 24 -10 55 -13 68 -5 20 -3 22 16 16 19 -6 20 -3 15 24 -5 24 -3 31 10 31 9 0 16 7 16 15 0 8 5 15 10 15 12 0 3 -43 -17 -84 -11 -21 -12 -35 -4 -52 7 -16 7 -24 0 -26 -6 -2 -12 -15 -12 -30 -1 -14 -5 -24 -9 -21 -5 2 -8 -1 -8 -6 0 -13 17 -14 24 -2 3 5 17 11 30 13 22 5 25 1 28 -31 2 -24 8 -36 18 -36 32 0 39 -23 41 -135 0 -31 12 -49 32 -50 4 0 7 8 8 18 1 28 21 -29 21 -60 -1 -26 21 -44 39 -32 12 7 11 64 -1 64 -6 0 -15 11 -20 25 -5 14 -14 25 -20 25 -5 0 -10 8 -9 18 0 10 3 12 6 5 12 -32 24 -8 21 44 -3 55 -21 83 -31 46 -4 -16 -5 -16 -6 -1 0 10 8 23 19 30 12 8 20 24 20 40 0 15 5 30 11 34 6 3 9 16 7 28 -3 17 5 30 34 51 25 19 44 45 56 78 13 35 21 45 25 33 4 -9 13 -16 22 -16 20 0 19 36 -1 44 -13 5 -14 16 -8 62 6 51 5 56 -15 61 -14 3 -21 13 -21 28 0 36 -11 55 -31 55 -14 0 -19 -7 -19 -28 0 -15 4 -32 9 -37 12 -12 17 -152 7 -182 -4 -13 -12 -23 -17 -23 -6 0 -8 -8 -4 -19 6 -20 -20 -38 -31 -20 -8 14 5 79 16 79 11 0 13 40 4 64 -3 9 -12 16 -19 16 -17 0 -27 28 -13 36 7 4 8 3 4 -4 -4 -7 -2 -12 3 -12 6 0 11 7 11 15 0 24 -26 17 -38 -10 -16 -35 -27 -105 -16 -105 10 0 16 -119 7 -133 -8 -14 -23 14 -23 44 0 32 -31 62 -55 53 -17 -7 -17 -6 0 20 12 19 23 25 36 21 17 -6 19 -1 19 44 0 28 5 51 10 51 6 0 10 7 10 15 0 18 -17 20 -23 3 -2 -7 -4 12 -3 42 1 44 -2 55 -16 58 -12 2 -19 -5 -24 -22 -3 -14 -11 -26 -16 -26 -6 0 -8 -14 -3 -36 5 -28 3 -35 -7 -32 -9 3 -13 24 -13 63 0 62 -18 85 -29 39 -5 -19 -10 -24 -18 -16 -15 15 -16 94 0 100 14 4 16 42 2 42 -5 0 -10 -7 -10 -15 0 -8 -4 -15 -10 -15 -5 0 -10 6 -10 13 0 6 -5 43 -10 80 -7 45 -7 74 0 85 8 15 9 14 10 -5 0 -27 0 -27 34 -9 14 7 42 12 61 9 30 -3 36 0 50 28 16 29 17 30 30 12 18 -23 19 -33 1 -33 -11 0 -26 -20 -26 -36 0 -2 14 -1 30 3 24 4 36 1 51 -16 11 -11 24 -21 29 -21 17 0 11 26 -10 45 -23 21 -27 65 -5 65 11 0 13 -7 9 -29 -5 -23 -2 -32 16 -41 39 -21 51 -7 48 60 -2 46 2 64 15 78 26 25 41 -2 20 -35 -12 -17 -13 -27 -5 -35 19 -19 42 -1 42 33 0 37 23 35 28 -3 2 -17 11 -28 25 -32 34 -9 37 -8 37 15 0 15 4 19 16 15 9 -3 17 -6 19 -6 2 0 1 -16 -2 -36 -5 -29 -3 -36 8 -32 20 7 46 56 62 118 l15 55 13 -30 c7 -16 13 -31 14 -31 0 -1 11 -5 24 -9 20 -6 23 -4 18 9 -4 9 -2 16 4 16 7 0 8 19 5 50 -7 59 14 71 29 18 7 -24 17 -34 34 -36 21 -3 23 -1 18 20 -5 21 -5 21 7 6 15 -21 33 -23 39 -5 6 19 57 -12 57 -35 0 -26 18 -22 23 5 4 19 4 18 6 -5 1 -25 21 -42 21 -18 0 6 7 10 15 10 8 0 15 2 15 3 0 10 -33 67 -41 72 -17 11 2 25 25 19 17 -4 25 1 36 23 18 34 31 44 48 38 6 -2 12 0 12 5 0 6 -13 10 -30 10 -24 0 -30 -4 -30 -21 0 -11 -4 -17 -10 -14 -5 3 -10 19 -10 36 0 29 -13 36 -39 20z m-762 -865 c17 -20 17 -96 0 -106 -7 -5 -10 -12 -6 -17 5 -4 12 -1 16 6 6 9 11 10 15 2 12 -19 29 -12 23 9 -6 24 8 36 17 14 7 -19 -10 -44 -30 -44 -10 0 -13 -7 -8 -25 3 -14 2 -31 -4 -38 -5 -6 -13 -32 -17 -56 -5 -30 -10 -39 -16 -30 -5 8 -6 29 -3 47 4 18 2 32 -4 32 -21 0 -22 61 -2 100 11 22 20 46 20 55 0 19 -29 20 -36 0 -4 -8 -13 -15 -21 -15 -10 0 -13 -9 -9 -37 3 -21 3 -30 0 -20 -6 20 -15 22 -33 5 -11 -11 -13 -7 -7 22 4 19 11 37 16 38 6 2 10 8 10 14 0 14 42 58 56 58 6 0 17 -6 23 -14z"/> <path d="M7640 3783 c1 -19 19 -35 30 -28 9 5 11 4 6 -3 -4 -7 -18 -9 -32 -6 -14 4 -24 2 -24 -5 0 -6 6 -11 14 -11 20 0 27 -27 9 -34 -9 -4 -23 0 -33 9 -9 8 -26 15 -38 15 -17 0 -22 -6 -22 -26 0 -20 4 -24 19 -19 21 6 70 -34 63 -53 -2 -6 6 -15 16 -21 11 -6 22 -18 26 -27 5 -14 0 -15 -35 -9 -39 7 -42 6 -36 -14 3 -11 2 -21 -2 -21 -13 0 -31 24 -31 42 0 9 -13 27 -29 39 -16 12 -32 35 -35 51 -6 32 -33 65 -44 53 -4 -4 -1 -10 6 -12 17 -7 15 -43 -3 -43 -20 0 -19 -6 6 -31 23 -23 21 -42 -5 -47 -14 -3 -17 1 -11 17 5 17 1 23 -20 31 -34 13 -45 13 -45 -1 0 -6 9 -13 20 -16 29 -8 25 -17 -15 -33 -38 -15 -46 -30 -16 -30 12 0 21 -9 25 -24 3 -14 15 -27 25 -31 30 -9 47 -33 33 -47 -9 -9 -12 -8 -12 4 0 20 -38 34 -52 20 -14 -14 -1 -50 20 -55 16 -4 16 -5 0 -6 -23 -1 -23 -15 -1 -32 15 -12 16 -12 11 2 -5 13 -2 16 14 11 28 -7 20 19 -10 33 -13 6 -22 18 -21 30 1 16 2 17 6 3 6 -25 42 -33 61 -14 14 14 14 17 -3 38 -11 13 -13 17 -5 11 17 -16 40 -17 40 -2 0 6 -10 24 -21 41 -18 25 -19 32 -8 39 11 6 15 1 17 -21 2 -23 8 -30 24 -30 16 0 19 5 15 21 -7 25 2 51 14 43 5 -3 9 -13 9 -23 0 -10 9 -26 20 -36 20 -18 22 -18 38 -1 15 15 15 18 2 26 -10 6 -3 7 22 3 24 -3 43 -1 53 7 12 10 15 10 15 -3 0 -15 28 -27 63 -27 14 0 17 5 13 23 -3 12 -3 16 0 10 7 -16 34 -17 34 -3 0 6 -6 26 -14 45 -13 30 -13 33 1 28 14 -5 15 0 10 31 -4 25 -2 34 5 30 6 -4 17 1 25 11 7 11 13 13 13 7 0 -7 7 -12 16 -12 9 0 14 7 12 18 -4 22 21 52 38 45 8 -3 14 0 14 7 0 18 -52 3 -72 -22 -10 -11 -18 -15 -18 -9 0 6 -7 11 -16 11 -11 0 -14 -6 -9 -20 5 -14 2 -20 -9 -20 -9 0 -16 -8 -16 -19 0 -10 -8 -21 -18 -23 -15 -4 -18 -1 -14 17 3 17 -2 24 -21 29 -14 3 -33 3 -41 0 -12 -5 -16 0 -16 18 0 13 -9 31 -20 41 -22 18 -30 21 -30 10z"/> <path d="M8140 3756 c1 -14 25 -46 34 -46 4 0 5 9 1 19 -3 11 -1 22 4 26 6 3 8 0 5 -9 -3 -8 2 -17 13 -20 10 -3 24 -19 30 -36 12 -31 33 -41 33 -15 0 19 21 19 46 0 19 -14 18 -14 -3 -15 -28 0 -29 -17 -4 -47 22 -26 46 -31 37 -7 -3 8 -2 12 4 9 17 -11 32 5 19 21 -6 7 -8 22 -4 31 6 16 8 15 24 -6 20 -26 51 -23 51 4 0 11 -6 15 -19 10 -14 -4 -20 1 -25 20 -7 27 -36 35 -36 10 0 -23 -11 -18 -59 25 -61 56 -78 52 -46 -10 9 -17 11 -30 5 -30 -5 0 -10 5 -10 10 0 6 -11 23 -26 39 -25 28 -74 40 -74 17z"/> <path d="M6829 3558 c-1 -29 -3 -45 -6 -35 -2 9 -11 17 -19 17 -10 0 -13 -7 -8 -24 3 -13 1 -27 -5 -30 -15 -10 -14 -22 5 -40 8 -9 11 -16 5 -16 -6 0 -11 -16 -11 -35 0 -23 5 -35 14 -35 17 0 40 55 30 71 -13 21 -11 59 3 59 9 0 13 -17 13 -55 0 -53 -10 -83 -37 -113 -18 -19 -16 -30 8 -37 29 -10 38 3 51 74 10 50 13 59 20 41 17 -46 58 6 58 75 0 51 -12 69 -39 62 -16 -4 -21 -1 -21 14 0 10 -7 19 -15 19 -8 0 -15 9 -15 20 0 11 -7 20 -15 20 -11 0 -15 -13 -16 -52z"/> <path d="M7310 3428 c0 -19 5 -39 12 -46 9 -9 8 -12 -5 -12 -20 0 -22 -11 -5 -28 18 -18 26 -15 30 10 4 25 28 37 28 14 0 -9 11 -21 25 -26 24 -9 29 -19 26 -47 -1 -6 3 -14 9 -18 19 -12 11 -33 -10 -28 -28 7 -26 -21 3 -44 12 -10 29 -27 37 -37 15 -19 14 -19 -13 -1 -15 10 -30 15 -34 12 -11 -11 27 -57 47 -57 13 0 21 -9 25 -25 3 -14 7 -37 10 -51 4 -17 11 -24 20 -20 8 3 15 1 15 -4 0 -6 -9 -10 -20 -10 -11 0 -20 7 -20 15 0 9 -6 18 -14 21 -8 3 -20 19 -26 35 -12 28 -37 43 -27 15 3 -8 -1 -17 -9 -20 -11 -4 -13 -13 -9 -27 4 -12 8 -29 9 -37 4 -21 26 -28 26 -8 0 9 -4 16 -10 16 -5 0 -10 11 -10 25 0 14 3 25 8 25 12 0 49 -44 56 -67 8 -25 22 -30 29 -10 3 9 8 9 21 -2 20 -17 33 -7 17 13 -15 18 -6 37 14 29 17 -6 20 8 4 24 -7 7 -6 15 5 26 20 20 21 47 1 47 -8 0 -17 12 -21 28 -10 49 -26 82 -39 82 -8 0 -10 9 -7 25 5 27 -9 33 -27 11 -9 -10 -7 -21 6 -44 15 -26 15 -31 2 -44 -13 -14 -19 -11 -49 18 -19 19 -31 34 -28 34 4 0 13 -6 20 -14 19 -19 58 -30 58 -17 0 6 -3 10 -7 10 -20 -3 -33 2 -33 12 0 8 5 8 15 -1 8 -7 15 -8 15 -2 0 5 -6 15 -14 21 -8 6 -16 25 -18 40 -3 22 -1 28 11 23 10 -4 13 -1 8 11 -6 16 6 30 31 33 6 1 10 -2 6 -7 -3 -5 0 -9 5 -9 16 0 13 20 -3 26 -8 3 -24 1 -35 -5 -13 -7 -22 -8 -26 -1 -4 6 -13 5 -25 -2 -15 -10 -22 -10 -31 -1 -9 9 -6 11 12 7 23 -5 23 -5 4 8 -12 7 -19 20 -18 29 4 18 -22 44 -54 53 -21 7 -23 4 -23 -26z"/> <path d="M9345 3418 c-10 -53 -10 -279 -1 -326 6 -30 17 -48 35 -59 53 -33 67 -66 23 -57 -20 4 -33 0 -47 -16 -17 -19 -20 -38 -22 -147 -1 -68 -7 -141 -13 -161 -21 -70 -52 -317 -50 -393 1 -75 -15 -157 -33 -170 -13 -9 1 -29 19 -29 15 0 19 -16 15 -63 -1 -16 3 -34 9 -42 7 -8 9 -18 6 -23 -9 -16 22 -232 37 -255 9 -14 15 -54 16 -117 1 -52 5 -132 10 -177 5 -45 6 -93 4 -106 -3 -14 0 -28 6 -31 6 -4 11 -15 11 -24 0 -9 11 -44 24 -77 24 -58 52 -82 83 -71 13 5 17 -4 14 -36 -1 -9 7 -27 19 -40 40 -44 46 -53 65 -98 11 -25 27 -53 37 -63 9 -11 19 -31 23 -45 4 -15 16 -46 27 -71 11 -24 36 -89 55 -145 20 -56 39 -106 44 -111 22 -28 29 -105 15 -162 -14 -60 -108 -267 -126 -278 -13 -8 -13 -25 0 -25 14 0 125 236 140 298 14 60 8 115 -19 176 -10 22 -24 59 -31 81 -27 86 -109 283 -133 318 -14 21 -28 51 -32 67 -4 17 -12 30 -19 30 -13 0 -40 57 -37 78 3 20 -19 42 -41 42 -11 0 -26 7 -34 15 -9 8 -11 15 -5 15 21 0 11 31 -13 40 -44 16 -72 177 -68 390 1 72 -2 110 -12 125 -23 36 -33 90 -39 212 -2 40 -9 79 -16 86 -6 8 -9 22 -5 31 9 24 -4 66 -21 66 -12 0 -12 5 -3 28 7 15 15 83 19 152 4 69 10 139 13 155 3 17 8 59 11 95 4 36 15 97 25 135 15 55 17 91 13 166 -5 76 -2 101 11 126 9 18 20 34 25 37 14 9 41 -4 41 -20 0 -8 4 -14 9 -14 39 0 13 91 -32 111 -28 13 -32 21 -45 84 -12 57 -12 90 -3 179 6 60 12 110 14 112 2 2 17 -2 35 -8 41 -16 56 -54 49 -122 -3 -36 -1 -60 7 -72 7 -11 22 -44 34 -74 11 -30 27 -68 35 -85 28 -56 67 -154 67 -169 0 -15 12 -47 51 -132 11 -23 19 -48 19 -57 0 -9 6 -34 14 -54 42 -112 106 -371 106 -428 0 -20 7 -53 16 -73 28 -65 31 -76 43 -150 15 -99 14 -102 -14 -48 -14 26 -25 58 -25 70 0 13 -7 29 -15 36 -8 7 -15 21 -15 31 0 10 -5 21 -11 25 -6 3 -9 19 -5 35 3 16 2 29 -3 29 -5 0 -11 19 -14 43 -8 74 -71 217 -116 264 -12 12 -21 27 -21 33 0 26 -47 99 -92 143 -50 47 -93 62 -104 33 -10 -26 15 -201 34 -241 20 -40 38 -103 34 -118 -1 -4 2 -17 8 -27 6 -11 12 -57 15 -103 5 -101 30 -221 55 -264 13 -23 17 -43 13 -67 -3 -20 0 -56 6 -81 6 -25 14 -73 16 -106 3 -34 8 -66 12 -72 13 -20 32 -100 33 -134 0 -18 4 -33 10 -33 5 0 7 -7 3 -16 -7 -19 13 -167 33 -241 8 -28 14 -71 14 -95 0 -24 5 -59 11 -78 6 -19 15 -55 19 -80 15 -85 33 -165 41 -185 11 -25 28 -96 38 -155 4 -25 20 -85 35 -135 15 -49 34 -111 42 -136 7 -25 20 -82 27 -125 8 -43 22 -97 30 -119 9 -22 18 -49 20 -60 4 -15 5 -13 6 7 0 14 -7 46 -18 70 -10 24 -21 68 -25 99 -7 59 -11 74 -70 278 -20 69 -36 137 -36 152 0 15 -4 30 -9 33 -4 3 -11 24 -15 47 -4 23 -10 47 -14 53 -7 11 -24 91 -41 191 -5 28 -14 66 -20 85 -6 19 -11 54 -11 78 0 24 -6 64 -14 90 -21 71 -36 187 -30 221 4 20 2 31 -5 31 -6 0 -11 13 -11 30 0 26 -13 82 -38 165 -5 17 -7 36 -5 42 3 7 -1 39 -8 70 -7 32 -12 82 -10 112 1 34 -3 60 -12 70 -29 34 -45 107 -66 301 -10 87 -25 146 -64 255 -8 22 -17 73 -19 113 -5 66 -4 72 14 72 31 0 103 -66 132 -121 14 -28 26 -55 26 -60 0 -5 10 -20 23 -35 26 -30 87 -143 87 -162 0 -7 7 -26 15 -42 8 -16 16 -57 17 -90 1 -36 7 -65 15 -71 7 -7 13 -20 13 -30 0 -10 5 -21 10 -24 6 -3 10 -16 10 -28 0 -12 7 -33 15 -47 8 -14 19 -37 26 -52 7 -18 19 -28 31 -28 18 0 20 4 13 33 -3 17 -12 64 -19 102 -7 39 -23 92 -34 119 -12 27 -22 64 -22 83 0 53 -51 261 -106 431 -8 23 -14 50 -14 60 0 9 -8 31 -18 47 -10 17 -26 57 -36 90 -23 72 -75 202 -93 230 -7 11 -13 26 -13 35 0 8 -10 35 -23 60 -16 31 -23 66 -25 113 -3 85 -15 115 -46 123 -14 3 -30 12 -37 20 -18 22 -28 17 -34 -18z"/> <path d="M4978 3403 c-20 -5 -25 -33 -7 -33 8 0 8 -5 -1 -15 -16 -19 -5 -49 15 -41 8 3 15 0 15 -5 0 -11 -16 -9 -51 5 -12 5 -16 0 -16 -24 0 -18 -4 -35 -10 -38 -5 -4 -13 -14 -16 -22 -7 -15 -3 21 9 80 4 24 2 30 -11 30 -11 0 -15 -5 -11 -15 3 -8 -4 -21 -16 -29 -16 -11 -18 -19 -11 -28 19 -23 26 -80 12 -89 -7 -4 -10 -11 -7 -14 8 -9 43 24 51 48 4 9 15 17 25 17 27 0 32 9 22 36 -5 13 -6 23 -2 23 23 -4 42 3 42 14 0 6 9 23 20 37 22 28 26 50 9 50 -5 0 -7 -5 -3 -12 4 -7 3 -8 -4 -4 -6 4 -9 12 -6 19 5 13 -17 17 -48 10z"/> <path d="M5112 3345 c-17 -14 -37 -25 -45 -25 -8 0 -21 -7 -28 -16 -7 -9 -24 -20 -37 -25 -12 -5 -22 -15 -20 -21 3 -17 -39 -110 -54 -119 -12 -8 -2 -29 14 -29 5 0 8 7 4 15 -3 9 0 15 10 15 8 0 17 13 21 30 3 17 10 30 15 30 6 0 8 14 6 30 -3 17 0 30 6 30 5 0 23 12 38 27 22 21 28 23 28 10 0 -9 -7 -17 -15 -17 -8 0 -22 -11 -30 -24 -13 -19 -14 -29 -5 -45 13 -26 35 -27 49 -3 10 16 10 15 11 -3 0 -11 -11 -33 -25 -50 -14 -16 -22 -22 -19 -12 4 12 1 17 -11 17 -12 0 -15 -5 -10 -20 4 -11 2 -20 -4 -20 -6 0 -11 -7 -11 -15 0 -18 16 -20 23 -2 4 9 6 8 6 -2 1 -8 -7 -20 -16 -27 -10 -7 -15 -16 -10 -20 8 -9 47 29 47 46 0 6 5 8 10 5 8 -5 8 -11 1 -19 -8 -10 -5 -56 4 -56 13 0 65 24 65 30 0 14 -20 22 -33 13 -7 -4 -4 0 6 9 11 10 17 25 13 33 -3 8 -1 15 4 15 10 0 14 -21 11 -47 -1 -7 3 -13 9 -13 5 0 10 6 11 13 0 6 5 -1 11 -16 9 -26 13 -28 49 -22 39 7 40 7 33 -21 -5 -20 -4 -25 6 -19 9 6 9 3 0 -15 -8 -14 -15 -19 -19 -12 -9 15 -48 4 -56 -16 -3 -8 -1 -20 4 -25 7 -7 7 -17 0 -29 -11 -21 -6 -48 10 -48 6 0 15 18 22 39 7 24 19 41 31 44 11 3 22 15 25 26 3 12 9 21 14 21 5 0 9 7 9 16 0 9 -5 12 -12 8 -9 -4 -10 -4 -3 3 6 5 22 14 38 21 22 9 27 9 27 -2 0 -7 -8 -20 -18 -30 -20 -18 -30 -106 -12 -106 5 0 10 6 10 14 0 8 9 21 20 29 11 8 17 17 12 22 -4 5 -2 5 4 2 7 -4 14 0 18 8 7 20 46 20 46 0 0 -9 7 -18 15 -21 8 -4 15 -12 15 -20 0 -8 7 -14 15 -14 8 0 15 6 15 13 0 20 -14 34 -31 32 -17 -3 -20 18 -4 32 4 4 5 3 1 -4 -8 -14 10 -28 18 -14 4 5 0 16 -8 24 -17 16 -9 31 17 34 13 1 17 -4 12 -15 -11 -29 -10 -37 3 -34 8 1 11 -1 8 -6 -2 -4 -7 -45 -11 -90 -5 -69 -3 -82 10 -82 9 0 15 9 14 23 -1 37 10 119 16 126 4 3 12 6 18 6 7 0 11 11 9 24 -1 12 6 36 15 52 26 44 5 48 -31 6 -20 -24 -33 -33 -33 -23 0 8 5 13 10 9 5 -3 6 4 2 18 -11 34 -15 36 -29 16 -7 -9 -20 -17 -27 -17 -8 0 -20 -9 -27 -20 -7 -11 -20 -20 -30 -20 -10 0 -36 -17 -58 -37 -21 -21 -32 -30 -25 -21 7 9 10 21 7 26 -3 6 1 15 9 22 8 7 15 21 15 31 0 23 34 45 82 54 20 4 39 14 43 22 8 23 -3 29 -25 15 -25 -16 -30 -15 -30 3 0 19 -10 19 -38 -1 -13 -9 -26 -13 -30 -9 -4 4 -1 10 6 12 14 5 16 33 2 33 -5 0 -10 -7 -10 -15 0 -8 -5 -15 -11 -15 -7 0 -10 -12 -7 -30 3 -18 -1 -35 -9 -41 -8 -7 -13 -8 -13 -1 0 15 -42 23 -57 11 -6 -6 -17 -8 -23 -4 -6 4 -18 1 -26 -6 -12 -10 -13 -9 -8 6 4 10 1 20 -6 25 -9 6 -6 14 13 30 15 13 24 28 20 33 -3 6 -1 7 5 3 7 -4 12 -2 12 3 0 16 -8 14 -47 -10 -33 -20 -63 -20 -63 1 0 5 6 10 14 10 19 0 40 26 26 35 -7 4 -7 12 0 25 13 25 13 50 -2 50 -6 0 -24 -14 -40 -32 -15 -17 -28 -27 -28 -22 0 5 14 23 30 41 34 36 36 43 15 43 -8 0 -15 -6 -15 -12 0 -10 -2 -10 -8 0 -5 8 -16 10 -27 6 -13 -5 -16 -4 -11 4 4 7 17 12 28 12 21 0 47 26 48 48 0 19 -15 15 -48 -13z"/> <path d="M4048 3313 c-3 -11 -23 -23 -47 -31 -23 -7 -54 -24 -69 -37 -15 -14 -34 -25 -42 -25 -23 0 -116 -56 -137 -84 -11 -13 -33 -32 -50 -43 -43 -26 -138 -109 -197 -172 -28 -30 -90 -95 -137 -145 -115 -121 -199 -217 -199 -226 0 -5 -20 -32 -46 -62 -86 -101 -164 -270 -186 -403 -8 -53 -42 -168 -98 -335 -10 -30 -24 -82 -30 -114 -7 -33 -41 -139 -77 -235 -36 -97 -79 -216 -96 -266 -36 -102 -57 -122 -155 -151 -31 -9 -88 -31 -127 -49 -151 -72 -192 -87 -252 -92 -58 -5 -80 -16 -51 -25 7 -3 -24 -22 -68 -43 -43 -21 -106 -51 -138 -66 -33 -16 -65 -29 -73 -29 -7 0 -36 -11 -63 -25 -59 -30 -161 -69 -249 -95 -35 -11 -73 -25 -85 -33 -29 -19 -119 -47 -151 -47 -14 0 -58 -17 -98 -37 -40 -20 -97 -40 -127 -44 -46 -7 -60 -14 -85 -43 -19 -22 -54 -45 -95 -61 -91 -37 -150 -67 -180 -90 -14 -12 -55 -35 -91 -53 -36 -18 -86 -53 -112 -77 -26 -24 -56 -47 -67 -50 -11 -4 -20 -11 -20 -16 0 -16 60 20 102 61 22 21 70 53 106 71 37 18 78 42 92 54 30 24 90 54 180 90 41 16 76 38 95 61 26 29 40 36 87 43 32 4 86 23 127 44 39 20 83 37 97 37 31 0 121 28 150 47 12 8 50 22 85 33 88 26 190 65 249 95 27 14 56 25 63 25 8 0 40 13 73 29 32 15 94 45 137 65 42 21 77 43 77 50 0 8 20 15 53 19 51 5 99 24 242 92 39 18 96 40 127 49 98 29 119 49 154 151 18 50 48 133 68 185 47 120 106 295 106 312 0 14 63 225 99 333 11 34 23 81 26 105 19 129 105 319 189 418 26 30 46 57 46 62 0 10 85 106 204 231 50 53 112 118 137 145 55 58 150 142 192 167 17 11 39 30 50 43 21 28 114 84 137 84 8 0 26 10 40 23 14 12 37 28 52 34 26 11 28 11 34 -12 3 -13 3 -32 0 -42 -4 -13 2 -22 24 -31 23 -11 29 -19 26 -35 -18 -86 -17 -97 4 -97 13 0 20 -7 20 -20 0 -11 6 -20 14 -20 7 0 16 -13 20 -30 4 -21 11 -30 25 -30 29 0 34 -27 5 -34 -29 -8 -32 -26 -4 -26 11 0 20 -5 20 -11 0 -5 4 -8 9 -4 5 3 13 0 17 -6 4 -8 3 -9 -4 -5 -8 5 -12 -2 -12 -18 0 -32 16 -34 23 -4 11 39 20 11 21 -66 1 -41 5 -78 8 -82 11 -11 30 7 25 25 -2 10 7 24 22 36 24 18 25 18 11 0 -13 -16 -13 -18 0 -13 20 6 26 38 7 38 -8 0 -26 -11 -41 -25 -25 -23 -38 -21 -15 2 6 6 8 17 3 24 -4 7 -8 25 -8 41 -1 22 2 27 17 22 17 -5 57 28 57 48 0 14 -19 9 -30 -9 -9 -17 -11 -16 -29 5 -22 25 -36 29 -27 7 3 -8 1 -15 -4 -15 -6 0 -10 9 -10 20 0 25 -29 60 -51 60 -9 0 -20 7 -23 16 -9 22 -8 24 9 18 9 -4 15 0 15 10 0 11 -9 16 -29 16 -23 0 -30 5 -33 23 -2 13 -10 22 -19 21 -13 -1 -14 7 -7 55 6 37 6 57 -1 59 -6 2 -11 11 -11 19 0 9 -6 13 -14 10 -18 -7 -16 44 3 59 8 6 11 16 7 22 -4 7 -2 12 3 12 6 0 11 7 11 15 0 21 -27 19 -32 -2z"/> <path d="M5390 2972 c0 -5 -11 -14 -24 -22 -26 -14 -41 -43 -51 -102 -3 -20 -12 -50 -20 -65 -8 -15 -15 -34 -15 -40 0 -7 -4 -13 -10 -13 -5 0 -10 -16 -10 -35 0 -37 8 -43 28 -23 13 13 16 3 13 -34 -2 -18 14 -25 22 -10 3 4 8 34 12 66 7 52 6 58 -8 53 -11 -4 -14 -2 -11 8 3 8 13 11 21 8 13 -5 15 -1 10 18 -3 13 0 41 8 62 7 21 11 47 8 57 -3 12 0 20 7 20 7 0 10 7 6 15 -3 8 -2 14 2 14 20 -3 32 3 32 16 0 8 -4 15 -10 15 -5 0 -10 -4 -10 -8z"/> <path d="M8846 2852 c3 -9 11 -43 15 -75 13 -88 -11 -133 -109 -203 -2 -1 4 -18 12 -39 19 -45 7 -80 -24 -70 -30 9 -60 -12 -60 -43 -1 -15 -9 -42 -19 -61 -14 -26 -19 -30 -24 -17 -10 24 -57 21 -57 -4 0 -22 15 -27 24 -7 3 8 8 7 16 -6 8 -12 18 -16 32 -11 19 6 20 3 14 -31 -5 -25 -3 -40 4 -45 17 -10 -6 -90 -26 -90 -8 0 -20 -12 -27 -27 -6 -15 -27 -42 -44 -60 -18 -18 -33 -37 -33 -43 0 -5 -11 -10 -25 -10 -14 0 -25 5 -25 10 0 6 -4 10 -10 10 -14 0 -13 -27 1 -32 14 -5 -50 -68 -68 -68 -22 0 -53 -33 -53 -57 0 -14 -6 -23 -15 -23 -9 0 -17 -14 -21 -39 -6 -37 -8 -39 -50 -46 -24 -3 -45 -12 -45 -18 -1 -7 -2 -41 -3 -77 -1 -62 -2 -65 -24 -62 -35 5 -54 -16 -47 -50 5 -21 3 -28 -8 -28 -10 0 -18 -14 -22 -40 -4 -25 -12 -40 -21 -40 -21 0 -94 -60 -94 -77 0 -7 4 -13 10 -13 15 0 0 -33 -26 -55 -12 -12 -25 -38 -29 -58 -4 -22 -13 -37 -21 -37 -8 0 -14 -4 -14 -9 0 -4 -19 -5 -42 0 -58 11 -128 11 -128 0 0 -5 -8 -12 -17 -14 -14 -4 -13 -5 4 -6 12 0 24 5 26 12 4 9 6 9 6 0 1 -7 6 -13 12 -13 5 0 7 5 4 10 -4 6 5 10 19 10 14 0 26 -3 26 -7 0 -12 104 -11 116 1 6 7 17 29 23 49 7 21 24 49 39 62 16 15 25 34 25 54 0 21 6 33 18 36 10 3 21 15 24 26 4 10 15 19 25 19 13 0 22 9 26 25 3 14 15 30 25 36 21 11 25 49 8 66 -16 16 8 27 53 24 22 -1 38 2 38 8 0 6 -4 11 -10 11 -6 0 -10 28 -10 63 l0 63 45 13 c42 12 46 16 51 52 4 23 12 39 20 39 8 0 14 10 14 23 0 25 31 57 57 57 22 0 83 48 83 66 0 8 10 14 25 14 17 0 25 6 25 18 0 9 16 28 35 42 20 14 35 34 35 46 0 12 10 25 23 31 15 7 26 26 35 57 7 29 18 46 27 46 18 0 20 16 3 26 -6 4 -14 2 -16 -4 -9 -29 -18 -7 -16 41 3 68 12 97 30 90 20 -7 17 7 -3 23 -15 11 -16 15 -4 23 7 5 21 7 30 4 27 -7 55 22 57 58 0 19 4 44 8 57 5 14 3 22 -4 22 -6 0 -8 -5 -4 -12 4 -6 3 -8 -4 -4 -6 3 -13 -2 -15 -11 -4 -16 -5 -16 -6 -1 0 9 15 29 34 44 54 41 68 76 69 180 1 81 -1 90 -17 92 -14 1 -17 -3 -11 -16z"/> <path d="M5554 2745 c-3 -8 -2 -20 2 -27 5 -10 4 -11 -7 0 -19 17 -29 15 -29 -8 0 -11 -4 -20 -9 -20 -12 0 -23 -120 -12 -134 14 -17 20 -114 7 -112 -17 3 -36 16 -36 27 0 16 18 10 23 -8 3 -10 5 6 4 36 -1 32 -7 56 -14 58 -8 3 -10 -7 -7 -34 l6 -38 -27 43 c-29 47 -50 55 -43 17 3 -14 1 -25 -3 -25 -13 0 -11 -28 2 -36 6 -3 15 -1 19 6 11 18 34 -27 32 -62 -1 -16 3 -28 9 -28 6 0 9 9 6 19 -3 14 -1 18 9 14 8 -3 14 -16 14 -29 0 -30 14 -31 28 -1 10 21 11 21 17 -11 4 -18 12 -35 16 -38 5 -3 9 -14 9 -25 0 -11 7 -19 18 -19 17 0 17 1 25 134 1 24 -3 41 -10 43 -9 3 -13 -8 -13 -36 0 -55 -15 -52 -18 3 -1 36 2 45 18 49 12 3 20 14 21 29 1 12 6 -1 11 -29 12 -67 28 -68 28 -3 0 38 -4 52 -16 57 -15 5 -15 8 -2 17 8 6 17 18 21 26 4 12 6 11 6 -2 1 -10 6 -18 11 -18 7 0 9 20 4 60 -5 42 -3 60 5 60 6 0 11 7 11 15 0 9 -9 15 -23 15 -19 0 -24 -8 -35 -56 -12 -50 -24 -72 -59 -109 -7 -8 -13 -20 -13 -29 0 -8 -4 -17 -9 -21 -19 -11 -2 134 24 223 8 25 -12 32 -21 7z"/> <path d="M4280 2731 c0 -5 7 -11 15 -15 8 -3 15 -12 15 -20 0 -8 6 -17 13 -20 10 -5 10 -7 0 -12 -20 -9 -17 -48 3 -40 12 4 14 1 9 -14 -5 -14 -2 -20 9 -20 9 0 16 -4 16 -10 0 -5 10 -11 23 -11 18 -1 18 -2 4 -6 -11 -3 -16 -10 -13 -20 3 -8 6 -17 6 -19 0 -2 7 -4 15 -4 8 0 15 7 15 16 0 14 3 14 15 4 8 -7 15 -19 15 -26 0 -8 9 -14 20 -14 11 0 20 4 20 10 0 5 -8 7 -17 4 -15 -5 -15 -4 -3 4 18 14 21 11 45 -34 15 -28 17 -38 7 -42 -16 -5 -16 -22 1 -22 22 0 77 -66 77 -92 0 -14 7 -28 15 -32 8 -3 15 -12 15 -19 0 -15 33 -57 45 -57 4 0 4 7 1 16 -3 8 -2 12 4 9 6 -3 10 -12 10 -20 0 -19 47 -68 58 -61 5 3 7 -7 4 -22 -4 -19 -7 -22 -10 -9 -4 18 -22 24 -22 7 0 -18 23 -60 34 -60 31 1 45 41 23 68 -7 8 -5 12 6 12 8 0 17 3 20 8 2 4 2 1 0 -6 -3 -13 19 -42 32 -42 4 0 5 6 2 14 -10 25 5 26 24 2 12 -15 19 -40 19 -65 0 -23 5 -41 10 -41 6 0 10 12 10 28 1 21 3 24 10 11 15 -25 29 -99 19 -99 -5 0 -9 -4 -9 -10 0 -5 7 -10 15 -10 8 0 15 -4 15 -9 0 -16 57 -40 68 -29 6 6 15 2 24 -11 10 -14 21 -18 36 -14 27 7 27 12 5 30 -16 12 -15 13 7 2 13 -7 33 -23 43 -36 10 -12 25 -23 33 -23 8 0 14 -4 14 -10 0 -5 6 -10 14 -10 7 0 16 -9 19 -20 3 -11 1 -20 -4 -20 -5 0 -9 -9 -9 -20 0 -11 5 -20 10 -20 6 0 10 8 10 18 0 14 2 14 9 3 5 -8 16 -11 24 -8 12 4 20 -7 32 -44 16 -47 35 -66 35 -33 0 9 -5 12 -12 8 -10 -6 -10 -4 0 8 7 8 9 24 6 34 -5 13 -4 16 4 9 5 -5 12 -19 14 -30 2 -11 10 -20 18 -20 15 0 31 -21 50 -65 5 -14 17 -37 25 -51 8 -14 11 -35 8 -47 -4 -18 -1 -22 16 -22 11 0 21 5 21 11 0 5 -5 7 -11 4 -6 -4 -5 2 3 14 13 21 14 20 67 -34 29 -30 57 -55 61 -55 15 0 19 14 9 27 -9 9 -8 13 0 13 6 0 12 10 12 23 1 16 2 18 6 5 5 -21 12 -22 36 -4 19 15 23 36 5 36 -6 0 -9 3 -5 6 10 10 60 -47 87 -99 13 -26 28 -47 32 -47 14 0 9 31 -9 61 -15 25 -16 31 -4 38 19 12 33 5 50 -22 14 -21 13 -21 -5 -7 -10 8 -22 20 -26 25 -5 6 -8 6 -8 -2 0 -21 51 -64 83 -70 41 -8 100 -58 136 -115 32 -50 85 -98 109 -98 9 0 30 -14 46 -30 28 -29 56 -39 56 -21 0 15 -79 81 -98 81 -13 0 -14 2 -3 9 10 7 7 16 -18 41 -17 18 -31 40 -30 49 0 12 3 11 9 -4 8 -19 9 -19 9 3 1 14 7 22 19 22 10 0 13 -3 6 -8 -14 -10 -26 -42 -14 -42 5 0 11 8 13 18 4 13 5 11 6 -5 1 -13 7 -23 16 -23 8 0 15 -5 15 -11 0 -6 14 -9 33 -7 27 2 36 -2 55 -29 12 -18 31 -33 41 -33 10 0 30 -9 44 -20 14 -11 33 -20 43 -20 11 0 38 -8 61 -17 32 -14 43 -24 45 -43 2 -14 10 -26 20 -28 15 -3 17 2 12 27 -6 28 -4 31 20 31 15 0 29 -7 32 -15 7 -17 34 -21 34 -5 0 7 6 7 19 0 23 -12 61 -13 61 -2 0 4 -5 13 -12 20 -9 9 -9 15 0 24 8 8 16 6 30 -12 14 -17 32 -24 72 -28 55 -5 80 -19 80 -45 0 -11 24 -15 108 -21 110 -6 202 0 202 15 0 14 86 21 125 10 29 -8 41 -8 46 1 5 9 15 4 29 -15 12 -15 25 -25 30 -22 4 3 6 -4 3 -15 -3 -12 0 -20 7 -20 8 0 10 11 5 38 -6 37 -4 39 32 58 21 10 41 23 44 28 4 5 25 6 47 3 29 -3 42 -1 46 8 7 18 79 32 84 16 5 -15 27 -14 53 2 17 10 23 10 26 0 3 -7 9 -13 14 -13 6 0 5 8 -1 20 -9 18 -7 23 19 38 44 24 41 52 -5 52 -19 0 -44 5 -55 11 -32 17 -79 -9 -79 -43 0 -31 -32 -58 -61 -51 -11 3 -19 0 -19 -6 0 -7 6 -9 13 -5 6 4 8 3 4 -1 -4 -5 -28 -8 -52 -6 -25 1 -45 -2 -45 -7 0 -5 -18 -14 -40 -21 -33 -10 -40 -16 -40 -36 0 -27 -15 -34 -23 -12 -4 10 -28 15 -79 17 -115 5 -150 1 -168 -15 -10 -9 -37 -17 -61 -18 -38 -2 -44 1 -41 17 2 11 -1 16 -10 13 -7 -2 -12 -9 -11 -13 1 -5 -16 -8 -38 -6 -21 2 -39 8 -39 12 0 5 -18 11 -40 15 -42 7 -48 13 -28 33 21 21 -2 27 -36 8 -25 -13 -41 -15 -66 -9 -35 9 -54 33 -26 33 9 0 16 5 16 10 0 6 12 10 26 10 19 0 25 4 20 15 -4 10 1 15 14 15 11 0 20 3 20 8 -1 13 -71 52 -95 52 -13 0 -27 5 -30 10 -12 20 -25 9 -25 -21 0 -30 1 -31 40 -24 26 4 40 3 40 -4 0 -6 -19 -11 -44 -11 -40 0 -43 -2 -43 -25 0 -32 -11 -44 -23 -25 -8 12 -11 13 -22 2 -11 -11 -8 -18 17 -38 32 -25 24 -34 -10 -11 -11 8 -43 15 -72 16 -42 2 -52 -1 -56 -16 -4 -13 -5 -14 -6 -2 0 8 -13 20 -28 25 -23 8 -17 10 39 9 52 0 73 5 94 21 42 31 41 44 -1 44 -29 0 -36 -3 -32 -15 9 -22 -12 -29 -32 -11 -21 19 -41 21 -41 4 -1 -7 -9 9 -19 37 -22 62 -51 74 -51 21 0 -46 -21 -48 -38 -3 -10 27 -9 29 2 15 7 -10 16 -18 18 -18 10 0 19 66 12 84 -8 20 -24 21 -24 0 0 -9 5 -12 12 -8 7 4 8 3 4 -4 -4 -6 -14 -8 -23 -5 -12 5 -14 3 -8 -8 5 -8 4 -11 0 -6 -13 12 -15 41 -3 48 12 8 2 29 -14 29 -5 0 -8 -7 -4 -15 7 -20 -1 -19 -31 5 -29 23 -53 26 -53 8 0 -7 -5 -5 -11 5 -10 17 -29 23 -29 9 0 -5 9 -18 21 -31 25 -27 19 -37 -11 -21 -12 6 -24 9 -27 6 -12 -11 7 -34 32 -38 22 -5 29 -1 39 23 l12 28 28 -24 c18 -15 23 -25 15 -25 -8 0 -20 5 -27 12 -17 17 -43 -20 -36 -52 9 -43 58 -68 61 -31 1 12 -10 25 -30 35 -18 8 -27 16 -22 16 6 1 22 3 36 5 22 3 28 -3 45 -41 14 -33 25 -44 42 -44 19 0 22 5 22 37 0 45 12 35 33 -27 14 -40 14 -45 0 -48 -9 -2 -18 1 -22 6 -3 6 -20 12 -36 14 -19 2 -33 11 -40 26 -12 26 -22 29 -22 5 0 -10 7 -23 16 -30 9 -7 12 -12 6 -12 -5 0 -19 6 -29 14 -11 8 -28 15 -38 15 -10 0 -30 18 -44 40 -15 22 -31 37 -37 33 -6 -3 -7 -1 -3 5 4 7 2 12 -3 12 -6 0 -11 9 -11 20 0 23 -32 43 -54 34 -12 -4 -15 -2 -10 9 8 21 -17 33 -28 13 -6 -11 -17 -14 -34 -10 -16 4 -24 2 -24 -7 0 -10 -3 -10 -12 -1 -18 18 -41 15 -34 -4 6 -15 4 -15 -11 -3 -10 7 -29 23 -43 35 -14 12 -43 25 -65 29 l-40 8 33 10 c34 10 39 32 8 32 -10 0 -22 8 -27 18 -6 9 -16 17 -23 17 -15 0 -76 56 -76 70 0 6 -4 10 -10 10 -5 0 -10 -6 -10 -14 0 -22 -24 -38 -38 -24 -9 9 -16 7 -31 -6 -19 -17 -20 -17 -40 3 -12 12 -28 21 -36 21 -8 0 -15 3 -15 8 -1 4 -10 18 -20 31 -16 18 -23 21 -34 12 -11 -9 -15 -7 -20 12 -4 18 -13 24 -31 25 -20 0 -25 -5 -25 -27 l0 -26 -15 25 c-26 46 -29 54 -17 58 21 7 13 20 -13 20 -14 0 -25 -6 -26 -12 -1 -6 -4 0 -8 14 -8 30 -41 40 -41 13 -1 -11 -6 -6 -15 15 -15 33 -30 41 -38 20 -2 -7 -8 1 -12 17 -12 52 -15 57 -29 52 -8 -3 -17 1 -20 9 -3 8 -12 14 -20 14 -8 0 -21 8 -28 18 -18 26 -88 58 -96 45 -16 -26 -82 -11 -82 18 0 10 -4 20 -9 23 -11 7 -25 83 -22 118 1 18 -6 36 -23 53 -28 28 -36 31 -36 12 0 -7 9 -18 20 -25 21 -13 28 -52 9 -52 -6 0 -8 7 -5 16 8 20 -40 68 -60 60 -8 -3 -14 1 -14 9 0 8 -6 15 -14 15 -8 0 -16 6 -19 13 -4 10 -7 10 -18 0 -24 -24 -49 -15 -65 23 -12 28 -19 35 -35 31 -16 -4 -21 1 -26 24 -3 16 -12 29 -19 29 -9 0 -14 11 -14 29 0 21 -11 39 -35 62 -19 19 -35 41 -35 50 0 20 -32 79 -42 79 -5 0 -8 7 -8 15 0 8 -4 15 -10 15 -5 0 -7 7 -4 15 4 9 0 15 -9 15 -8 0 -17 -7 -21 -15 -9 -24 -22 -17 -21 12 0 32 -21 42 -30 14 -6 -18 -8 -19 -21 -7 -8 8 -14 22 -14 30 0 9 -8 16 -17 16 -15 0 -16 2 -3 10 10 6 17 5 23 -5 20 -36 57 8 41 49 -8 22 -25 20 -31 -3 -4 -17 -8 -18 -24 -8 -10 6 -19 17 -19 24 0 7 -9 17 -20 23 -11 6 -20 7 -20 1z"/> <path d="M4333 2424 c-9 -14 -27 -30 -40 -35 -13 -5 -23 -14 -23 -21 0 -7 -26 -30 -58 -50 -50 -32 -184 -135 -266 -204 -15 -13 -29 -24 -31 -24 -4 0 -55 -43 -110 -92 -23 -21 -46 -38 -50 -38 -5 0 -31 -17 -59 -38 -28 -21 -61 -45 -73 -53 -60 -39 -221 -167 -242 -193 -14 -15 -29 -33 -35 -40 -20 -21 -56 -75 -56 -83 0 -4 -9 -19 -20 -33 -11 -14 -20 -39 -20 -56 0 -39 -53 -102 -114 -134 -24 -14 -49 -35 -55 -47 -6 -13 -15 -23 -20 -23 -10 0 -4 -81 10 -130 14 -45 -9 -138 -41 -172 -12 -12 -30 -39 -41 -58 -10 -19 -34 -53 -54 -74 -20 -22 -39 -52 -42 -68 -3 -15 -9 -28 -14 -28 -14 0 -11 -36 6 -67 9 -15 20 -40 25 -55 19 -55 80 -19 65 39 -8 33 9 52 55 59 36 6 38 8 56 70 10 35 21 64 25 64 3 0 18 11 33 25 29 27 35 71 11 89 -13 9 -11 18 17 61 27 40 40 51 73 57 21 5 50 18 62 30 24 22 31 62 13 73 -18 11 -10 35 12 35 27 0 108 83 108 112 0 12 19 45 43 75 23 30 62 84 87 121 25 37 55 71 68 77 12 5 22 15 22 22 0 7 5 13 11 13 7 0 34 23 61 52 26 28 58 57 71 64 43 24 110 54 121 54 21 0 36 -23 36 -58 0 -29 3 -33 21 -27 11 4 37 25 57 47 19 22 54 49 76 60 22 11 56 38 76 59 20 22 40 39 45 39 18 0 84 35 85 45 0 6 13 18 29 28 26 15 30 25 38 85 10 85 10 308 0 345 -9 34 -31 35 -54 1z m54 -92 c5 -74 -10 -271 -22 -304 -4 -9 -15 -18 -26 -21 -11 -3 -23 -15 -26 -26 -3 -12 -11 -21 -19 -21 -24 0 -88 -39 -124 -76 -19 -20 -51 -44 -70 -54 -19 -10 -53 -37 -75 -59 -46 -48 -55 -50 -55 -15 0 41 -18 64 -50 64 -16 0 -31 -4 -34 -9 -4 -5 -27 -20 -54 -32 -26 -13 -73 -49 -104 -81 -32 -32 -62 -58 -68 -58 -5 0 -10 -7 -10 -15 0 -8 -6 -15 -13 -15 -16 0 -58 -45 -77 -84 -8 -16 -27 -42 -42 -59 -16 -16 -28 -33 -28 -38 0 -5 -9 -14 -20 -21 -11 -7 -20 -18 -20 -25 0 -7 -4 -13 -10 -13 -5 0 -10 -13 -10 -30 0 -16 -4 -30 -10 -30 -5 0 -10 -6 -10 -13 0 -22 -53 -65 -85 -69 -24 -2 -31 -8 -33 -31 -2 -18 2 -29 12 -33 9 -3 16 -11 16 -18 0 -14 -61 -56 -82 -56 -24 0 -67 -39 -88 -81 -24 -46 -25 -65 -5 -77 21 -11 10 -35 -29 -66 -27 -20 -35 -36 -46 -85 -11 -53 -16 -61 -36 -61 -13 0 -35 -5 -49 -12 -21 -9 -26 -18 -24 -42 3 -40 -10 -78 -24 -73 -7 2 -16 20 -22 40 -6 20 -16 42 -23 49 -14 14 -16 38 -3 38 5 0 11 13 14 28 3 15 20 43 37 62 17 19 47 59 66 89 20 30 42 60 49 67 19 20 38 110 30 147 -25 122 -11 172 58 203 21 10 59 41 83 68 36 41 44 56 40 78 -3 15 -2 30 3 32 5 3 16 20 24 38 39 82 193 230 340 327 12 8 45 32 73 53 28 21 54 38 59 38 4 0 27 17 50 38 74 66 107 92 116 92 5 0 9 4 9 8 0 5 30 30 68 57 37 26 83 62 102 80 34 31 45 38 123 91 21 14 59 47 85 73 56 57 62 52 69 -57z"/> <path d="M4310 1779 c-14 -17 -37 -45 -52 -61 -16 -16 -28 -40 -28 -53 0 -23 4 -25 45 -25 31 0 51 6 64 19 22 22 41 80 41 124 0 39 -37 37 -70 -4z"/> <path d="M4275 1403 c-3 -16 -10 -41 -15 -58 -53 -181 -102 -470 -106 -625 -1 -36 -6 -83 -12 -105 -11 -41 -20 -149 -27 -310 -2 -50 -7 -139 -10 -200 -3 -60 -4 -107 -1 -104 6 6 18 152 21 259 4 136 16 287 28 340 6 30 12 82 12 115 2 65 32 324 40 348 3 7 19 70 35 138 37 161 47 200 53 205 2 2 7 -76 10 -173 5 -160 15 -238 46 -375 34 -149 48 -197 92 -320 27 -75 49 -140 49 -144 0 -11 130 -235 157 -270 12 -17 23 -34 23 -39 0 -10 62 -87 66 -82 2 2 -26 51 -64 108 -141 216 -179 297 -259 554 -26 86 -35 119 -53 205 -33 160 -42 230 -47 388 -5 134 -9 172 -19 172 -8 0 -16 -12 -19 -27z"/> </g> </svg> </div> ); export default Face; <filename>src/feedbacks.js const colorsys = require('colorsys'); module.exports = { // ########################## // #### Define Feedbacks #### // ########################## setFeedbacks: function (i) { var self = i var feedbacks = {} const foregroundColor = self.rgb(255, 255, 255) // White const backgroundColorRed = self.rgb(255, 0, 0) // Red const backgroundColorGreen = self.rgb(0, 255, 0) // Green const backgroundColorOrange = self.rgb(255, 102, 0) // Orange feedbacks.powerState = { type: 'boolean', label: 'Power State', description: 'Indicate if Bulb is On or Off', style: { color: foregroundColor, bgcolor: backgroundColorRed, }, options: [ { type: 'dropdown', label: 'Indicate in X State', id: 'option', default: 1, choices: [ { id: 0, label: 'Off' }, { id: 1, label: 'On' }, ], }, ], callback: function (feedback, bank) { var opt = feedback.options if (self.BULBINFO.light_state) { if (self.BULBINFO.light_state.on_off === opt.option) { return true; } } return false } } feedbacks.color = { type: 'advanced', label: 'Show Bulb Color', description: 'Show the current bulb color on the button', callback: function (feedback, bank) { var opt = feedback.options if ('hue"' in self.BULBINFO.light_state) { let rgb = colorsys.hsv2Rgb(self.BULBINFO.light_state.hue, self.BULBINFO.light_state.saturation, self.BULBINFO.light_state.brightness) return { bgcolor: self.rgb(rgb.r, rgb.g, rgb.b) } } return false } } return feedbacks } } // importa a row import Row from './Row'; // exporta a row por padrão export default Row;<filename>src/js/plugins/body-parse.js<gh_stars>1-10 /* * Copyright 2020 Phara0h * Changes are the diff from uWebSockets.js v17.4.0 (commit 116a85f9668dcb03e7799db06dc8275bc43c0963) * to this file. * * 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 = async (req, res) => { return new Promise((resolve, reject) => { const headers = req.headers; const contentType = headers['Content-Type'] || headers['content-type']; res.finished = false; res.onAborted(() => { res.finished = true; resolve(); }); var buffer; res.onData((bytes, isLast) => { // no longer have access to native req functions in this scope?? const chunk = Buffer.from(bytes); if (isLast) { if (!buffer) { buffer = chunk; } if(contentType === 'application/json') { req.body = JSON.parse(buffer.toString()); } else if(contentType === 'text/plain'){ req.body = buffer.toString(); } else { req.body = buffer; } if (!res.finished) { resolve(); } } else { if (buffer) { buffer = Buffer.concat([buffer, chunk]); } else { buffer = chunk; } } }); }); }; var Ref_8h = [ [ "klee::ReferenceCounter", "classklee_1_1ReferenceCounter.html", "classklee_1_1ReferenceCounter" ], [ "klee::ref< T >", "classklee_1_1ref.html", "classklee_1_1ref" ], [ "llvm::simplify_type< const ::klee::ref< T > >", "structllvm_1_1simplify__type_3_01const_01_1_1klee_1_1ref_3_01T_01_4_01_4.html", "structllvm_1_1simplify__type_3_01const_01_1_1klee_1_1ref_3_01T_01_4_01_4" ], [ "llvm::simplify_type< ::klee::ref< T > >", "structllvm_1_1simplify__type_3_01_1_1klee_1_1ref_3_01T_01_4_01_4.html", null ], [ "operator<<", "Ref_8h.html#abfaec138df8a280202e13c413e1a4884", null ], [ "operator<<", "Ref_8h.html#a0318472ba3f66035b26aa03fbccc5152", null ] ];/** * 数据结构:数字 * 算法:循环 */ /** * @param {number} n * @return {boolean} */ function isPowerOfTwo(n) { if (n <= 0) { return false; } var sum = 0; for (var i = 0; i < 32; i++) { sum += (n >> i) & 1; if (sum > 1) { return false; } } return true; }; export default isPowerOfTwo;import React, { useState } from "react" import CookieConsent from "react-cookie-consent" // import { Link } from "gatsby" // import Layout from "../components/layout" // import Image from "../components/image" import HeaderLegalPage from "../components/header_legalpage" import Footer from "../components/footer" //import SEO from "../components/seo" import "semantic-ui-css/semantic.min.css" import "../styles/index.scss" const IndexPage = () => { let [menuActive, setmenuActive] = useState(false) const toggleMenu = () => { setmenuActive(!menuActive) } return ( <div className="pageWrap"> {/* <SEO title="Home" /> */} <HeaderLegalPage toggleMenu={toggleMenu} menuState={menuActive} /> <div className="legalInfo-div"> <h1>Privacy Policy</h1> <h2>Privacy Notice</h2> <p> We want to give you an amazing browsing experience on our website. For us, an amazing experience means at the same time, to protect your personal data in the best way we can. In order to achieve that, we want to be as transparent as possible and give you the chance to see how, why and where we process your data. This policy gives you an overview of: what information we keep on file, how long we intend to keep your information, why we are keeping your information, what your rights are as a data subject, who the data controller is, where you can file a complaint and if we share your information with third parties. </p> <p> All information will be processed by the Data Controller: <br /> Delivery Hero SE <br /> Oranienburger Straße 70 <br /> 10117 Berlin <br /> If you require additional information or have any concerns about the processing of your personal data please contact us by email at: <EMAIL> </p> <h2>Categories of personal data:</h2> <p> When you browse our website, we also automatically receive your computer’s internet protocol (IP) address in order to provide us with information that helps us learn about your browser and operating system. We also use cookies or similar technologies to collect extra data, including: </p> <ul> <li> your IP address - a numerical code to identify your device, together with the country, region or city where you are based </li> <li> your geolocation data - your IP address can be used to find information about the latitude, longitude, altitude of your device, its direction of travel, your GPS data and data about connection with local Wi-Fi equipment </li> <li>information on how you interact with our services</li> <li> your browsing history of the content you have visited on our sites, including how you were referred to our sites via other websites </li> <li> details of your computer, unique vendor or advertising ID and browsers used to access our content </li> </ul> <h2>Legal basis</h2> <p> Our legitimate interest: where it is necessary for us to understand our visitors and operate our sites efficiently. Examples of when we rely on legitimate interests to use your personal data include: </p> <ul> <li> to collect and log IP addresses to improve the website and monitor website usage </li> <li> for security and fraud prevention, and to ensure that our sites and apps are safe and secure and used in line with our terms of use </li> </ul> <h2>Service providers</h2> <p> We use different data processors in our daily processing. These process your personal data in accordance with the requirements of Art. 28 GDPR only according to our instructions and have no claims whatsoever on these data. We also monitor our processors and include only those who meet our high standards. </p> <p> Because we use different data processors and change them from time to time, it is not appropriate to identify specific recipients of personal information. However, if you are interested, we will be happy to disclose the name of the processor(s) in use at that time upon request. </p> <h2>Processing in third countries</h2> <p> We process your data mainly within the European Union (EU) and the European Economic Area (EEA). However, some of our service providers mentioned above are based outside the EU and the EEA. </p> <p> Before we transfer your personal data to any third parties, we carefully assess if these companies have adequate security measures in place and if they meet the requirements outlined by GDPR. </p> <p> Only if they can demonstrate an adequate level of data protection will they be shortlisted for service providers. </p> <p> Regardless of whether our service providers are located within the EU/EEA or in third countries, each service provider must sign a data processing agreement with us. Service providers outside the EU/EEA must meet additional requirements. According to Art. 44 ff. GDPR personal data may be transferred to service providers that meet at least one of the following requirements: </p> <ol> <li> Commission has decided that the third country ensures an adequate level of protection (e.g. Israel and Canada) </li> <li>Standard data protection clauses adopted.</li> </ol> <p> These are contractual clauses which cannot be modified by the contracting parties and in which they undertake to ensure an adequate level of data protection. </p> <h1>Retention Period</h1> <p> In order to be able to reply to enquiries made through our website, we will need to store your data. We will not keep your data for a longer period that is needed for the purpose of processing and to comply with applicable law. </p> <h2>Data subjects’ rights</h2> <h3>Right to access</h3> <p> You have the right to be informed which data we store about you and how we process this data. </p> <h3>Right to rectification</h3> <p> If you notice that stored data is incorrect, you can always ask us to correct it. </p> <h3>Right to erasure</h3> <p> You can ask us at any time to delete the data we have stored about you. </p> <h3>Right to object to the processing of your data</h3> <p> You can revoke your consent at any time or object to the further processing of your data. This also includes objecting to our processing, which we process without your consent but based on our legitimate interest. </p> <p> If you do not agree with one of our processing purposes based on our legitimate interest or wish to object to it, you may object to the processing at any time on grounds relating to the particular situation. Please fill in the contact form on our website stating your concerns in the comments. In this case we will review the processing activity again and either stop processing your data for this purpose or explain to you our reasons worth protecting and why we will continue with the processing. </p> <h3>Right of complaint</h3> <p> If you believe that we have done something wrong with your personal data or your rights, you can complain to the appropriate supervisory authority at any time. </p> <p> To exercise your rights, you can contact <EMAIL> at any time. </p> <p> The responsible supervisory authority for Delivery Hero is: <br /> Berliner Beauftragte für Datenschutz und Informationsfreiheit <br /> Friedrichstr. 219 <br /> 10969 Berlin <br /> E-Mail: <EMAIL> </p> <p> You can also send your complaint to the supervisory authority in your habitual residence or place of work. </p> <p> If you would like to exercise your rights as a data subject, please do not hesitate to contact us under the contact information provided above. </p> <h3>Automated decision-making</h3> <p> We do not have any processes where decisions are made in an automated way having a legal effect or similar effects on you. </p> <h2>Cookie Information</h2> <p> In order for your visit to Just Thai website to be attractive and to enable the use of certain functions, we use the so-called cookies on various pages. Cookies are small text files that are stored in your browser. Some of the cookies we use are deleted after the end of the operation period of your browser, eg. after the closing of the browser. Other cookies remain in your browser and allow us to identify your browser on your next visit (permanent cookies). You can configure your browser so that you are informed about the setting of cookies and decide individually on their acceptance or deviation for specific cases or in general. Non-acceptance of cookies may limit the functionality of our website. </p> <p>We classify the cookies in three categories:</p> <ul> <li>Necessary</li> <li>Functionality</li> <li>Personalization</li> </ul> <p> We are only using Necessary cookies that are required to navigate our site and use its features. Without the use of these cookies, the proper functioning of our website is not guaranteed (eg entering text) while browsing the pages of the website. In addition, they are cookies that collect information about how visitors use our site, for example, which pages they visit most often and if they receive error messages. They also let our site remember your choices, such as language or region, to provide enhanced features. They are also used to store information about the consent option where required. No action is required from you to activate them. </p> <h2>Changes to this Privacy Notice</h2> <p> We reserve the right to modify this privacy notice at any time, so please review it frequently. Changes and clarifications will take effect immediately upon their posting on the website. If we make material changes to this policy, we will notify you here that it has been updated, so that you are aware of what information we collect, how we use it, and under what circumstances, if any, we use and/or disclose it. </p> <h2>Questions and Contact Information</h2> <p> If you would like to: access, correct, amend or delete any personal information we have about you, register a complaint, or simply want more information, please fill out the contact form on the website to get in touch with us. </p> </div> <Footer /> <CookieConsent location="bottom" buttonText="I AGREE" cookieName="myAwesomeCookieName2" style={{ background: "#2B373B" }} buttonStyle={{ color: "#4e503b", fontSize: "13px" }} expires={150} // debug={true} > <span className="cookie_consent"> We use cookies needed to run the website and for analytical purposes.{" "} <a href="/"> More information </a> </span> </CookieConsent> </div> ) } export default IndexPage const express = require('express'); const router = express.Router(); const { db } = require('../../db.js'); router.post('/api/filter/eso-hour-readings', (req, res) => { let { search, start, length, order, fromDate, toDate, client_name, ident_code, type } = req.body; const columnNum = order[0].column; const columnType = getColumnType(columnNum, 'readings') const orderType = order[0].dir; let sql = `SELECT clients.id as cId, hour_readings_eso.id, hour_readings_eso.date, clients.client_name, clients.ident_code, hour_readings_eso.type FROM hour_readings_eso INNER JOIN clients ON clients.id = hour_readings_eso.client_id WHERE 1 = 1 `; let countTotalSql = `SELECT COUNT(hour_readings_eso.id) as countTotal FROM hour_readings_eso INNER JOIN clients ON clients.id = hour_readings_eso.client_id WHERE 1 = 1 `; let countFilteredSql = `SELECT COUNT(hour_readings_eso.id) as countFiltered FROM hour_readings_eso INNER JOIN clients ON clients.id = hour_readings_eso.client_id WHERE 1 = 1 `; if (client_name != '' && client_name != undefined) { sql += ` AND clients.client_name LIKE '%${client_name}%'`; countFilteredSql += ` AND clients.client_name LIKE '%${client_name}%'`; } if (ident_code != '' && ident_code != undefined) { sql += ` AND clients.ident_code = '${ident_code}'`; countFilteredSql += ` AND clients.ident_code = '${ident_code}'`; } if (fromDate != '' && fromDate != undefined && toDate != '' && toDate != undefined) { sql += ` AND hour_readings_eso.date >= '${fromDate}' AND hour_readings_eso.date <= '${toDate}' `; countFilteredSql += ` AND hour_readings_eso.date >= '${fromDate}' AND hour_readings_eso.date <= '${toDate}' `; } else if (fromDate != '' && fromDate != undefined && (toDate == '' || toDate == undefined)) { sql += ` AND hour_readings_eso.date >= '${fromDate}' `; countFilteredSql += ` AND hour_readings_eso.date >= '${fromDate}' `; } else if (toDate != '' && toDate != undefined && (fromDate == '' || fromDate == undefined)) { sql += ` AND hour_readings_eso.date <= '${toDate}' `; countFilteredSql += ` AND hour_readings_eso.date <= '${toDate}' `; } if (type && type.length === 1) { sql += ` AND hour_readings_eso.type = '${type}'`; countFilteredSql += ` AND hour_readings_eso.type = '${type}' `; } else if (type == undefined) { return res.send(JSON.stringify([])); } if (search.value) { sql += ` AND (hour_readings_eso.date = '%${search.value}%' OR clients.ident_code LIKE '%${search.value}%' OR clients.client_name LIKE '%${search.value}%' ) ` countFilteredSql += ` AND (hour_readings_eso.date = '%${search.value}%' OR clients.ident_code LIKE '%${search.value}%' OR clients.client_name LIKE '%${search.value}%' ) ` } sql += ` ORDER BY ${columnType} ${orderType}`; sql += ` LIMIT ${start},${length}`; const countSQL = countTotalSql + ' UNION ' + countFilteredSql; db.query(countSQL, (err, countTotal) => { if (err) { throw err; } db.query(sql, (err, result) => { if (err) { throw err; } const recordsTotal = countTotal[0].countTotal; const recordsFiltered = countTotal[1] ? countTotal[1].countTotal : countTotal[0].countTotal let arr = { recordsTotal, recordsFiltered, data: result } return res.send(JSON.stringify(arr)); }) }); }); router.post('/api/filter/eso-graph-readings', (req, res) => { let { search, start, length, order, fromDate, toDate, client_name, ident_code, } = req.body; const columnNum = order[0].column; const columnType = getColumnType(columnNum, 'graphs') const orderType = order[0].dir; let sql = `SELECT clients.id as cId, hour_prediction_eso.id, hour_prediction_eso.date, clients.client_name, clients.ident_code FROM hour_prediction_eso INNER JOIN clients ON clients.id = hour_prediction_eso.client_id WHERE 1 = 1 `; let countTotalSql = `SELECT COUNT(hour_prediction_eso.id) as countTotal FROM hour_prediction_eso INNER JOIN clients ON clients.id = hour_prediction_eso.client_id WHERE 1 = 1 `; let countFilteredSql = `SELECT COUNT(hour_prediction_eso.id) as countFiltered FROM hour_prediction_eso INNER JOIN clients ON clients.id = hour_prediction_eso.client_id WHERE 1 = 1 `; if (client_name != '' && client_name != undefined) { sql += ` AND clients.client_name LIKE '%${client_name}%'`; countFilteredSql += ` AND clients.client_name LIKE '%${client_name}%'`; } if (ident_code != '' && ident_code != undefined) { sql += ` AND clients.ident_code = '${ident_code}'`; countFilteredSql += ` AND clients.ident_code = '${ident_code}'`; } if (fromDate != '' && fromDate != undefined && toDate != '' && toDate != undefined) { sql += ` AND hour_prediction_eso.date >= '${fromDate}' AND hour_prediction_eso.date <= '${toDate}' `; countFilteredSql += ` AND hour_prediction_eso.date >= '${fromDate}' AND hour_prediction_eso.date <= '${toDate}' `; } else if (fromDate != '' && fromDate != undefined && (toDate == '' || toDate == undefined)) { sql += ` AND hour_prediction_eso.date >= '${fromDate}' `; countFilteredSql += ` AND hour_prediction_eso.date >= '${fromDate}' `; } else if (toDate != '' && toDate != undefined && (fromDate == '' || fromDate == undefined)) { sql += ` AND hour_prediction_eso.date <= '${toDate}' `; countFilteredSql += ` AND hour_prediction_eso.date <= '${toDate}' `; } if (search.value) { sql += ` AND (hour_prediction_eso.date = '%${search.value}%' OR clients.ident_code LIKE '%${search.value}%' OR clients.client_name LIKE '%${search.value}%' ) ` countFilteredSql += ` AND (hour_prediction_eso.date = '%${search.value}%' OR clients.ident_code LIKE '%${search.value}%' OR clients.client_name LIKE '%${search.value}%' ) ` } sql += ` ORDER BY ${columnType} ${orderType}`; sql += ` LIMIT ${start},${length}`; const countSQL = countTotalSql + ' UNION ' + countFilteredSql; db.query(countSQL, (err, countTotal) => { if (err) { throw err; } db.query(sql, (err, result) => { if (err) { throw err; } const recordsTotal = countTotal[0].countTotal; const recordsFiltered = countTotal[1] ? countTotal[1].countTotal : countTotal[0].countTotal let arr = { recordsTotal, recordsFiltered, data: result } return res.send(JSON.stringify(arr)); }) }); }); function getColumnType(columnNum, type) { let table; const clientsTable = 'clients'; if (type == 'graphs') { table = 'hour_prediction_eso'; } else if (type == 'readings') { table = 'hour_readings_eso'; } let result = `${table}.id`; switch (columnNum) { case '0': result = `${table}.id`; break; case '1': result = `${clientsTable}.ident_code`; break; case '2': result = `${clientsTable}.client_name`; break; case '3': result = `${table}.date`; break; case '4': result = `${table}.type`; break; } return result } module.exports = router;function getAttribute(name,m){return coiatr$(this,name,m);} import React, {Component} from 'react'; import { API } from 'aws-amplify'; import {listTodos} from '../../graphql/queries'; import SearchForm from './function'; import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/css/bootstrap.css'; import Col from 'react-bootstrap/Col'; import Container from 'react-bootstrap/Container'; import Row from 'react-bootstrap/Row'; import Button from 'react-bootstrap/Button'; import './style.css'; import "../../App.css"; import SearchCard from '../Card/search'; class Results extends Component { state = { search: "", listings: [], listingSort: [], order: "", searchLength: false }; async componentDidMount() { try{ // var notesFromAPI= await API.graphql({ query: listTodos }) const locationInfo = await API.graphql({ query: listTodos }) const notesFromAPI = locationInfo.data.listTodos.items; this.setState({ listings: notesFromAPI, listingSort: notesFromAPI }) }catch (err){ console.log(err)} } sortByName = () => { const filtereds = this.state.listingSort; if (this.state.order === "ascending") { const sortFunction = filtereds.sort((a, b) => (a.date > b.date) ? 1 : -1) console.log(sortFunction) this.setState({ listingSort: sortFunction, order: "descending" }) } else { const sortFunction = filtereds.sort((a, b) => (a.date > b.date) ? -1 : 1) this.setState({ listingSort: sortFunction, order: "ascending" }) } } render() { return ( <div> <Container fluid className="search-bkg"> <div style={{ textAlign: 'center' }}> <h2> Listings </h2> <h3><SearchForm id={this.state._id} listing={this.state.listings} handleSearch={this.handleSearch} handleInputChange={ this.handleInputChange } /></h3> </div> <div className="itemTable"> <Row> <Col > <Row> <thead className=""> <h2 className="hover-pointer heading" onClick={this.sortByName} > Sort by date</h2> </thead> </Row> {this.state.searchLength ? ( <Row className="justify-content-md-center"> {this.state.listingSort.map( (listing) => { return ( <Col xs={12} md={12}> <Row className="justify-content-md-center"> <SearchCard listingId={listing._id} title={ listing.businessName } street={ listing.businessAddress } city={listing.city} state={listing.state} modalButton={ <Button className="btn-custom" variant="custom"><a href={"/Update/" + listing._id}>View</a></Button> } /> </Row> </Col> ) } )} </Row> ) : ( <h3>No Results to Display</h3> )} {this.state.listings.length ? ( <tbody className=""> </tbody> ) : ( <h3>No Results to Display</h3> )} </Col> </Row> </div> </Container> </div> ); } handleInputChange = (event) => { const listings = this.state.listings; const UserInput = event.target.value; const listingSort = listings.filter( (listing) => listing.businessName .toLowerCase() .indexOf(UserInput.toLowerCase()) > -1 || listing.city .toLowerCase() .indexOf(UserInput.toLowerCase()) > -1 || listing.state .toLowerCase() .indexOf(UserInput.toLowerCase()) > -1 ); this.setState({ listingSort, }); this.setState({ searchLength: !event? false : true, }); }; listingSearch = () => { API.getListings() .then((res) => this.setState({ listingSort: res.data, listings: res.data, }) ) .catch((err) => console.log(err)); }; handleSearch = (event) => { event.preventDefault(); event.persist(); const { listings, search } = this.state; const userInput = event.target.value; console.log(event); const listingSort = listings.filter( (listing) => listing.businessName .toLowerCase() .includes(search.toLowerCase()) ); this.setState({ listingSort, }); }; } export default Results;<filename>lib/board/spec/SquareSpec.js // describe("Square", function() { // }); module.exports = { /** * Generates a string of random alphanumeric characters. * @param {number} length - The length the string should be. * @returns - The resulting string. */ randomString: function (length) { const acceptedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; let result = ""; for (let i = 0; i < length; i++) { result += acceptedChars.charAt(Math.floor(Math.random() * acceptedChars.length)); } return result; }, }'use strict'; const AWS = require('aws-sdk'); const moment = require('moment'); const CloudwatchEvents = require('@cumulus/aws-client/CloudwatchEvents'); const Lambda = require('@cumulus/aws-client/Lambda'); const awsServices = require('@cumulus/aws-client/services'); const SQSUtils = require('@cumulus/aws-client/SQS'); const StepFunctions = require('@cumulus/aws-client/StepFunctions'); const { deprecate } = require('@cumulus/common/util'); /** * getEndpoint returns proper AWS arguments for various * AWS classes to use. It is primarily intended for cases when * running an AWS service locally. For example, it sets the correct * endpoint for a dynamoDB table running locally and so on * * @param {boolean} [local] whether this is a local run * @param {number} [port=8000] port number defaults to 8000 * @returns {object} the options for AWS service classes */ function getEndpoint(local = false, port = 8000) { deprecate('@cumulus/ingest/aws/getEndpoint', '1.17.0'); const args = {}; if (process.env.IS_LOCAL === 'true' || local) { // use dummy access info AWS.config.update({ accessKeyId: 'myKeyId', secretAccessKey: 'secretKey', region: 'us-east-1' }); args.endpoint = new AWS.Endpoint(`http://localhost:${port}`); return args; } if (process.env.AWS_DEFAULT_REGION) { AWS.config.update({ region: process.env.AWS_DEFAULT_REGION }); } return args; } /** * Returns execution ARN from a statement machine Arn and executionName * * @param {string} executionArn - execution ARN * @returns {string} return aws console url for the execution */ function getExecutionUrl(executionArn) { deprecate('@cumulus/ingest/aws/getExecutionUrl', '1.17.0', '@cumulus/aws-client/StepFunctions.getExecutionUrl'); return StepFunctions.getExecutionUrl(executionArn); } function invoke(name, payload, type = 'Event') { deprecate('@cumulus/ingest/aws/invoke', '1.17.0', '@cumulus/aws-client/Lambda.invoke'); return Lambda.invoke(name, payload, type); } class CloudWatch { static cw() { deprecate('@cumulus/ingest/aws/CloudWatch.cw', '1.17.0'); return new AWS.CloudWatch(); } /** * Return the bucket size using information provided by the CloudWatch * * Example return object: * ``` * { * Timestamp: 2017-04-23T17:39:00.000Z, * Sum: 4809568606909, * Unit: 'Bytes', * bucket: 'cumulus-internal' * } * ``` * * @param {string} bucketName - Name of the bucket to get the size * @returns {Object} Retuns total storage for a given bucket */ static async bucketSize(bucketName) { deprecate('@cumulus/ingest/aws/CloudWatch.bucketSize', '1.17.0'); AWS.config.update({ region: process.env.AWS_DEFAULT_REGION }); const cw = this.cw(); const params = { EndTime: moment().unix(), MetricName: 'BucketSizeBytes', Namespace: 'AWS/S3', Period: 3600 * 24, // 24 hours StartTime: moment().subtract(5, 'day').unix(), Dimensions: [ { Name: 'BucketName', Value: bucketName }, { Name: 'StorageType', Value: 'StandardStorage' } ], Statistics: [ 'Sum' ] }; const response = await cw.getMetricStatistics(params).promise(); // return the latest number const sorted = response.Datapoints.sort((a, b) => { const time1 = moment(a.Timestamp).unix(); const time2 = moment(b.Timestamp).unix(); return time1 > time2 ? -1 : 1; }); sorted[0].bucket = bucketName; return sorted[0]; } } class ECS { static ecs(local) { deprecate('@cumulus/ingest/aws/ECS.ecs', '1.17.0'); return new AWS.ECS(getEndpoint(local, 9324)); } constructor(cluster) { deprecate('@cumulus/ingest/aws/ECS', '1.17.0'); this.cluster = cluster || process.env.ECS_CLUSTER; this.ecs = this.constructor.ecs(); } async describeCluster() { const params = { clusters: [this.cluster] }; return this.ecs.describeClusters(params).promise(); } async listServices() { const params = { cluster: this.cluster }; return this.ecs.listServices(params).promise(); } async describeServices(services) { const params = { services, cluster: this.cluster }; return this.ecs.describeServices(params).promise(); } async listInstances() { return this.ecs.listContainerInstances({ cluster: this.cluster }).promise(); } async describeInstances(instances) { const params = { cluster: this.cluster, containerInstances: instances }; return this.ecs.describeContainerInstances(params).promise(); } } class Events { static putEvent(name, schedule, state, description = null, role = null) { deprecate('@cumulus/ingest/aws/Events.putEvent', '1.17.0', '@cumulus/aws-client/CloudwatchEvents.putEvent'); return CloudwatchEvents.putEvent(name, schedule, state, description, role); } static deleteEvent(name) { deprecate('@cumulus/ingest/aws/Events.deleteEvent', '1.17.0', '@cumulus/aws-client/CloudwatchEvents.deleteEvent'); return CloudwatchEvents.deleteEvent(name); } static deleteTarget(id, rule) { deprecate('@cumulus/ingest/aws/Events.deleteTarget', '1.17.0', '@cumulus/aws-client/CloudwatchEvents.deleteTarget'); return CloudwatchEvents.deleteTarget(id, rule); } static putTarget(rule, id, arn, input) { deprecate('@cumulus/ingest/aws/Events.putTarget', '1.17.0', '@cumulus/aws-client/CloudwatchEvents.putTarget'); return CloudwatchEvents.putTarget(rule, id, arn, input); } } class SQS { static getUrl(name) { deprecate('@cumulus/ingest/aws/SQS.getUrl', '1.17.0', '@cumulus/aws-client/SQS.getQueueUrlByName'); return SQSUtils.getQueueUrlByName(name); } static deleteQueue(queueUrl) { deprecate('@cumulus/ingest/aws/SQS.deleteQueue', '1.17.0', '@cumulus/aws-client/SQS.deleteQueue'); return SQSUtils.deleteQueue(queueUrl); } static receiveMessage(queueUrl, numOfMessages = 1, timeout = 30) { deprecate('@cumulus/ingest/aws/SQS.receiveMessage', '1.17.0', '@cumulus/aws-client/SQS.receiveSQSMessages'); return SQSUtils.receiveSQSMessages(queueUrl, { numOfMessages, visibilityTimeout: timeout }); } static sendMessage(queueUrl, message) { deprecate('@cumulus/ingest/aws/SQS.sendMessage', '1.17.0', '@cumulus/aws-client/SQS.sendSQSMessage'); return SQSUtils.sendSQSMessage(queueUrl, message); } static deleteMessage(queueUrl, receiptHandle) { deprecate('@cumulus/ingest/aws/SQS.deleteMessage', '1.17.0', '@cumulus/aws-client/SQS.deleteSQSMessage'); return SQSUtils.deleteSQSMessage(queueUrl, receiptHandle); } static attributes(name) { deprecate('@cumulus/ingest/aws/SQS.attributes', '1.17.0', '@cumulus/aws-client/SQS.getQueueAttributes'); return SQSUtils.getQueueAttributes(name); } } class StepFunction { static async getExecutionStatus(executionArn) { deprecate('@cumulus/ingest/aws/StepFunction.getExecutionStatus', '1.17.0', '@cumulus/aws-client/StepFunction.getExecutionStatus'); return StepFunctions.getExecutionStatus(executionArn); } /** * Push an event to S3 if the length of the event is greater than 32000 bytes * * The event must have the following properties: * - resources.stack * - ingest_meta.execution_name * * @param {Object} event - an event to be pushed to S3 * @returns {Promise.<Object>} - a Promise that resoles to an Object with an * s3_path property indicating where the event was pushed to */ static pushEvent(event) { deprecate('@cumulus/ingest/aws/StepFunctions.pushEvent', '1.17.0'); const str = JSON.stringify(event); if (str.length <= 32000) return Promise.resolve(event); const stack = event.meta.stack; const name = event.cumulus_meta.execution_name; const key = `${stack}/payloads/${name}.json`; const bucket = event.cumulus_meta.system_bucket; return awsServices.s3().putObject({ Bucket: bucket, Key: key, Body: str }).promise() .then(() => ({ s3_path: `s3://${bucket}/${key}` })); } } module.exports = { CloudWatch, ECS, SQS, invoke, Events, StepFunction, getEndpoint, getExecutionUrl }; import PopupManager from './manager'; import { getZIndex } from './utils'; export default { props: { open: Boolean, overlay: { type: Boolean, default: true }, overlayClose: { type: Boolean, default: true }, overlayOpacity: { type: Number, default: 0.4 }, overlayColor: { type: String, default: '#000' }, escPressClose: { // 按退出键是否触发关闭事件 type: Boolean, default: true }, lockScroll: { // 是否锁定全局滚动 type: Boolean, default: false }, appendBody: { // 是否添加到 body 元素后, 内部使用 type: Boolean, default: true } }, data: function data() { return { overlayZIndex: getZIndex(), zIndex: getZIndex() }; }, methods: { overlayClick: function overlayClick(e) { if (!this.overlay || !this.overlayClose || !this.open) return; this.$emit('update:open', false); this.$emit('close', 'overlay'); }, escPress: function escPress(e) { if (!this.escPressClose || !this.open) return; this.$emit('update:open', false); this.$emit('close', 'esc'); }, resetZIndex: function resetZIndex() { this.overlayZIndex = getZIndex(); this.zIndex = getZIndex(); }, popupEl: function popupEl() { return this.$el; }, appendPopupElToBody: function appendPopupElToBody() { var _this = this; if (!this.appendBody || this.appened) return; this.$nextTick(function () { document.body.appendChild(_this.$el); _this.appened = true; }); } }, mounted: function mounted() { if (this.open) { PopupManager.open(this); this.appendPopupElToBody(); } }, beforeDestroy: function beforeDestroy() { PopupManager.close(this); if (this.appendBody) { if (!this.$el) return; if (this.$el.parentNode) this.$el.parentNode.removeChild(this.$el); } }, watch: { open: function open(val, oldVal) { if (val) { this.resetZIndex(); PopupManager.open(this); this.appendPopupElToBody(); } else { PopupManager.close(this); } } } };import styled from "styled-components"; import BlogItem from "./Item"; import BlogDate from "./Date"; import BlogTitle from "./Title"; const Blog = styled.div` display: grid; grid-template-columns: auto; grid-column: 3; grid-gap: 30px; list-style: none; `; Blog.Item = BlogItem; Blog.Date = BlogDate; Blog.Title = BlogTitle; export default Blog; <reponame>dipsywong98/reforml import { transparentize } from 'polished' import { mapObjIndexed } from 'ramda' export const midTransparentize = transparentize(0.6) export const highTransparentize = transparentize(0.75) export const vibrantColors = { blue: '#3976E9', red: '#E4456F', green: '#2AC87D', yellow: '#E99608', gray: '#9CC6E9' } export const dullColors = { blue: '#4168AE', red: '#925666', green: '#569276', yellow: '#D49E41', gray: '#8E959B' } export const paleColors = { blue: '#7ea6f1', red: '#ed86a1', green: '#74dbaa', yellow: '#f1bb5e', gray: '#bfdaf1' } export const baseColors = { ...vibrantColors, vibrantHighlights: mapObjIndexed(midTransparentize, vibrantColors), dark: ['#282c30', '#383e43', '#484f56'], light: ['#E0E3E5', '#c0c2c4', '#a0a1a3'], white: ['#f9fbfc', '#f0f2f3', '#e8ebec'] } export const colors = { ...baseColors, primary: baseColors.blue, accent: baseColors.yellow, inputFocus: transparentize(0.2, baseColors.blue) } export const light = { ...colors, blue: [colors.blue, dullColors.blue], red: [colors.red, dullColors.red], green: [colors.green, dullColors.green], yellow: [colors.yellow, dullColors.yellow], fgHighlights: mapObjIndexed(midTransparentize, dullColors), bgHighlights: mapObjIndexed(midTransparentize, paleColors), bgLightHighlights: mapObjIndexed(highTransparentize, paleColors), gray: [colors.gray, dullColors.gray], text: colors.dark[0], muted: midTransparentize(colors.dark[0]), background: colors.white[0], bgs: colors.white, fgs: colors.dark, fgPales: colors.dark.map(midTransparentize), border: transparentize(0.8, baseColors.dark[0]), highlight: transparentize(0.9, baseColors.dark[0]), code: { color: '#0451a5', backgroundColor: '#ffffff', prolog: '#001080', comment: '#008000', keyword: '#0000FF', number: '#09885a', constant: '#0000ff', variable: '#001080', string: '#a31515', selector: '#800000', tag: '#800000', operator: '#000000', punctuation: '#000000', function: '#795e26', className: '#267f99', char: '#a31515' } } export const dark = { ...colors, blue: [colors.blue, paleColors.blue], red: [colors.red, paleColors.red], green: [colors.green, paleColors.green], yellow: [colors.yellow, paleColors.yellow], gray: [colors.gray, paleColors.gray], fgHighlights: mapObjIndexed(midTransparentize, paleColors), bgHighlights: mapObjIndexed(midTransparentize, dullColors), text: colors.light[0], muted: midTransparentize(colors.light[0]), background: colors.dark[0], bgs: colors.dark, fgs: colors.light, fgPales: colors.light.map(midTransparentize), border: transparentize(0.8, baseColors.light[0]), highlight: transparentize(0.9, baseColors.light[0]), code: { color: '#9CDCFE', backgroundColor: '#1E1E1E', prolog: '#9cdcfe', comment: 'rgb(106, 153, 85)', keyword: 'rgb(86, 156, 214)', number: 'rgb(181, 206, 168)', constant: 'rgb(86, 156, 214)', variable: 'rgb(156, 220, 254)', string: 'rgb(206, 145, 120)', selector: 'rgb(215, 186, 125)', tag: 'rgb(86, 156, 214)', operator: '#808080', punctuation: 'rgb(212, 212, 212)', function: 'rgb(220, 220, 170)', className: 'rgb(78, 201, 176)', char: 'rgb(209, 105, 105)' } } <gh_stars>0 import Vue from "vue"; import store from "../store/index"; import { createRouter, createWebHistory } from "vue-router"; import auth from "../middleware/auth"; const routes = [{ path: "/", name: "home", component: () => import ( /* webpackChunkName: "home" */ "../views/Home"), }, { path: "/dashboard", name: "dashboard", meta: { requiresAuth: true }, component: () => import ( /* webpackChunkName: "dashboard" */ "../views/Dashboard.vue"), }, { path: "/user", name: "user", meta: { requiresAuth: true }, component: () => import ( /* webpackChunkName: "user" */ "../views/users/User"), }, { path: "/users", name: "users", meta: { requiresAuth: true }, component: () => import ( /* webpackChunkName: "users" */ "../views/users/Users"), beforeEnter: (to, from, next) => { if (store.getters["auth/isAdmin"]) next(); else next(false); }, }, { path: "/login", name: "login", component: () => import ( /* webpackChunkName: "login" */ "../views/auth/Login"), }, { path: "/register", name: "register", component: () => import ( /* webpackChunkName: "register" */ "../views/auth/Register"), }, { path: "/reset-password", name: "ResetPassword", meta: { middleware: [auth] }, component: () => import ( /* webpackChunkName: "reset-password" */ "../views/ResetPassword"), }, { path: "/forgot-password", name: "ForgotPassword", component: () => import ( /* webpackChunkName: "forgot-password" */ "../views/ForgotPassword" ), }, { path: "/customer", name: "customer", meta: { requiresAuth: true }, component: () => import ( /* webpackChunkName: "customer" */ "../views/customers/Customer"), }, { path: "/customers", name: "customers", meta: { requiresAuth: true }, component: () => import ( /* webpackChunkName: "customer" */ "../views/customers/Customers"), beforeEnter: (to, from, next) => { if (store.getters["auth/isAdmin"]) next(); else next(false); }, }, ] const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) router.beforeEach((to, from, next) => { const authUser = store.getters["auth/authUser"]; const reqAuth = to.matched.some((record) => record.meta.requiresAuth); const loginQuery = { path: "/login", query: { redirect: to.fullPath } }; if (reqAuth && !authUser) { store.dispatch("auth/getAuthUser").then(() => { if (!store.getters["auth/authUser"]) next(loginQuery); else next(); }); } else { next(); // make sure to always call next()! } }); export default router<reponame>notrubp/Z /** * Image loading helper. * * MIT License * Copyright (c) 2015 <EMAIL> * * 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. * * @license MIT * @copyright <EMAIL> 2015 */ (function(global) { "use strict"; /* * Image loading helper. * @namespace Image */ var Image = {}; var images = {}; /** * Get or create a new image. If it has already been loaded, the previously loaded image will be returned. * @function get * @memberof Image * @param {String} url * @returns {HTMLImageElement} The image element associated with the provided URL. */ Image.get = function(url) { if (url in images) { return images[url]; } var img = document.createElement('img'); img.src = url; images[url] = img; return img; } /* * Exports */ global.Image = Image; })(window); <reponame>paramountric/digitaltwincityviewer import React from 'react'; import clsx from 'clsx'; import Link from '@docusaurus/Link'; import styles from './styles.module.css'; const FeatureList = [ { title: 'Built to simplify visualisation of city data online', Svg: require('@site/static/img/online.svg').default, description: ( <> The Digital Twin City Viewer is built for actors that both provides and consume data in cities to easily share this online. Since the viewer is open source (MIT) the lock-in effect is minimal and the customisation possibilites maximal. </> ), }, { title: 'Built with decentralized data ownership in mind', Svg: require('@site/static/img/connection.svg').default, description: ( <> We need to stop copying data! This viewer uses a unique and simple concept of letting actors publish data on their own site. The data will automatically be updated in the viewer! <div className={styles.buttons} style={{ marginTop: 20 }}> <Link className="button button--secondary button--md" to="/docs/intro" > More about data sharing </Link> </div> </> ), }, { title: 'Seamless integration with the DTCC Platform', Svg: require('@site/static/img/integration.svg').default, description: ( <> The DTCC Platform is a digital twin city platform developed in the Digital Twin Cities Centre (DTCC) hosted by Chalmers University of Technology. <div className={styles.buttons} style={{ marginTop: 20 }}> <Link className="button button--secondary button--md" href="https://dtcc.chalmers.se/" > More about DTCC </Link> </div> </> ), }, ]; function Feature({ Svg, title, description }) { return ( <div className={clsx('col col--4')}> <div className="text--center"> <Svg className={styles.featureSvg} role="img" /> </div> <div className="text--center padding-horiz--md"> <h3>{title}</h3> <div>{description}</div> </div> </div> ); } export default function HomepageFeatures() { return ( <section className={styles.features}> <div className="container"> <div className="row"> {FeatureList.map((props, idx) => ( <Feature key={idx} {...props} /> ))} </div> </div> </section> ); } const moment = require('moment'); moment.locale("zh-cn"); const secret = require('./secret'); module.exports = { //更新时间 '@vuepress/last-updated': { transformer: (timestamp) => moment(timestamp).format('LLLL') // 不要忘了安装 moment // const moment = require('moment'); // return moment(timestamp).format('LLLL'); }, //PWA更新 '@vuepress/pwa': { serviceWorker: true, updatePopup: { message: "发现新内容可用", buttonText: "刷新", } }, //vssue评论插件 // '@vssue/vuepress-plugin-vssue': { // // 设置 `platform` 而不是 `api` // platform: 'github-v4', // // 其他的 Vssue 配置 // owner: 'githubsgeek', // repo: 'VuePressBlog', // clientId: secret.clientId, // clientSecret: secret.clientSecret, // autoCreateIssue: true, // }, //置顶 '@vuepress/back-to-top': true, //Google Analytics '@vuepress/google-analytics': { 'ga': secret.ga, }, //图片缩放 '@vuepress/medium-zoom': { selector: 'img.custom', } }<filename>src/service/api.js import axios from "axios"; import { config } from './config'; const defaultClient = axios.create({ baseURL: config.BASE_URL, timeout: 10000, headers: { Accept: "application/json", "Content-Type": "application/json", }, }); const clients = { default: { client: defaultClient, } }; /** Middleware to extract API error details from response */ export const thunkHandler = async (asyncFn, thunkAPI) => { try { const response = await asyncFn; return response.data; } catch (error) { return thunkAPI.rejectWithValue(error.response); } }; export default clients; <reponame>Wikunia/hakank<gh_stars>100-1000 /* Hamming Numbers in JavaScript. http://rosettacode.org/wiki/Hamming_numbers """ Hamming numbers are numbers of the form H = 2^i . 3^j . 5^k where} i, j, k > 0. Generate the sequence of Hamming numbers, in increasing order. In particular: 1. Show the first twenty Hamming numbers. 2. Show the 1691st Hamming number (the last one below 2^31). 3. Show the one millionth Hamming number (if the language - a convenient library -upports arbitrary-precision integers). ... The result should be: 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36 2125764000 519312780448388736089589843750000000000000000000000000000000000000000000000000000000 """ This JavaScript program was created by <NAME>, <EMAIL> See also my JavaScript page: http://www.hakank.org/javascript_progs/ */ 'use strict'; const {min2N,range,range2,timing2} = require('./js_utils.js'); // This is much slower than min2N (from js_utils.js) function minN(a) { let minVal = a[0]; for (const i of a) { if (a[i] < minVal) { minVal = a[i]; } } return minVal; } // hamming for Small Int function hamming(n) { let q = new Set([1,2,3,5]); let low = 1; for (let i of range(n)) { low = Math.min(...q.values()) q.delete(low); [low*2,low*3,low*5].map(v=>q.add(v)); } return low; } // hamming for Big Int: very slow for 1_000_000) function hammingN(n) { let q = new Set([1n,2n,3n,5n]); let low = 1n; for (let i of range(n)) { low = [...q.values()].minN(); q.delete(low); [low*2n,low*3n,low*5n].map(v=>q.add(v)); } return low; } // hamming2: faster function hamming2(n) { let h = [1]; let [next2,next3,next5] = [2,3,5]; let i = 0, j = 0, k = 0; // counters let m = 1; while (m < n) { h[m] = Math.min(...[next2,next3,next5]); // Note that we might update more than one counters if (h[m] === next2) { i++; next2 = 2*h[i]; } if (h[m] === next3) { j++; next3 = 3*h[j]; } if (h[m] === next5) { k++; next5 = 5*h[k]; } m++; } return h[n-1]; } // hamming2 for BigInt: much faster function hamming2N(n) { let h = [1n]; let [next2,next3,next5] = [2n,3n,5n]; let i = 0n, j = 0n, k = 0n; // counters let m = 1n; while (m < n) { h[m] = [next2,next3,next5].min2N(); // Note that we might update more than one counters if (h[m] === next2) { i++; next2 = 2n*h[i]; } if (h[m] === next3) { j++; next3 = 3n*h[j]; } if (h[m] === next5) { k++; next5 = 5n*h[k]; } m++; } return h[n-1]; } console.log("hamming(1..20):", range2(1,20).map(n=>hamming(n))); console.log("hamming(1691):", hamming(1691)); // console.log("hamming(1_000_000):", hammingN(1_000_000)); // Too slow console.log("hamming2(1..20):", range2(1,20).map(n=>hamming2(n))); console.log("hamming2(1691):", hamming2(1691)); // Much faster than hammingN console.log("hamming2N(1_000_000):", timing2(()=> hamming2N(1_000_000))); <reponame>Coldboltage/coldbolt-blog import React from 'react' import {Link} from "gatsby" import SEO from "../components/seo" import Layout from "../components/layout" const Lab = () => { return ( <Layout> <SEO title="Lab" description="This is where I test the stuff that I think I can make work for the site. I have no idea what I'm doing here"></SEO> <div className="container blog-title"> <h1>The Lab</h1> </div> <div className="container"> <ul> <li> <Link to="/wordpress-source">Wordpress source</Link> <p>I'm going to try to figure out how to source posts from my ColdboltSEO site. Should be interesting</p> </li> </ul> </div> </Layout> ) } export default Lab <reponame>shengnian/shengnian-ui-react<filename>docs/app/Examples/collections/Table/States/TableExampleWarning.js import React from 'react' import { Icon, Table } from 'shengnian-ui-react' const TableExampleWarning = () => ( <Table celled> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Status</Table.HeaderCell> <Table.HeaderCell>Notes</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>No Name Specified</Table.Cell> <Table.Cell>Unknown</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row warning> <Table.Cell>Jimmy</Table.Cell> <Table.Cell> <Icon name='attention' /> Requires Action </Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Unknown</Table.Cell> <Table.Cell warning> <Icon name='attention' /> Hostile </Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell>Unknown</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> </Table.Body> </Table> ) export default TableExampleWarning <gh_stars>0 export default class Stream { #data = null; #pipes = new Array(); #running = false; constructor( data ){ this.#data = data; return this; } pipe( destination ){ const promise = new Promise(async ( resolve )=>{ this.#createPipe(destination); await this.#run(); resolve(this.#data); }); promise.pipe = ( destination )=>{ this.#createPipe(destination); return promise; }; return promise; } #createPipe( destination ){ this.#pipes.push(destination); } async #run(){ if( !this.#running && this.#pipes.length ){ this.#running = true; const destination = this.#pipes.shift(); this.#data = await destination.transfer("pipe", this.#data); this.#running = false; await this.#run(); } } } /*global describe, it */ "use strict"; var expect = require('chai').expect; (function (window) { var v = require('../virtual-dom.js')(window).vNode; describe('various vNodes', function () { it('render a simple BR', function () { expect(v('br')).to.be.eql({ tag: 'br' }); }); it('render a complex list', function () { expect(v('ul.list', [ {key: 'k1', text: 'first value'}, {key: 'k2', text: 'second value'} ].map(function (option) { return v('li', {'data-key': option.key}, option.text); }))).to.be.eql( {tag: 'ul', attrs: {class: ['list']}, children: [ {tag: 'li', attrs: {'data-key': 'k1'}, children: ['first value']}, {tag: 'li', attrs: {'data-key': 'k2'}, children: ['second value']} ]} ); }); it('render a tag with id, class, attrs and contents', function () { expect(v('a#google.external[href="http://google.com"]', 'Google')).to.be.eql( {tag: 'a', attrs: { class:['external'], href:'http://google.com', id:'google' }, children:['Google']}, 'google' ); }); }); })(global.window || require('fake-dom')); <gh_stars>0 const path = require('path'); const { json, makeDirs, template, packageJson, install } = require('mrm-core'); function task() { const packages = ['typescript']; // tsconfig.json const tsconfig = json('tsconfig.json'); tsconfig.set('compilerOptions', { rootDir: '.', outDir: './dist', strict: true, declaration: true, module: 'commonjs', target: 'esnext', esModuleInterop: true, moduleResolution: 'node', resolveJsonModule: true, jsx: 'react', }); tsconfig.set('exclude', ['dist']); tsconfig.save(); makeDirs('src'); template('src/index.ts', path.join(__dirname, 'index.ts.template')).apply().save(); const pkg = packageJson(); pkg // Add scripts .setScript('build', 'tsc --project .') .setScript('prepublishOnly', 'npm run build') .set('types', 'dist/index.d.ts') .save(); // Dependencies install(packages); } task.description = 'Adds TypeScript'; module.exports = task; export default function breakpoint() { // eslint-disable-next-line no-debugger debugger; } <gh_stars>0 function maxSubArray(nums) { } <reponame>zackcglee/SaeSeomBot module.exports.genreateTimeMealText = (corner, initialText) => { const price = '가격: ' + corner.price + '원\n\n'; const morningMenu = '🥚 조식 🥚\n' + corner.morning.join('\n') + '\n\n'; const lunchMenu = '🐣 중식 🐣\n' + corner.lunch.join('\n') + '\n\n'; const dinnerMenu = '🐥 석식 🐥\n' + corner.dinner.join('\n') + '\n\n'; return initialText + price + morningMenu + lunchMenu + dinnerMenu; }; module.exports.generateGeneralMealText = (corner, initialText) => { let menuNum = corner.menus.length; for (let i = 0; i < menuNum; i++) { const menu = corner.menus[i]; let price = null; if (corner.prices.length > i) price = corner.prices[i]; if (price) initialText += menu + '\t' + price + '원\n'; else initialText += menu + '\n'; } if (menuNum == 0) return (initialText += '오늘은 운영하지 않아요 :)'); return initialText; }; import jwt_decode from 'jwt-decode'; import API from '../utils/api/api'; export const saveBook = (currentBook, status) => { console.log("This is the current book", currentBook); const token = localStorage.getItem('userToken'); const decoded = jwt_decode(token); console.log(decoded); return API.saveBook({ id: currentBook.id, title: currentBook.title, authors: currentBook.authors, description: currentBook.description, image: currentBook.image, link: currentBook.link, status: status, userId: decoded._id , }) .then(res => console.log("Successful POST to DB!", res)) .catch(err => console.log("this is the error", err)); } if(!user.logged) location="/"; //var latitude, longitude, index, i; if(user.logged){ API('/pic',"GET",null,function(data) { for (i=0; i<data.pictures.length; i++) { addPreview(serverAddress+'/data/'+data.pictures[i].hash+'_min.jpg', data.pictures[i].hash, data.pictures[i].gps.latitude, data.pictures[i].gps.longitude); addCityToPreview(data.pictures[i].hash); } }); } function deletePhoto(src, id){ if(id == null){ var tab = src.split('/'); id = tab[tab.length-1].replace(".jpg","") closeDialog(); } $('#preview_drop_'+id).hide(400, function(){ $('#preview_drop_'+id).remove(); }); API("/pic/"+id,"DELETE", null, function(ret) { if (!ret.success) { openDialog('Error while deleting image', '<p>:(</p>', 'OK', function(){}); } }); } <reponame>chahlaouy/recycauto.fr<filename>tailwind.config.js const defaultTheme = require('tailwindcss/defaultTheme'); module.exports = { purge: [ './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php', './storage/framework/views/*.php', './resources/views/**/*.blade.php', ], theme: { extend: { fontFamily: { sans: ['Nunito', ...defaultTheme.fontFamily.sans], }, }, borderColor: theme => ({ ...theme('colors'), DEFAULT: theme('colors.gray.300', 'currentColor'), 'primary': '#becf00;', 'secondary': '#ffed4a', 'danger': '#e3342f', }), backgroundColor: theme => ({ ...theme('colors'), DEFAULT: theme('colors.gray.300', 'currentColor'), 'primary': '#becf00;' }), textColor: theme => ({ ...theme('colors'), DEFAULT: theme('colors.gray.300', 'currentColor'), 'primary': '#becf00;' }), }, variants: { extend: { opacity: ['disabled'], fontWeight: ['hover'] }, }, plugins: [ require('@tailwindcss/forms'), require('@tailwindcss/typography'), ], }; /** * See LICENSE file. * **/ CAAT.Module({ /** * @name Curve * @memberOf CAAT.Math * @constructor */ defines:"CAAT.Math.Curve", depends:["CAAT.Math.Point"], extendsWith:function () { return { /** * @lends CAAT.Math.Curve.prototype */ /** * A collection of CAAT.Math.Point objects. */ coordlist:null, /** * Minimun solver step. */ k:0.05, /** * Curve length. */ length:-1, /** * If this segments belongs to an interactive path, the handlers will be this size. */ HANDLE_SIZE:20, /** * Draw interactive handlers ? */ drawHandles:true, /** * Paint the curve control points. * @param director {CAAT.Director} */ paint:function (director) { if (false === this.drawHandles) { return; } var cl = this.coordlist; var ctx = director.ctx; // control points ctx.save(); ctx.beginPath(); ctx.strokeStyle = '#a0a0a0'; ctx.moveTo(cl[0].x, cl[0].y); ctx.lineTo(cl[1].x, cl[1].y); ctx.stroke(); if (this.cubic) { ctx.moveTo(cl[2].x, cl[2].y); ctx.lineTo(cl[3].x, cl[3].y); ctx.stroke(); } ctx.globalAlpha = 0.5; for (var i = 0; i < this.coordlist.length; i++) { ctx.fillStyle = '#7f7f00'; var w = this.HANDLE_SIZE / 2; ctx.beginPath(); ctx.arc(cl[i].x, cl[i].y, w, 0, 2 * Math.PI, false); ctx.fill(); } ctx.restore(); }, /** * Signal the curve has been modified and recalculate curve length. */ update:function () { this.calcLength(); }, /** * This method must be overriden by subclasses. It is called whenever the curve must be solved for some time=t. * The t parameter must be in the range 0..1 * @param point {CAAT.Point} to store curve solution for t. * @param t {number} * @return {CAAT.Point} the point parameter. */ solve:function (point, t) { }, /** * Get an array of points defining the curve contour. * @param numSamples {number} number of segments to get. */ getContour:function (numSamples) { var contour = [], i; for (i = 0; i <= numSamples; i++) { var point = new CAAT.Math.Point(); this.solve(point, i / numSamples); contour.push(point); } return contour; }, /** * Calculates a curve bounding box. * * @param rectangle {CAAT.Rectangle} a rectangle to hold the bounding box. * @return {CAAT.Rectangle} the rectangle parameter. */ getBoundingBox:function (rectangle) { if (!rectangle) { rectangle = new CAAT.Math.Rectangle(); } // thanks yodesoft.com for spotting the first point is out of the BB rectangle.setEmpty(); rectangle.union(this.coordlist[0].x, this.coordlist[0].y); var pt = new CAAT.Math.Point(); for (var t = this.k; t <= 1 + this.k; t += this.k) { this.solve(pt, t); rectangle.union(pt.x, pt.y); } return rectangle; }, /** * Calculate the curve length by incrementally solving the curve every substep=CAAT.Curve.k. This value defaults * to .05 so at least 20 iterations will be performed. * * @return {number} the approximate curve length. */ calcLength:function () { var x1, y1; x1 = this.coordlist[0].x; y1 = this.coordlist[0].y; var llength = 0; var pt = new CAAT.Math.Point(); for (var t = this.k; t <= 1 + this.k; t += this.k) { this.solve(pt, t); llength += Math.sqrt((pt.x - x1) * (pt.x - x1) + (pt.y - y1) * (pt.y - y1)); x1 = pt.x; y1 = pt.y; } this.length = llength; return llength; }, /** * Return the cached curve length. * @return {number} the cached curve length. */ getLength:function () { return this.length; }, /** * Return the first curve control point. * @return {CAAT.Point} */ endCurvePosition:function () { return this.coordlist[ this.coordlist.length - 1 ]; }, /** * Return the last curve control point. * @return {CAAT.Point} */ startCurvePosition:function () { return this.coordlist[ 0 ]; }, setPoints:function (points) { }, setPoint:function (point, index) { if (index >= 0 && index < this.coordlist.length) { this.coordlist[index] = point; } }, /** * * @param director <=CAAT.Director> */ applyAsPath:function (director) { } } } }); asyncTest("can call traditional asynchronous echo function", function(){ var testlib = loadNewTestingLibraryWithLightningjs(); expect(1); testlib("asynchronousEcho", "hello world", function(echoText) { equals(echoText, "echo:hello world"); start(); }) }); asyncTest("can call promised echo function", function(){ var testlib = loadNewTestingLibraryWithLightningjs(); expect(1); testlib("echo", "hello world").then(function(echoText) { equals(echoText, "echo:hello world"); start(); }) }); asyncTest("can call promised exception-throwing function", function(){ var testlib = loadNewTestingLibraryWithLightningjs(); expect(1); testlib("throwThisError", "goodbye moon").then(function() { ok(false, "this method should throw an exception"); start(); }, function(error) { equals(error.message, "goodbye moon", "exception was thrown and delivered") start(); }); }); asyncTest("can call then() multiple times to attach more listeners", function(){ var testlib = loadNewTestingLibraryWithLightningjs(); expect(2); var callbackLookup = {first: false, second: false}; var echoPromise = testlib("throwThisError", "goodbye moon"); echoPromise.then(function() { ok(false, "this method should throw an exception"); start(); }, function(error) { equals(error.message, "goodbye moon", "exception was thrown and delivered") callbackLookup.first = true; allValuesAreTruthy(callbackLookup) && start(); }); echoPromise.then(function() { ok(false, "this method should throw an exception"); start(); }, function(error) { equals(error.message, "goodbye moon", "exception was thrown and delivered") callbackLookup.second = true; allValuesAreTruthy(callbackLookup) && start(); }); }); asyncTest("can call then() after the call returns once, and get the result again", function(){ var testlib = loadNewTestingLibraryWithLightningjs(); expect(3); var callbackLookup = {first: false, chained: false, timeout: false}; var echoPromise = testlib("throwThisError", "goodbye moon"); echoPromise.then(function() { ok(false, "this method should throw an exception"); start(); }, function(error) { equals(error.message, "goodbye moon", "exception was thrown and delivered") callbackLookup.first = true; echoPromise.then(function() { ok(false, "this method should throw an exception"); start(); }, function(error) { equals(error.message, "goodbye moon", "exception was thrown and delivered") callbackLookup.chained = true; allValuesAreTruthy(callbackLookup) && start(); }); }); setTimeout(function(){ echoPromise.then(function() { ok(false, "this method should throw an exception"); start(); }, function(error) { equals(error.message, "goodbye moon", "exception was thrown and delivered") callbackLookup.timeout = true; allValuesAreTruthy(callbackLookup) && start(); }); }, 2000); }); asyncTest("can chain calls to then()", function(){ var testlib = loadNewTestingLibraryWithLightningjs(); expect(2); var callbackLookup = {first: false, second: false}; var echoPromise = testlib("throwThisError", "goodbye moon"); echoPromise.then(function() { ok(false, "this method should throw an exception"); start(); }, function(error) { equals(error.message, "goodbye moon", "exception was thrown and delivered") callbackLookup.first = true; allValuesAreTruthy(callbackLookup) && start(); }).then(function() { ok(false, "this method should throw an exception"); start(); }, function(error) { equals(error.message, "goodbye moon", "exception was thrown and delivered") callbackLookup.second = true; allValuesAreTruthy(callbackLookup) && start(); }); }); asyncTest("promised then() callbacks calls execute in the given order", function(){ var testlib = loadNewTestingLibraryWithLightningjs(); expect(3); var callbackLookup = {first: false, second: false, third: false}; var echoPromise = testlib("throwThisError", "goodbye moon"); function shouldHaveThrownException() { ok(false, "this method should throw an exception"); start(); } function firstCallback() { equals(callbackLookup.second, false, "the second callback should not have executed yet"); callbackLookup.first = true; allValuesAreTruthy(callbackLookup) && start(); } function secondCallback() { equals(callbackLookup.first, true, "the first callback should already have executed"); callbackLookup.second = true; allValuesAreTruthy(callbackLookup) && start(); } function thirdCallback() { equals(callbackLookup.first && callbackLookup.second, true, "the other callback should already have executed"); callbackLookup.third = true; allValuesAreTruthy(callbackLookup) && start(); } echoPromise.then(shouldHaveThrownException, firstCallback); echoPromise.then(shouldHaveThrownException, secondCallback).then(shouldHaveThrownException, thirdCallback); }); asyncTest("promised then() give an error about unknown method when the method was not found", function(){ var testlib = loadNewTestingLibraryWithLightningjs(); expect(1); testlib("nonexistentMethod").then(function(valueList){ ok(false, "this method shouldn't exist"); start(); }, function(error) { ok(/unknown deferred method.*nonexistentMethod/.test(error.message), "we should get an error about the method not existing, got: " + error); start(); }); }); asyncTest("deferred calls return deferred closures that can be further chained for calls to nested functions", function(){ var testlib = loadNewTestingLibraryWithLightningjs(); expect(6); // create a "secret" string that we will retrieve later from // a nested object var originalSecretValue = "shh, it's a secret"; // grab a complex object from our API var complexObject = testlib("getComplexObject", originalSecretValue); // try the promise API first complexObject.then(function(complexObject){ equals(complexObject.getColorOfSky(), "blue", "the promise API should give direct access to the color"); complexObject.getColorOfSky(function(color){ equals(color, "blue", "the traditional async callback should give the color as well (even when using the promise API)"); }); // we should be able to traverse the complex object without // using the deferred closures in here var treasureChest = complexObject.getTreasureChest(); equals(treasureChest.getSecretValue(), originalSecretValue, "the non-deferred method should get the secret value"); }); // try the traditional async callback next complexObject("getColorOfSky", function(color) { equals(color, "blue", "the traditional async callback should give the color as well"); }); // chain a bit deeper to get other attributes on this object, // and inspect the "secret" value via promise API and the // traditional callback as well var treasureChest = complexObject("getTreasureChest"); treasureChest("getSecretValue").then(function(secretValue){ equals(secretValue, originalSecretValue, "the secret value should be accessible via promise API"); }); treasureChest("getSecretValue", function(secretValue){ equals(secretValue, originalSecretValue, "the secret value should be accessible via traditional async callbacks"); // this *should* be the last call start(); }); }); asyncTest("asynchronous calls always execute in the given order", function(){ var testlib = loadNewTestingLibraryWithLightningjs(2); expect(6); testlib("appendToValueList", "first1", function(valueList){ equals(valueList[0], "first1"); }); testlib("appendToValueList", "second2", function(valueList){ equals(valueList[0], "first1"); equals(valueList[1], "second2"); }); testlib("appendToValueList", "third3", function(valueList){ equals(valueList[0], "first1"); equals(valueList[1], "second2"); equals(valueList[2], "third3"); start(); }); }); asyncTest("can call asynchronous methods, even when download takes a long time (3 seconds)", function(){ var testlib = loadNewTestingLibraryWithLightningjs(3); var callbackLookup = { asynchronousEchoCallback: false, echoCallback: false }; expect(2); testlib("asynchronousEcho", "hello world", function(echoText) { equals(echoText, "echo:hello world"); callbackLookup.asynchronousEchoCallback = true; allValuesAreTruthy(callbackLookup) && start(); }) testlib("echo", "hello world").then(function(echoText) { equals(echoText, "echo:hello world"); callbackLookup.echoCallback = true; allValuesAreTruthy(callbackLookup) && start(); }) }); asyncTest("can call require() twice for the same namespace and get the exact same library without an additional download", function(){ var somethinglib1 = loadNewTestingLibraryWithLightningjs(0.5, "somethinglib"); expect(2); somethinglib1("getDownloadTimestamp").then(function(value){ var originalTimestamp = value; var somethinglib2 = loadNewTestingLibraryWithLightningjs(2.0, "somethinglib"); equals(somethinglib1, somethinglib2, "the library objects should be the same closure"); somethinglib2("getDownloadTimestamp").then(function(value){ equals(value, originalTimestamp, "we didn't download a new version of the library"); start(); }); }) }); asyncTest("can call traditional asynchronous echo function when global id is set", function(){ window.id = 999; var testlib = loadNewTestingLibraryWithLightningjs(); expect(1); testlib("asynchronousEcho", "hello world", function(echoText) { equals(echoText, "echo:hello world"); start(); window.id = null; }) }); // TODO: figure out an easy way to test the lightningjs.expensive API // asyncTest("expensive calls are executed only after window.onload", function(){ // }); <reponame>paulvollmer/api-boilerplate 'use strict'; // The lib. const lib = require('loopback-extended-lib'); // Register files. lib.register(__dirname); // Export. module.exports = lib; <gh_stars>1-10 /* eslint-disable react/display-name */ import React from 'react'; import { Container, Divider, Header, Tab } from 'semantic-ui-react'; import EventForm from '../../components/eventForm'; import EventEdit from '../../components/eventEdit'; import ReadMe from '../../components/readme'; const Admin = (props) => { const panes = [ { menuItem: 'Events Add', render: () => ( <Tab.Pane style={{ background: 'black' }} attached={false}> <EventForm /> </Tab.Pane> ), }, { menuItem: 'Events Edit', render: () => ( <Tab.Pane style={{ background: 'black' }} attached={false}> <EventEdit /> </Tab.Pane> ), }, { menuItem: 'ReadMe!', render: () => ( <Tab.Pane style={{ background: 'black' }} attached={false}> <ReadMe /> </Tab.Pane> ), }, ]; return ( <Container> <Divider hidden /> <Header as="h1" dividing inverted> Please enter the event information below. </Header> <Tab menu={{ inverted: true, attached: false, tabular: false, pointing: true, secondary: true, }} panes={panes} /> </Container> ); }; export default Admin; <reponame>abdulfatahi/gnome-video-app-backend /* eslint-disable import/extensions */ import fs from 'fs'; import { validationResult } from 'express-validator'; import jwt from 'jsonwebtoken'; import db from '../../../models/index.js'; import cloudinary from '../../../lib/cloudConfig.js'; const { gif: GifModel, user: User } = db; export default () => { // Creating a new video record const Create = async (req, res) => { const error = validationResult(req); if (!error.isEmpty()) return res.status(422).json({ errors: error.array() }); if (!req.file) return res.status(400).json({ message: 'gif required' }); const { path, filename } = req.file; // file becomes available in req at this point // Upload Video to Cloudinary const isUploaded = await cloudinary.uploader.upload( path, { public_id: `GifUploads/${filename}`, }, ); if (!isUploaded) return res.status(500).json({ isUploaded }); await fs.unlinkSync(path); // decode admin/user email const tokenData = jwt.verify( req.headers.authorization.split(' ')[1], process.env.SECRET, ); // Query for the unique user const isUser = await User.findOne({ where: { email: tokenData.email }, }); const gifCreateObject = { gif: isUploaded.secure_url, cloudinary_id: isUploaded.public_id, }; if (isUser) { gifCreateObject.UserId = isUser.id; gifCreateObject.isDefault = false; } const Video = await GifModel.create(gifCreateObject); return res.status(201).json({ ...Video.createRepresenter() }); }; return { Create }; }; import { Fragment } from 'react' const Support = ({ mainColor, subColor }) => { return ( <Fragment> <svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M12.3561 0.282227C5.69401 0.282227 0.287109 5.67551 0.287109 12.3208C0.287109 18.9661 5.69401 24.3594 12.3561 24.3594C19.0181 24.3594 24.425 18.9661 24.425 12.3208C24.425 5.67551 19.0181 0.282227 12.3561 0.282227ZM13.563 20.7478H11.1492V18.3401H13.563V20.7478ZM16.0612 11.4179L14.975 12.5255C14.1061 13.4043 13.563 14.1266 13.563 15.9324H11.1492V15.3304C11.1492 14.0062 11.6923 12.8023 12.5612 11.9235L14.0578 10.4067C14.5044 9.97328 14.7699 9.37135 14.7699 8.70923C14.7699 7.38499 13.6837 6.30151 12.3561 6.30151C11.0285 6.30151 9.94228 7.38499 9.94228 8.70923H7.52849C7.52849 6.0487 9.68883 3.8938 12.3561 3.8938C15.0233 3.8938 17.1837 6.0487 17.1837 8.70923C17.1837 9.76862 16.7492 10.7317 16.0612 11.4179Z" fill={mainColor} /> </svg> </Fragment> ) } export default Support import EventBus from '../../../src/EventBus'; export default class Example { constructor() { if (!this.init()) return false; this.EventBus = new EventBus(); } init() { this.selectors = { clickButton: 'example-click', }; this.clickButton = document.querySelector(`.${this.selectors.clickButton}`); if (!this.clickButton) return false; return true; } } // imports below import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware, compose } from 'redux'; import { Provider } from 'react-redux'; import { StripeProvider } from 'react-stripe-elements'; import thunk from 'redux-thunk'; // import Logger from 'redux-logger'; // REMOVE FOR PRODUCTION -----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^\\\\\\\\\\\\\\\\\\\\ import { BrowserRouter as Router, withRouter } from 'react-router-dom'; import 'bootstrap/dist/css/bootstrap.min.css'; import config from "./auth/auth_config.json" import './index.scss'; import rootReducer from './reducers'; import App from './auth/AppSetter'; import { Auth0Provider } from "./react-auth0-wrapper"; // requires below require("dotenv").config(); // variable below // composeEnhancer allows for redux store dev view in chrome const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore(rootReducer, composeEnhancer(applyMiddleware(thunk))); // redirect for auth0 const onRedirectCallback = appState => { window.history.replaceState( {}, document.title, appState && appState.targetUrl ? appState.targetUrl : window.location.pathname ); }; const AppwithRouter = withRouter(App); // const pkTest = process.env.PK_TEST; // ^^ PK = Publishable Key ^^ const pkTest = process.env.REACT_APP_PK_TEST; console.log('PK', pkTest) ReactDOM.render( <Auth0Provider domain={config.domain} client_id={config.clientId} redirect_uri={window.location.origin} audience={config.audience} onRedirectCallback={onRedirectCallback} > <Provider store={store}> <Router> <AppwithRouter /> </Router> </Provider> </Auth0Provider>, document.getElementById('root') ); module.exports = class { constructor(client) { this.client = client; } async run(oldState, newState) { const player = this.client.music.players.get(newState.guild.id); const t = await this.client.getTranslate(newState.guild.id); if (!newState.channelID && newState.member.user.id === this.client.user.id) { if (player) { player.destroy(oldState.guild.id) return this.client.channels.cache.get(player.textChannel).send(new this.client.embed().setDescription(t('utils:music.voiceStateUpdate'))); } } if (!newState.channelID && newState.member.user.id !== this.client.user.id && player && player.voiceChannel === oldState.channelID) { if (oldState.channel.members.filter(c => !c.user.bot).size === 0) { player.pause(true); this.client.channels.cache.get(player.textChannel).send(new this.client.embed() .setDescription(t('utils:music:voiceStateUpdate.2minutos'))).then(msg => msg.delete({ timeout: 60000 * 2 })) setTimeout(() => { if (!player) return; if (oldState.channel.members.filter(c => !c.user.bot).size > 0) return; player.destroy(); return this.client.channels.cache.get(player.textChannel).send(t('utils:music:voiceStateUpdate.2minutosEnd')) }, 2 * 60000); } } else if (newState.channel && newState.channel.members.filter(c => !c.user.bot).size === 1 && player && player.voiceChannel === newState.channelID) { player.pause(false); } } }var draw_time = 800; function makeGraph(data, title, divName, xTitle, yTitle) { var svg = dimple.newSvg(divName, "100%", "100%"); if (data.length > 0) { var chart = new dimple.chart(svg, data); chart.addCategoryAxis("y", yTitle); chart.addMeasureAxis("x", xTitle, "Full Tweet"); var s = chart.addSeries(null, dimple.plot.bar); if (yTitle === "Sentiment") { chart.setMargins("15%", "20%", "5%", "15%"); svg.append("text") .attr("x", chart._xPixels() + chart._widthPixels() / 2 - 30) .attr("y", chart._yPixels() - 40) .attr("text-anchor", "middle") .style("font-size", "16px") .style("text-decoration", "underline") .text(title); } else { chart.setMargins("38%", "20%", "5%", "15%"); svg.append("text") .attr("x", chart._xPixels() + chart._widthPixels() / 2 - 150) .attr("y", chart._yPixels() - 40) .attr("text-anchor", "middle") .style("font-size", "16px") .style("text-decoration", "underline") .text(title); } s.tooltipFontSize = "14px"; s.getTooltipText = function (e) { tooltip = []; tooltip.push(xTitle + ": " + e.cx); return tooltip; }; if (yTitle === "Sentiment") { chart.axes[0].addOrderRule(["Negative", "Neutral", "Positive"]); } else { chart.axes[0].addOrderRule(xTitle, false); } chart.axes[1].fontSize = "14px"; chart.draw(draw_time); chart.axes[0].titleShape.style("font-size", "14px"); s.shapes.on("mouseover", function (e) { d3.select(divName).selectAll("rect").style("opacity", .3); d3.select(this).style("opacity", 0.8); dimple._showBarTooltip(e, this, chart, s); var max_tweets = $("#tweet_btn").text(); max_tweets = max_tweets.replace(/\s+/g, ""); if (title === 'Most Retweeted') { var type = 'retweet'; var tweets = get_rt_tweets(); } else if (title === 'Most Favourited') { var type = 'favourite'; var tweets = get_fav_tweets(); } if (title !== 'Tweets by Sentiment') { var tweets_title = make_tweets_title(type, max_tweets); var tweets_container = $("#tweets"); tweets_container.html("<b>" + tweets_title + "</b>"); tweets_container.append(tweets.slice(0, max_tweets)); tweets_container.attr('tweets-type', type); var tid = data.find(function (d) { return d[xTitle] == e.cx && d[yTitle] == e.cy }); var tweet_box = $("." + tid.ID); var vert_position = tweet_box.offset().top + tweets_container.scrollTop() - $('#flex').height() - tweet_box.height(); tweet_box.addClass("tweet-highlight"); tweets_container.animate({ scrollTop: vert_position }, 200); } }); s.shapes.on("mouseleave", function (e) { $('#tweets').stop(true, true); d3.selectAll("rect").style("opacity", 0.8); dimple._removeTooltip(e, this, chart, s); $(".twitter-tweet").removeClass("tweet-highlight"); }); s.shapes.on("click", function (e) { var tid = data.find(function (d) { return d[xTitle] == e.cx && d[yTitle] == e.cy }); var url = "https://www.twitter.com/" + tid.User + "/status/" + tid.ID; url = url.replace(/\s/g, ""); var text = '<a href=' + url + '></a>'; var feed = document.createElement("blockquote"); feed.className = "twitter-tweet"; feed.setAttribute("data-conversation", "none"); feed.innerHTML = text; if (yTitle != "Sentiment") { $(".dial").html(feed); $(".dial").dialog({ title: "Tweet", draggable: false, position: {my: "center", at: "top"}, modal: true, minHeight: 200, minWidth: 500, dialogClass: 'dial-head' }); $.getScript("/static/twitter_widget.js"); $(".ui-widget-overlay").on("click", function () { $(".dial").dialog("close"); }); } }); window.onresize = function () { // As of 1.1.0 the second parameter here allows you to draw // without reprocessing data. This saves a lot on performance // when you know the data won't have changed. chart.draw(0, true); }; } else { var div = document.getElementById("sentiment"); rect = div.getBoundingClientRect(); svg.append("text") .attr("x", rect.width / 2) .attr("y", rect.height / 2) .attr("text-anchor", "middle") .style("font-size", "16px") .style("text-decoration", "underline") .text("No data avaliable"); } } function makeSocialGraph(data, divName, title, xTitle) { makeGraph(data, title, divName, xTitle, "Tweet"); } function makeSentimentGraph(data, divName, title, xTitle) { makeGraph(data, title, divName, xTitle, "Sentiment"); } function redraw_socialgraph(data, object_name, title, x_title) { $(object_name).remove(); var class_name = object_name.slice(1); $(".bar-graphs").append("<div class=" + class_name + "></div>"); makeSocialGraph(data, object_name, title, x_title); return; } <gh_stars>0 var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var hbs = require('hbs'); var fs = require('fs'); var about = require('./about'); var assignments = require('./user/tasks'); var calendar = require('./user/calendar'); var dashboard = require('./user/dashboard'); var index = require('./routes/index'); var schedule = require('./user/schedule'); var search = require('./user/search'); var settings = require('./user/settings'); var users = require('./routes/users'); var app = express(); console.log("in app.js"); // Block the header from containing information // about the server app.disable('x-powered-by'); console.log("engine setup"); // view engine setup hbs.registerPartials(__dirname + '/views/partials'); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hbs'); app.set('view options', { layout: '/layouts/main.hbs' }); console.log("parsers, etc."); // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); console.log("routings and such"); app.use('/about', about); app.use('/user/tasks', assignments); app.use('/user/calendar', calendar); app.use('/user/dashboard', dashboard); app.use('/', index); app.use('/user/schedule', schedule); app.use('/user/search', search); app.use('/user/settings', settings); // app.use('/user', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. var sqlite3 = require('sqlite3').verbose(); var db = new sqlite3.Database('testDB.db'); db.serialize(function() { db.run("CREATE TABLE IF NOT EXISTS users (id TEXT, name TEXT, email TEXT, password TEXT)"); db.run("INSERT INTO users VALUES ('admin', '<NAME>', '<EMAIL>', 'admin')"); // var stmt = db.prepare("INSERT INTO users VALUES (?, ?, ?, ?)"); // for (var i = 0; i < 10; i++) { // stmt.run("Ipsum " + i); // } // stmt.finalize(); // // db.each("SELECT rowid AS id, info FROM lorem", function(err, row) { // console.log(row.id + ": " + row.info); // }); }); db.close(); console.log("export app"); module.exports = app; <reponame>KevinLam2980/front-end import axios from 'axios' export const GET_CITIES_START = 'GET_CITIES_START' export const GET_CITIES_SUCCESS = 'GET_CITIES_SUCCESS' export const GET_CITIES_FAILURE = 'GET_CITIES_FAILURE' export const MOVE_CITY_COMPARE = 'MOVE_CITY_COMPARE' export const MOVE_CITY_ERROR = 'MOVE_CITY_ERROR' export const REMOVE_CITY_TO_COMPARE = 'REMOVE_CITY_TO_COMPARE' export const GET_USER_START = 'GET_USER_START' export const GET_USER_SUCCESS = 'GET_USER_SUCCESS' export const GET_USER_FAILURE = 'GET_USER_FAILURE' export const getCities = () => dispatch => { dispatch({ type: GET_CITIES_START }) axios .get('https://labs-28-citrics-b.herokuapp.com/cities/allid') .then(res => { console.log('get citites ->', res.data) dispatch({ type: GET_CITIES_SUCCESS, payload: res.data }) }) .catch(err => { console.log(err) dispatch({ type: GET_CITIES_FAILURE, payload: err.message }) }) } export const cityToCompare = cityId => dispatch => { axios .get(`https://labs-28-citrics-b.herokuapp.com/cities/city/${cityId}`) .then(res => { dispatch({ type: MOVE_CITY_COMPARE, payload: res.data }) }) .catch(err => { dispatch({ type: MOVE_CITY_ERROR, payload: err.message }) }) } export const removeCityFromCompare = cityId => dispatch => { dispatch({ type: REMOVE_CITY_TO_COMPARE, payload: cityId }) } export const getUserData = () => dispatch => { dispatch({ type: GET_USER_START }) axios .get(`https://labs-28-citrics-b.herokuapp.com/users/user/1`) .then(res => { dispatch({ type: GET_USER_SUCCESS, payload: res.data }) }) .catch(err => { dispatch({ type: GET_USER_FAILURE, payload: err.message }) }) } import request from '@/utils/request' export function addCartBook(bookId, bookCount) { return request({ url: '/cart/addBook', method: 'post', params: { bookId, bookCount } }) } export function addBatchBooks(bookList) { return request({ url: '/cart/addBatchBooks', method: 'post', data: bookList }) } export function getCartBookList() { return request({ url: '/cart/bookList', method: 'get' }) } export function deleteCartBook(bookId) { return request({ url: '/cart/deleteBook', method: 'post', params: { bookId } }) } export function clearCart() { return request({ url: '/cart/clear', method: 'delete' }) } export function resetCartBookCount(bookId, bookCount) { return request({ url: '/cart/resetBookCount', method: 'post', params: { bookId, bookCount } }) } <gh_stars>0 define("ace/mode/abc_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function (e, t, n) { "use strict"; var r = e("../lib/oop"), i = e("./text_highlight_rules").TextHighlightRules, s = function () { this.$rules = { start: [{ token: ["zupfnoter.information.comment.line.percentage", "information.keyword", "in formation.keyword.embedded"], regex: "(%%%%)(hn\\.[a-z]*)(.*)", comment: "Instruction Comment" }, { token: ["information.comment.line.percentage", "information.keyword.embedded"], regex: "(%%)(.*)", comment: "Instruction Comment" }, { token: "comment.line.percentage", regex: "%.*", comment: "Comments" }, { token: "barline.keyword.operator", regex: "[\\[:]*[|:][|\\]:]*(?:\\[?[0-9]+)?|\\[[0-9]+", comment: "Bar lines" }, { token: ["information.keyword.embedded", "information.argument.string.unquoted"], regex: "(\\[[A-Za-z]:)([^\\]]*\\])", comment: "embedded Header lines" }, { token: ["information.keyword", "information.argument.string.unquoted"], regex: "^([A-Za-z]:)([^%\\\\]*)", comment: "Header lines" }, { token: ["text", "entity.name.function", "string.unquoted", "text"], regex: "(\\[)([A-Z]:)(.*?)(\\])", comment: "Inline fields" }, { token: ["accent.constant.language", "pitch.constant.numeric", "duration.constant.numeric"], regex: "([\\^=_]*)([A-Ga-gz][,']*)([0-9]*/*[><0-9]*)", comment: "Notes" }, { token: "zupfnoter.jumptarget.string.quoted", regex: '[\\"!]\\^\\:.*?[\\"!]', comment: "Zupfnoter jumptarget" }, { token: "zupfnoter.goto.string.quoted", regex: '[\\"!]\\^\\@.*?[\\"!]', comment: "Zupfnoter goto" }, { token: "zupfnoter.annotation.string.quoted", regex: '[\\"!]\\^\\!.*?[\\"!]', comment: "Zupfnoter annoation" }, { token: "zupfnoter.annotationref.string.quoted", regex: '[\\"!]\\^\\#.*?[\\"!]', comment: "Zupfnoter annotation reference" }, { token: "chordname.string.quoted", regex: '[\\"!]\\^.*?[\\"!]', comment: "abc chord" }, {token: "string.quoted", regex: '[\\"!].*?[\\"!]', comment: "abc annotation"}] }, this.normalizeRules() }; s.metaData = { fileTypes: ["abc"], name: "ABC", scopeName: "text.abcnotation" }, r.inherits(s, i), t.ABCHighlightRules = s }), define("ace/mode/folding/cstyle", ["require", "exports", "module", "ace/lib/oop", "ace/range", "ace/mode/folding/fold_mode"], function (e, t, n) { "use strict"; var r = e("../../lib/oop"), i = e("../../range").Range, s = e("./fold_mode").FoldMode, o = t.FoldMode = function (e) { e && (this.foldingStartMarker = new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + e.start)), this.foldingStopMarker = new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + e.end))) }; r.inherits(o, s), function () { this.foldingStartMarker = /([\{\[\(])[^\}\]\)]*$|^\s*(\/\*)/, this.foldingStopMarker = /^[^\[\{\(]*([\}\]\)])|^[\s\*]*(\*\/)/, this.singleLineBlockCommentRe = /^\s*(\/\*).*\*\/\s*$/, this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/, this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/, this._getFoldWidgetBase = this.getFoldWidget, this.getFoldWidget = function (e, t, n) { var r = e.getLine(n); if (this.singleLineBlockCommentRe.test(r) && !this.startRegionRe.test(r) && !this.tripleStarBlockCommentRe.test(r)) return ""; var i = this._getFoldWidgetBase(e, t, n); return !i && this.startRegionRe.test(r) ? "start" : i }, this.getFoldWidgetRange = function (e, t, n, r) { var i = e.getLine(n); if (this.startRegionRe.test(i)) return this.getCommentRegionBlock(e, i, n); var s = i.match(this.foldingStartMarker); if (s) { var o = s.index; if (s[1]) return this.openingBracketBlock(e, s[1], n, o); var u = e.getCommentFoldRange(n, o + s[0].length, 1); return u && !u.isMultiLine() && (r ? u = this.getSectionRange(e, n) : t != "all" && (u = null)), u } if (t === "markbegin") return; var s = i.match(this.foldingStopMarker); if (s) { var o = s.index + s[0].length; return s[1] ? this.closingBracketBlock(e, s[1], n, o) : e.getCommentFoldRange(n, o, -1) } }, this.getSectionRange = function (e, t) { var n = e.getLine(t), r = n.search(/\S/), s = t, o = n.length; t += 1; var u = t, a = e.getLength(); while (++t < a) { n = e.getLine(t); var f = n.search(/\S/); if (f === -1) continue; if (r > f) break; var l = this.getFoldWidgetRange(e, "all", t); if (l) { if (l.start.row <= s) break; if (l.isMultiLine()) t = l.end.row; else if (r == f) break } u = t } return new i(s, o, u, e.getLine(u).length) }, this.getCommentRegionBlock = function (e, t, n) { var r = t.search(/\s*$/), s = e.getLength(), o = n, u = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/, a = 1; while (++n < s) { t = e.getLine(n); var f = u.exec(t); if (!f) continue; f[1] ? a-- : a++; if (!a) break } var l = n; if (l > o) return new i(o, r, l, t.length) } }.call(o.prototype) }), define("ace/mode/abc", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/abc_highlight_rules", "ace/mode/folding/cstyle"], function (e, t, n) { "use strict"; var r = e("../lib/oop"), i = e("./text").Mode, s = e("./abc_highlight_rules").ABCHighlightRules, o = e("./folding/cstyle").FoldMode, u = function () { this.HighlightRules = s, this.foldingRules = new o, this.$behaviour = this.$defaultBehaviour }; r.inherits(u, i), function () { this.lineCommentStart = "%", this.$id = "ace/mode/abc", this.snippetFileId = "ace/snippets/abc" }.call(u.prototype), t.Mode = u }); (function () { window.require(["ace/mode/abc"], function (m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })(); <gh_stars>0 import { Router } from 'express'; import CompanyOrder from '../../controllers/company/order'; import {checkCompanyToken} from '../../middleware/checkToken'; import PhotoUploadController from '../../controllers/upload.controller'; const router = Router(); router.post('/company/order/activity/send', checkCompanyToken , CompanyOrder.sendOrderActivity); router.get('/company/orders', checkCompanyToken, CompanyOrder.getAllOrderForACompany); router.get('/company/order/pending', checkCompanyToken, CompanyOrder.getAllPendingOrder); router.post('/company/order/status/change', checkCompanyToken, CompanyOrder.changeorderStatus); router.get('/company/order/:track_id', checkCompanyToken, CompanyOrder.getOrderByTrackingId); router.get('/company/orders/analytics', checkCompanyToken, CompanyOrder.OrderAnalytics); router.get('/company/orders/search', checkCompanyToken, CompanyOrder.searchOrder); router.put('/company/order/approve', checkCompanyToken, CompanyOrder.approveOrder); router.post('/company/photo/upload', PhotoUploadController.upLoadphoto); export default router; import { axios } from '@/utils/request' const api = { define: '/open-api/define' } export function getDefineList (parameter) { return axios({ url: api.define + '/list', method: 'get', params: parameter }) } export function getDefine (apiId) { return axios({ url: api.define + '/get/' + apiId, method: 'get' }) } export function saveDefine (parameter) { return axios({ url: api.define + (parameter.id > 0 ? '/update' : '/save'), method: 'post', data: parameter, headers: { 'Content-Type': 'application/json;charset=UTF-8' } }) } export function delDefine (parameter) { return axios({ url: api.define + '/remove', method: 'post', params: parameter }) } export const defineExport = api.define + '/export' require.config({ baseUrl: '../../js/', paths: { // the left side is the module ID, // the right side is the path to // the jQuery file, relative to baseUrl. // Also, the path should NOT include // the '.js' file extension. config: '../etc/config' } }); import {createSelector} from 'reselect'; import { fiatCurrencyMap } from './constants'; // import {sortMap} from './constants'; const getFarm = function(farm, balances, addresses, fiatCurrency) { const currency = fiatCurrencyMap[fiatCurrency].label; let fractionDigits = 2; if(currency === 'ETH' || currency === 'BTC') { fractionDigits = 8; } const currentFarm = { ...farm, data: formatStakingInfo(farm.data, currency) } const allBalances = combineBalances(balances, addresses, fiatCurrency); const rawPrice = currentFarm.data?.rawPrice || 0; const formattedBonds = allBalances.bonds.map((bond)=>{ return { ...bond, payout: Number(bond.payout) === 0 ? 0 : bond.payout.toFixed(4), payoutInUSD: Number(bond.payout * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), pendingPayout: Number(bond.pendingPayout) === 0 ? 0 : bond.pendingPayout.toFixed(4), pendingPayoutInUSD: Number(bond.pendingPayout * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), }; }); const formattedWrappedBalances = allBalances.wrappedBalances.balances.map((bond)=>{ return { ...bond, convertedBalance: Number(bond.convertedBalance) === 0 ? 0 : bond.convertedBalance.toFixed(4), convertedBalanceInUSD: Number(bond.convertedBalance * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), tokenBalance: Number(bond.tokenBalance) === 0 ? 0 : bond.tokenBalance.toFixed(4) }; }) const formattedCollateralBalances = allBalances.collateralBalances.balances.map((bond)=>{ return { ...bond, convertedBalance: Number(bond.convertedBalance) === 0 ? 0 : bond.convertedBalance.toFixed(4), convertedBalanceInUSD: Number(bond.convertedBalance * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), tokenBalance: Number(bond.tokenBalance) === 0 ? 0 : bond.tokenBalance.toFixed(4) }; }) if (currentFarm.data === null) return currentFarm; const formatRebaseParams = [ Number(allBalances.stakingTokenBalance + allBalances.wrappedBalances?.total + allBalances.collateralBalances?.total + allBalances.wsOHMPoolBalance.convertedBalance), Number(allBalances.fullBondTotal + allBalances.tokenBalance), Number(currentFarm.data.rawPrice), currentFarm.data.stakingRebase, ]; let rawTotal = ( allBalances.tokenBalance + allBalances.stakingTokenBalance + allBalances.hugsBalance + allBalances.fullBondTotal + allBalances.vssBalance.convertedBalance + allBalances.wsOHMPoolBalance.convertedBalance + allBalances.wrappedBalances.total + allBalances.collateralBalances.total ) * currentFarm.data?.rawPrice; rawTotal = Number(rawTotal); const formattedAllBalances = currentFarm.treasuryBalance?.allBalances .map((balance) => { let value = balance.value; if(balance.symbol.indexOf('-') > -1 && !balance.converted) { value = balance.value * currentFarm.data?.rawPrice; } const valueInUSD = Number(value).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }) return { ...balance, valueInUSD }; }); const rawTreasuryTotal = currentFarm.treasuryBalance?.usdTreasuryValues + (currentFarm.treasuryBalance?.ohmTreasuryValues * currentFarm.data?.rawPrice); const rawBackingPrice = Number(rawTreasuryTotal / currentFarm.data?.totalSupply); const treasuryRunway = rawTreasuryTotal / currentFarm.data?.circulatingSupply; const runway = (Math.log(treasuryRunway) / Math.log(1 + currentFarm.data?.stakingRebase) / currentFarm.data?.distributeInterval).toFixed(2); const treasuryBalance = { ...currentFarm.treasuryBalance, allBalances: formattedAllBalances, priceBackingRatio: (currentFarm.data?.rawPrice / rawBackingPrice).toFixed(2), rawBackingPrice, runway, backingPrice: Number(rawTreasuryTotal / currentFarm.data?.totalSupply) .toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), rawTreasuryTotal, rfvInUSD: Number(currentFarm.treasuryBalance?.rfv).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }), total: Number(rawTreasuryTotal).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }) }; return { ...currentFarm, treasuryBalance, balances: { ...allBalances, bonds: formattedBonds, wrappedBalances: { ...allBalances.wrappedBalances, balances: formattedWrappedBalances }, collateralBalances: { ...allBalances.collateralBalances, balances: formattedCollateralBalances }, wsOHMPoolBalance: { ...allBalances.wsOHMPoolBalance, tokenBalance: Number(allBalances.wsOHMPoolBalance.tokenBalance) === 0 ? 0 :allBalances.wsOHMPoolBalance.tokenBalance.toFixed(4), convertedBalanceInUSD: Number(allBalances.wsOHMPoolBalance.convertedBalance * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), }, vssBalance: { ...allBalances.vssBalance, tokenBalance: Number(allBalances.vssBalance.tokenBalance) === 0 ? 0 :allBalances.vssBalance.tokenBalance.toFixed(4), convertedBalanceInUSD: Number(allBalances.vssBalance.convertedBalance * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), claimableInUSD: Number(allBalances.vssBalance.claimable).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), }, rawTotal, warmupBalance: Number(allBalances.warmupBalance) === 0 ? 0 :allBalances.warmupBalance.toFixed(4), warmupBalanceInUSD: Number(allBalances.warmupBalance * rawPrice).toLocaleString(undefined, { minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), fullPendingBondTotal: Number(allBalances.fullPendingBondTotal) === 0 ? 0 :allBalances.fullPendingBondTotal.toFixed(4), fullPendingBondTotalInUSD: Number(allBalances.fullPendingBondTotal * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), stakingTokenBalance: Number(allBalances.stakingTokenBalance) === 0 ? 0 :allBalances.stakingTokenBalance.toFixed(4), stakingTokenBalanceInUSD: Number(allBalances.stakingTokenBalance * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), tokenBalance: Number(allBalances.tokenBalance) === 0 ? 0 :allBalances.tokenBalance.toFixed(4), tokenBalanceInUSD: Number(allBalances.tokenBalance * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), hugsBalance: Number(allBalances.hugsBalance) === 0 ? 0 :allBalances.hugsBalance.toFixed(4), hugsBalanceInUSD: Number(allBalances.hugsBalance * rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), total: rawTotal.toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }) }, roiCalculations: { roiRebase: formatRebase(...formatRebaseParams, 1, currency), roi5Day: formatRebase( ...formatRebaseParams, currentFarm.data.distributeInterval * 5, currency), roiDynamic: formatRebase( ...formatRebaseParams, currentFarm.data.distributeInterval * currentFarm.roiDynamic, currency) } } } const combineBalances = (balances, addresses) => { if (typeof balances === 'undefined') return { bonds: [], fullBondTotal: 0, fullPendingBondTotal: 0, stakingTokenBalance: 0, warmupBalance: 0, tokenBalance: 0, hugsBalance: 0, wsOHMPoolBalance: { tokenBalance: 0, convertedBalance: 0 }, vssBalance: { tokenBalance: 0, convertedBalance: 0, claimable: 0 }, wrappedBalances: { balances: [], total: 0 }, collateralBalances: { balances: [], total: 0 } }; return Object.keys(balances).reduce((acc, address) => { if(!addresses[address]) return acc; const balance = balances[address]; let combinedBonds = []; let wrappedBalanceTotals = 0; let wrappedBalanceList = []; let collateralBalanceTotals = 0; let collateralBalanceList = []; if(typeof balance.bonds !== 'undefined' && typeof acc.bonds !== 'undefined') { combinedBonds = balance.bonds.reduce((bondAcc, bond, index)=> { bondAcc.push({ payout: (acc.bonds[index]?.payout || 0) + bond.payout, pendingPayout: (acc.bonds[index]?.pendingPayout || 0) + bond.pendingPayout, symbol: bond.symbol, lastTime: bond.lastTime }) return bondAcc; },[]) } if(typeof balance.wrappedBalances !== 'undefined' && typeof acc.wrappedBalances !== 'undefined') { wrappedBalanceList = balance.wrappedBalances.balances.reduce((balanceAcc, balance, index)=> { balanceAcc.push({ convertedBalance: (acc.wrappedBalances.balances[index]?.convertedBalance || 0) + balance.convertedBalance, tokenBalance: (acc.wrappedBalances.balances[index]?.tokenBalance || 0) + balance.tokenBalance, symbol: balance.symbol }) return balanceAcc; },[]) wrappedBalanceTotals = acc.wrappedBalances.total + balance.wrappedBalances.total } if(typeof balance.collateralBalances !== 'undefined' && typeof acc.collateralBalances !== 'undefined') { collateralBalanceList = balance.collateralBalances.balances.reduce((balanceAcc, balance, index)=> { balanceAcc.push({ convertedBalance: (acc.collateralBalances.balances[index]?.convertedBalance || 0) + balance.convertedBalance, tokenBalance: (acc.collateralBalances.balances[index]?.tokenBalance || 0) + balance.tokenBalance, symbol: balance.symbol }) return balanceAcc; },[]) collateralBalanceTotals = acc.collateralBalances.total + balance.collateralBalances.total } return { bonds: combinedBonds, fullBondTotal: (acc.fullBondTotal || 0) + (balance.fullBondTotal || 0), fullPendingBondTotal: (acc.fullPendingBondTotal || 0) + (balance.fullPendingBondTotal || 0), stakingTokenBalance: (acc.stakingTokenBalance || 0) + (balance.stakingTokenBalance || 0), tokenBalance: (acc.tokenBalance || 0) + (balance.tokenBalance || 0), warmupBalance: (acc.warmupBalance || 0) + (balance.warmupBalance || 0), hugsBalance: (acc.hugsBalance || 0) + (balance.hugsBalance || 0), wsOHMPoolBalance: { tokenBalance: (acc.wsOHMPoolBalance.tokenBalance || 0) + (balance.wsOHMPoolBalance.tokenBalance || 0), convertedBalance: (acc.wsOHMPoolBalance.convertedBalance || 0) + (balance.wsOHMPoolBalance.convertedBalance || 0) }, vssBalance: { tokenBalance: (acc.vssBalance.tokenBalance || 0) + (balance.vssBalance.tokenBalance || 0), convertedBalance: (acc.vssBalance.convertedBalance || 0) + (balance.vssBalance.convertedBalance || 0), claimable: (acc.vssBalance.claimable || 0) + (balance.vssBalance.claimable || 0) }, wrappedBalances: { total: wrappedBalanceTotals, balances: wrappedBalanceList }, collateralBalances: { total: collateralBalanceTotals, balances: collateralBalanceList }, }; }, { bonds: [], fullBondTotal: 0, fullPendingBondTotal: 0, stakingTokenBalance: 0, tokenBalance: 0, warmupBalance: 0, hugsBalance: 0, wsOHMPoolBalance: { tokenBalance: 0, convertedBalance: 0 }, vssBalance: { tokenBalance: 0, convertedBalance: 0, claimable: 0 }, wrappedBalances: { balances: [], total: 0 }, collateralBalances: { balances: [], total: 0 } }); } const formatRebase = (stakedBalance, otherBalance, price, stakingRebase, count, currency) => { let fractionDigits = 2; if(currency === 'ETH' || currency === 'BTC') { fractionDigits = 8; } const percent = (Math.pow(1 + stakingRebase, count) - 1); return { tokenProfit: Number( (percent * stakedBalance) ).toLocaleString(undefined, { minimumFractionDigits: 4, maximumFractionDigits: 4 }), profit: Number( (percent * stakedBalance * price) ).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), total: Number( ((otherBalance + (stakedBalance + (percent * stakedBalance))) * price) ).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), tokenCount: Number( (stakedBalance + (percent * stakedBalance)).toFixed(4) ), percent: Number( (percent * 100) ).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }; }; const formatStakingInfo = (stakingInfo, currency) => { let fractionDigits = 2; if(currency === 'ETH' || currency === 'BTC') { fractionDigits = 8; } if(stakingInfo === null) return stakingInfo; // console.log('stakingReward/circulatingSupply', stakingInfo.stakingRebase); // console.log('rebases per day', stakingInfo.distributeInterval); // console.log('1 Rebase',Number(( // (Math.pow(1 + stakingInfo.stakingRebase, // 1) - 1) * 100) // .toFixed(4)) // .toLocaleString()); return { ...stakingInfo, price: Number(stakingInfo.rawPrice).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }), apy: Number(( (Math.pow(1 + stakingInfo.stakingRebase, stakingInfo.distributeInterval * 365) - 1) * 100) .toFixed(0)) .toLocaleString(), rawApy: Number(( (Math.pow(1 + stakingInfo.stakingRebase, stakingInfo.distributeInterval * 365) - 1) * 100) .toFixed(0)), rawTVL:(Number(stakingInfo.lockedValue) * Number(stakingInfo.rawPrice)), $LPLiquidity: Number(stakingInfo.rawLPLiquidity) .toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }), $TVL: (Number(stakingInfo.lockedValue) * Number(stakingInfo.rawPrice)).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }), $Staked: (Number(stakingInfo.circulatingSupply) / Number(stakingInfo.totalSupply)).toLocaleString(undefined, { style: 'percent', minimumFractionDigits: 2, maximumFractionDigits: 2 }), $Circ: (Number(stakingInfo.circulatingSupply) * Number(stakingInfo.rawPrice)).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }), $MC: (Number(stakingInfo.totalSupply) * Number(stakingInfo.rawPrice)).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }), rawMC: (Number(stakingInfo.totalSupply) * Number(stakingInfo.rawPrice)), $RFV: Number(stakingInfo.totalReserves).toLocaleString(undefined, { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }), $BackedPrice: (Number(stakingInfo.totalReserves) / Number(stakingInfo.totalSupply)).toLocaleString() } }; const getMemoizedFarm = (farmKey) => createSelector( (state)=> state.farms[farmKey], (state) => state.balances[farmKey], (state) => state.app.addresses, (state) => state.app.fiatCurrency, (farm, balances, addresses, fiatCurrency) => { return getFarm(farm, balances, addresses, fiatCurrency); } ) export { combineBalances, getFarm, formatRebase, getMemoizedFarm }import React, {Component} from 'react'; import {Link} from 'react-router'; export default class App extends Component { render() { return ( <div> <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="navbar-header"> <Link to="/" className="navbar-brand">Home</Link> </div> <div className="navbar-collapse"> <ul className="nav navbar-nav navbar-right"> <li><Link to="/posts/new" activeStyle={{color: '#3CBFE7'}}>Add new post</Link></li> </ul> </div> </div> </nav> <div className="col-xs-12"> {this.props.children} </div> </div> ); } } import { take, call, put, select, takeLatest } from 'redux-saga/effects'; import * as types from './constants'; import * as api from 'utils/api'; import axios from 'axios'; import * as actions from './actions'; function* getProfile(){ const store = JSON.parse(sessionStorage.getItem('store')); const resp = yield call(api.getDetail, `Stores?username=${store.username}`); const { status, data } = resp; yield put(actions.getProfileSuccess(data)); } function* saveProfile(){ var profile = yield select(state => state.profileContainer.data); const res = yield call(api.put, 'Stores/update', profile); const { status, data } = res; if (status === 204) { yield put(actions.saveProfileSuccess()); } } // Individual exports for testing export default function* profileContainerSaga() { yield takeLatest(types.GET_PROFILE, getProfile); yield takeLatest(types.SAVE_PROFILE,saveProfile ); } import axios from 'axios'; export function fetchShipGroups() { return (dispatch) => { return axios.post('/api/eve-fitting-simulator/groups') .then(response => dispatch({ type: 'FETCH_SHIP_GROUPS', payload: response.data })) .catch(err => console.log(err)); }; } export function fetchShipGroup(id) { return (dispatch) => { return axios.post('/api/eve-fitting-simulator/group', {id: id}) .then(response => dispatch({ type: 'FETCH_CURRENT_SHIP_GROUP', payload: response.data })) .catch(err => console.log(err)); }; } export function fetchShip(id) { return (dispatch) => { return axios.post('/api/eve-fitting-simulator/ship', {id: id}) .then(response => dispatch({type: 'FETCH_SHIP', payload: response.data})) .catch(err => console.log(err)); }; } export function fetchModuleGroups(id) { return (dispatch) => { return axios.post('/api/eve-fitting-simulator/module-groups', {id: id}) .then(response => dispatch({type: 'FETCH_MODULE_GROUPS', payload: response.data})) .catch(err => console.log(err)); }; } export function fetchModuleGroup(id) { return (dispatch) => { return axios.post('/api/eve-fitting-simulator/module-group', {id: id}) .then(response => dispatch({type: 'FETCH_MODULE_GROUP', payload: response.data})) .catch(err => console.log(err)); }; } export function fetchDogma(id) { return (dispatch) => { return axios.post('/api/eve-fitting-simulator/dogma') .then(response => dispatch({type: 'FETCH_DOGMA', payload: response.data})) .catch(err => console.log(err)); }; } (function() { // Create the connector object var myConnector = tableau.makeConnector(); // Define the schema myConnector.getSchema = function(schemaCallback) { var cols = [ /*{ id: "Humidity", dataType: tableau.dataTypeEnum.float }, { id: "Temperature", //alias: "pm 2.5 value", dataType: tableau.dataTypeEnum.float }, { id: "Light", //alias: "unit", dataType: tableau.dataTypeEnum.float }, { id: "Soil", //alias: "latitude", dataType: tableau.dataTypeEnum.int }, { id: "Wifi", alias: "Wifi Signal", dataType: tableau.dataTypeEnum.int }, { id: "Wifirssi", alias: "Wifi rssi", dataType: tableau.dataTypeEnum.int }, { id: "LightState", alias: "Light State", dataType: tableau.dataTypeEnum.int }, { id: "WaterState", alias: "Water State", dataType: tableau.dataTypeEnum.int }, */ { id: "Timestamp", alias: "Test10", dataType: tableau.dataTypeEnum.int }]; var tableSchema = { id: "SensorFeed", alias: "Sensor Data from Elasticsearch", columns: cols }; schemaCallback([tableSchema]); }; // Download the data myConnector.getData = function(table, doneCallback) { //$.getJSON("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_week.geojson", function(resp) { //$.getJSON("http://192.168.3.11:9200/mysensor/_search?q=*:*&sort=timestamp:desc&size=60", function(resp) { //d3.json("https://api.openaq.org/v1/measurements?date_from=2019-03-20¶meter=pm25&coordinates=47.597,-122.3197&radius=20000", function(resp) { d3.json("http://192.168.3.11:9200/mysensor/_search", function(resp) { var feat = resp.hits.hits, tableData = []; // Iterate over the JSON object for (var i = 0, len = feat.length; i < len; i++) { tableData.push({ /* "Humidity": feat[i]._source.humidity, "Temperature": feat[i]._source.temperature, "Light": feat[i]._source.light, "Soil": feat[i]._source.soil, "Wifi": feat[i]._source.wifi_signal, "Wifirssi": feat[i]._source.wifi_rssi, "WaterState": feat[i]._source.water_state, "LightState": feat[i]._source.light_state, */ "Timestamp": len+i//new Date(feat[i]._id) }); } table.appendRows(tableData); doneCallback(); }); }; tableau.registerConnector(myConnector); // Create event listeners for when the user submits the form $(document).ready(function() { $("#submitButton").click(function() { tableau.connectionName = "Elasticsearch Sensor Feed"; // This will be the data source name in Tableau tableau.submit(); // This sends the connector object to Tableau }); }); })(); const path = require(`path`) exports.createPages = async ({ graphql, actions, reporter }) => { const { createPage, createRedirect } = actions createRedirect({ fromPath: '/', toPath: '/home', redirectInBrowser: true, isPermanent: true }) // const BlogPostTemplate = path.resolve('./src/templates/BlogPost.js') const PageTemplate = path.resolve('./src/templates/Page.js') const PostsTemplate = path.resolve('./src/templates/Posts.js') const PortfolioUnderContentTemplate = path.resolve( './src/templates/PortfolioUnderContent.js' ) const PortfolioPostTemplate = path.resolve('./src/templates/PortfolioPost.js') // query content for WordPress posts const result = await graphql(` query { allWordpressPage { edges { node { id slug status template title content wordpress_id } } } allWordpressWpPortfolio { edges { node { id slug content title excerpt featured_media { source_url } acf { portfolio_url } } } } allWordpressPost { edges { node { title content excerpt wordpress_id date(formatString: "MMM Do YYYY HH:mm") slug } } } } `) if (result.errors) { reporter.panicOnBuild(`Error while running GraphQL query.`) return } const Pages = result.data.allWordpressPage.edges Pages.forEach(page => { // console.log(page.node.title, page.node.template) createPage({ path: `/${page.node.slug}`, component: page.node.template === 'portfolio_under_content.php' ? PortfolioUnderContentTemplate : PageTemplate, context: page.node }) }) const Posts = result.data.allWordpressPost.edges const postsPerPage = 2 const numberOfPages = Math.ceil(Posts.length / postsPerPage) Array.from({ length: numberOfPages }).forEach((post, index) => { createPage({ path: index === 0 ? `/blog` : `/blog/${index + 1}/`, component: PostsTemplate, context: { posts: Posts.slice( index * postsPerPage, index * postsPerPage + postsPerPage ), numberOfPages, currentPage: index + 1 } }) }) Posts.forEach(post => { createPage({ path: `/post/${post.node.slug}`, component: PageTemplate, context: post.node }) }) const PortfolioPosts = result.data.allWordpressWpPortfolio.edges PortfolioPosts.forEach(portfolioPost => { createPage({ path: `/portfolio/${portfolioPost.node.slug}`, component: PortfolioPostTemplate, context: portfolioPost.node }) }) } function getInput() { let inputE = document.getElementById(ID_INPUT_BOX); return inputE.value; } function getOutput(input) { output = ""; l = input.length; for (let i = 0; i < l; i++) { m = getMorseFromChar(input.charAt(i)); if (i != l-1) { output += m + CHAR_SEP; } } return output; } function convert() { console.log("converting..."); let input = getInput(); console.log("got input: '" + input + "'"); let output = getOutput(input); console.log("got output: '" + output + "'"); let outputE = document.getElementById(ID_OUTPUT_BOX); outputE.value = output; }module.exports = function () { return { map: { PUT: { '/log': { body: '', responseCode: 200, header: { 'Content-Type': 'application/json' }, }, }, POST: { '/some/post/request': { body: '{ "key" : "value" }', responseCode: 200, headers: { 'Content-Type': 'application/json' }, }, }, GET: { '/some/get/request': { body: '{ "key" : "value" }', responseCode: 200, headers: { 'Content-Type': 'application/json' }, }, }, }, }; }; /*______________ | ______ | U I Z E J A V A S C R I P T F R A M E W O R K | / / | --------------------------------------------------- | / O / | MODULE : Uize.Date.Formatter Package | / / / | | / / / /| | ONLINE : http://www.uize.com | /____/ /__/_| | COPYRIGHT : (c)2009-2015 UIZE | /___ | LICENSE : Available under MIT License or GNU General Public License |_______________| http://www.uize.com/license.html */ /* Module Meta Data type: Package importance: 4 codeCompleteness: 100 docCompleteness: 100 */ /*? Introduction The =Uize.Date.Formatter= module provides methods for formatting and parsing date strings, supporting a wide variety of different formatting options. *DEVELOPERS:* `<NAME>` In a Nutshell The =Uize.Date.Formatter= module is a package under the =Uize.Date= namespace. Date Component For the purposes of discussing the formatting of date strings, a date is comprised of multiple date components, such as year, month, month name, day, day name, hour, minutes, etc. For each Date Component there is a corresponding `date component token` that can be used within a `date format` string to indicate the placement for the value for that component. Date Component Token A date component token is one of the many available `date component tokens` that can appear inside a `date format` string and that indicate where `date component` values should be placed. Date component tokens are comprised of a `date component` name enclosed inside curly braces. For example, the date component token for the year formatted using four digits is ={YYYY}=. Date Component Token Value A date component token value is a value for a specific `date component token` for a specific date. For example, for the date September 11th, 2001, the date component token value for the ={monthName}= date component token would be ='September'=, while the date component token value for the ={YYYY}= date component token would be ='2<PASSWORD>'=. When `formatting a date string`, every `date component token` in a `date format` string will be replaced with the date component token value for the specific date being formatted. Conversely, when `parsing a date string`, a date component token value is "captured" for every date component token in the date format string, after which a date object is produced by combining the values for all the components of the date together. Date Component Tokens The =Uize.Date.Formatter= module supports the following date component tokens... {date} The full date, as serialized by JavaScript's built-in =Date= object. NOTES - the =Uize.Date.Formatter.parse= method does currently not support parsing the ={date}= `date component token` - because the value for this token is serialized by the built-in =Date= object, the exact formatting may vary depending on the JavaScript interpreter being used {YYYY} The full year, represented using four digits, where leading zeros will be added as needed for dates before the year 1000. {YY} The year, represented using only two digits (ie. only year of century). When `parsing a date string` where the year is represented using the ={YY}= token, the year is assumed to be in the 20th century (ie. the value =99= represents the year 1999). When `formatting a date string` where the year is represented using the ={YY}= token, century information will be lost. Therefore, this token can only be safely used in a `date format` that will be applied to dates in the 20th century. {MM} The month number, represented always using two digits (ie. leading =0= if necessary), where January is represented by the value =01=, and where December is represented by the value =12=. {monthNo} The month number, represented using only as many digits as necessary (ie. no leading =0=), where January is represented by the value =1=, and where December is represented by the value =12=. {monthName} The full name of the month, as registered in the =Uize.Date.monthNames= static property of the =Uize.Date= module. Unless overriding the value of the =Uize.Date.monthNames= static property, the month names will be the English names January, February, March, April, May, June, July, August, September, October, November, and December. {shortMonthName} The short name of the month, as registered in the =Uize.Date.shortMonthNames= static property of the =Uize.Date= module. Unless overriding the value of the =Uize.Date.shortMonthNames= static property, the short month names will be derived from the English month names, as Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. {DD} The day number, represented always using two digits (ie. leading =0= if necessary), where the first day of any month is represented by the value =01=, and where the last day of the month January is represented by the value =31=. {dayNo} The day number, represented using only as many digits as necessary (ie. no leading =0=), where the first day of any month is represented by the value =1=, and where the last day of the month January is represented by the value =31=. {dayNoSuffix} An English language suffix that can be appended after the value for the ={dayNo}= token in order to produce friendlier and more human readable date strings. The suffixes ='st'=, ='nd'=, ='rd'=, and ='th'= are registered in the =Uize.Date.dayNoSuffixes= static property of the =Uize.Date= module. The ={dayNoSuffix}= token can be combined with the ={dayNo}= token, as in ={dayNo}{dayNoSuffix}=, to produce formatted results like =1st=, =2nd=, =3rd=, etc. The rules for determining the suffix for a particular day number are as follows... - ='th'= - for the day numbers =10= to =19=, and for all other day numbers whose first digit is either =0= or is greater than =3= (so, day numbers =4= through =20=, and =24= through =30=) - ='st'= - for any day number whose first digit is =1=, excepting the special case of =11= (so, day numbers =1=, =21=, and =31=) - ='nd'= - for any day number whose first digit is =2=, excepting the special case of =12= (so, day numbers =2= and =22=) - ='rd'= - for any day number whose first digit is =3=, excepting the special case of =13= (so, day numbers =3= and =23=) ................................... DAY NUMBER(S) | DAY NUMBER SUFFIX ---------------+------------------- 1 | st 2 | nd 3 | rd 4-20 | th 21 | st 22 | nd 23 | rd 24-30 | th 31 | st ................................... Because multiple days in a month can have the same day number suffix, the value of the ={dayNoSuffix}= token is ambiguous and is not considered meaningful when parsing date strings formatted using this token - it is simply ignored. {dayName} The full name of the day, as registered in the =Uize.Date.dayNames= static property of the =Uize.Date= module. Unless overriding the value of the =Uize.Date.dayNames= static property, the day names will be the English names Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. Because multiple days in a month can occur on the same day of the week and have the same day name, the value of the ={dayName}= token is ambiguous and is not considered meaningful when parsing date strings formatted using this token - it is simply ignored. {shortDayName} The short name of the day, as registered in the =Uize.Date.shortDayNames= static property of the =Uize.Date= module. Unless overriding the value of the =Uize.Date.shortDayNames= static property, the short day names will be derived from the English day names, as Mon, Tue, Wed, Thu, Fri, Sat, and Sun. Because multiple days in a month can occur on the same day of the week and have the same short day name, the value of the ={shortDayName}= token is ambiguous and is not considered meaningful when parsing date strings formatted using this token - it is simply ignored. {hh} The hour in military time ([[http://en.wikipedia.org/wiki/24-hour_clock][24-hour clock]]), represented always using two digits (ie. leading =0= if necessary), where 12am (midnight) is represented by the value =00=, where 12pm (midday) is represented by the value =12=, and where 11pm is represented by the value =23=. {h12} The hour of the day in 12-hour notation, represented using only as many digits as necessary (ie. no leading =0=), where 12am (midnight) and 12pm (midday) are both represented by the value =12=, and where 1am and 1pm are both represented by the value =1=. Because the ={h12}= token does not convey whether the time is in the first or second half of the day, this token should be used in conjunction with the companion ={ampm}= token. {hh12} The hour of the day in 12-hour notation, represented always using two digits (ie. leading =0= if necessary), where 12am (midnight) and 12pm (midday) are both represented by the value =12=, and where 1am and 1pm are both represented by the value =01=. Because the ={hh12}= token does not convey whether the time is in the first or second half of the day, this token should be used in conjunction with the companion ={ampm}= token. {mm} The minutes of the hour, represented always using two digits (ie. leading =0= if necessary), where the first minute of the hour is represented by the value =00=, and where the last minute of the hour is represented by the value =59=. {minutes} The minutes of the hour, represented using only as many digits as necessary (ie. no leading =0=), where the first minute of the hour is represented by the value =0=, and where the last minute of the hour is represented by the value =59=. {ss} The seconds of the minute, represented always using two digits (ie. leading =0= if necessary), where the first second of the minute is represented by the value =00=, and where the last second of the minute is represented by the value =59=. {seconds} The seconds of the minute, represented using only as many digits as necessary (ie. no leading =0=), where the first second of the minute is represented by the value =0=, and where the last second of the minute is represented by the value =59=. {zzz} The milliseconds of the second, represented always using three digits (ie. leading zeros as necessary), where the first millisecond of the second is represented by the value =000=, and where the last millisecond of the second is represented by the value =59=. {milliseconds} The milliseconds of the second, represented using only as many digits as necessary (ie. no leading zeros), where the first millisecond of the second is represented by the value =0=, and where the last millisecond of the second is represented by the value =999=. {ampm} An indicator of which half of the day the hour is in, where the first half of the day (morning) is represented by the value =am=, and where the second half of the day (afternoon and evening) is represented by the value =pm=. When using either of the ={h12}= or ={hh12}= tokens to indicate hour of day in a `date format` string, it is important to also use the ={ampm}= token in order to disambiguate between the two halves of the day. Date Component Tokens Example The following table uses the example date "Sat Sep 8 2007 18:03:05" to show the `date component token value` for each of the `date component tokens` supported by the =Uize.Date.Formatter= module. .................................................................................. DATE COMPONENT TOKEN | VALUE (using the example date Sat Sep 8 2007 18:03:05) ----------------------+----------------------------------------------------------- {date} | Sat Sep 08 2007 18:03:05 GMT-0700 (Pacific Daylight Time) {YYYY} | 2007 {YY} | 07 {MM} | 09 {monthNo} | 9 {monthName} | September {shortMonthName} | Sep {DD} | 08 {dayNo} | 8 {dayNoSuffix} | th {dayName} | Saturday {shortDayName} | Sat {hh} | 18 {h12} | 6 {hh12} | 06 {mm} | 03 {minutes} | 3 {ss} | 05 {seconds} | 5 {zzz} | 000 {milliseconds} | 0 {ampm} | pm .................................................................................. Date Format A date format is specified by a date format string, which contains one or more `date component tokens` separated by optional `date format static text`. EXAMPLE ......................................................................................... DATE FORMAT STRING | EXAMPLE FORMATTED DATE STRING -------------------------------------------------------+--------------------------------- {dayName}, {dayNo}{dayNoSuffix} of {monthName}, {YYYY} | Tuesday, 11th of September, 2001 ......................................................................................... Date Format and Formatting Dates When `formatting a date string` using a specified `date format`, each `date component token` in the date format string is replaced by the corresponding `date component token value` for the date being formatted. Any `date format static text` separating the tokens is left undisturbed and makes its way into the formatted date string. As you can tell from the above example, all the tokens have been replaced with the appropriate values for our example date, the historically significant September 11th, 2001. The static text - such as the comma, spaces, and the "of" - have been left in. The end result is an elegantly formatted date. Date Format and Parsing Dates When `parsing a date string` to produce a date object, the `date format` must be specified in order for the parser to know how to parse the string. The parser takes the specified `date format` string and translates it into a sophisticated regular expression that is used to match against the date string being parsed and then "capture" the values for the various `date component tokens` in the date format string. If the regular expression cannot be matched against a date string being parsed, then that date string is not formatted according to the specified date format, and the parser will produce the value =undefined=. Date Format Static Text A `date format` string may contain static text arround the one or more `date component tokens`. Static text can be used to introduce separator characters between year, month, and day, for example. Static text can also be used to create more elegant and more human readable date strings. For instance, in the date format string ='{dayName}, {dayNo}{dayNoSuffix} of {monthName}, {YYYY}'=, the commas, spaces, and the "of" static text all contribute to friendlier date strings, such as the date string "Tuesday, 11th of September, 2001". A Bad Date The formatting and parsing methods of the =Uize.Date.Formatter= module don't care which of the `date component tokens` are used or how they are used. Insufficient tokens could be used to fully convey the date. Or, the same token could be used multiple times, either to produce silly results or to express a date in multiple ways in the same formatted result. The wrong tokens could be used in the wrong places to produce incorrect representations of a date. Bottom line: specifying a silly `date format` string will produce a silly result. EXAMPLE ......................................................................... alert ( Uize.Date.Formatter.format ( new Date ('Sat Sep 8 2007 18:03:05'), '{ss}:{mm}:{h12}{ampm} on {YYYY}{dayNoSuffix} {monthName} {dayNo}', ) ); ......................................................................... In the above example, the date ='Sat Sep 8 2007 18:03:05'= is being formatted using the `date format` string ='{ss}:{mm}:{h12}{ampm} on {YYYY}{dayNoSuffix} {monthName} {dayNo}'=, and the resulting date string is then displayed in an alert dialog. The alert dialog will show the value ='05:03:6pm on 2007th September 8'=. Any human reading this date string will be completely confused. It's not a date that makes any sense. That said, if this date string was parsed using the =Uize.Date.Formatter.parse= method and using the same format that was used to produce it, then the correct original date would be produced. Formatting a Date String Date objects can be formatted to produce date strings using the =Uize.Date.Formatter.format= static method. When using the =Uize.Date.Formatter.format= method to format a date string, any or all of the available `date component tokens` can be utilized. For instance, you could format a date to a string and only utilize the year component. In cases where only a subset of the date components are used to format a date string, parsing a date string formatted in that way can result in a `loss of date detail`. For more info on formatting date strings, see the reference for the =Uize.Date.Formatter.format= method. Parsing a Date String Date strings can be parsed to produce date objects using the =Uize.Date.Formatter.parse= static method. When using the =Uize.Date.Formatter.parse= method to parse a date string, the `date format` for the date string must be specified in order for this method to know how to parse the date string. When parsing a date string, if the `date format` only utilizes a subset of the available date components, then a `loss of date detail` can occur and the resulting date object will have default values for the date components for which no data is present in the date string, according to the rules of the `date component defaults`. For example, if you were to parse a date string that only had a year component, then the month, day, hour, minutes, seconds, and milliseconds would be defaulted. For more info on parsing date strings, see the reference for the =Uize.Date.Formatter.parse= method. Date Component Defaults A `date format` string is not required to contain tokens for every `date component`, and so there is date component defaulting logic that is employed when `parsing a date string` that does not contain complete date information. The value defaulting for the different components of a date is as follows... - *year* - When there is no ={YYYY}= or ={YY}= token in the `date format` string, then the year for the date will be defaulted to the year =0=. - *month* - When there is no ={MM}=, ={monthNo}=, ={monthName}=, or ={shortMonthName}= token in the `date format` string, then the month for the date will be defaulted to the first month of the year (ie. January). - *day number* - When there is no ={DD}= or ={dayNo}= token in the `date format` string, then the day of the month for the date will be defaulted to =0= (ie. the first day of the month). - *hour* - When there is no ={hh}=, ={h12}=, or ={hh12}= token in the `date format` string, then the default value for the hour of the day will be determined by the value of the ={ampm}= token, if present. If the ={ampm}= token is present, then the hour of the day will be defaulted to =0= when the value of the ={ampm}= token is "am" (ie. the hour is defaulted to 12am), and the hour will be defaulted to =12= when the value of the ={ampm}= token is "pm" (ie. the hour is defaulted to 12pm). If the ={ampm}= token is *not* present, then the hour of the day will be defaulted to =0= (ie. 12am). - *ampm* - When there is no ={ampm}= token in the `date format` string, and when the hour of the day is specified using either of the ={h12}= or ={hh12}= tokens, then the time of day is defaulted to morning. - *minutes* - When there is no ={mm}= or ={minutes}= token in the `date format` string, then the minutes of the hour for the date will be defaulted to =0= (ie. the first minute of the hour). - *seconds* - When there is no ={ss}= or ={seconds}= token in the `date format` string, then the seconds of the minute for the date will be defaulted to =0= (ie. the first second of the minute). - *milliseconds* - When there is no ={zzz}= or ={milliseconds}= token in the `date format` string, then the milliseconds of the second for the date will be defaulted to =0= (ie. the first millisecond of the second). Loss of Date Detail Date detail can be lost when parsing a date string that is in a `date format` that doesn't contain a `date component token value` for all of the components of a date. In a rather typical case, a date object may be formatted to a date string and only include the components for year, month, and day - omitting the time of day components. In such cases, the time of day of the source date object will be lost when formatting it to a date string. Consequently, if the formatted date string is later parsed back to a date object, the time of day will be defaulted according to the rules of the `date component defaults`. Consider the following example... EXAMPLE ....................................................................... var date = new Date ('Sat Sep 8 2007 18:03:05'), dateFormat = '{YYYY}-{MM}-{DD}', formattedDateStr = Uize.Date.Formatter.format (date,dateFormat), parsedDate = Uize.Date.Formatter.parse (formattedDateStr,dateFormat) ; alert (+date == +parsedDate); // alerts "false" ....................................................................... In the above example, the date "Sat Sep 8 2007 18:03:05" is being formatted to a date string using the date format ='{YYYY}-{MM}-{DD}'=, which produces the date string ='2007-09-08'=. Then, this date string is being parsed using the same date format, and the resulting date object is being assigned to the =parsedDate= variable. The =alert= statement compares the time in milliseconds of the original date against the time in milliseconds of the parsed date. In this case they are not the same, because the date string ='2007-09-08'= that is being parsed has lost the original time of day information. Instead, the parsed date will be initialized to the time 12am (the beginning of the day), according to the rules of the `date component defaults`. */ Uize.module ({ name:'Uize.Date.Formatter', builder:function () { 'use strict'; var /*** Variables for Scruncher Optimization ***/ _Uize_Date = Uize.Date, _format = _Uize_Date.format, /*** General Variables ***/ _tokenMatcherRegExp, _tokenNameToValueRegExpString = { YYYY:'\\d{4}', YY:'\\d\\d', MM:'1[0-2]|0[1-9]', monthNo:'1[0-2]|0?[1-9]', DD:'30|31|[1-2]\\d|0[1-9]', dayNo:'30|31|[1-2]\\d|0?[1-9]', dayNoSuffix:_Uize_Date.dayNoSuffixes.join ('|'), hh:'[0-1]\\d|2[0-3]', h12:'1[0-2]|0?[1-9]', hh12:'1[0-2]|0[1-9]', mm:'[0-5]\\d', minutes:'[0-5]?\\d', ss:'[0-5]\\d', seconds:'[0-5]?\\d', zzz:'\\d{3}', milliseconds:'\\d{1,3}', ampm:'am|pm' }, _dynamicTokenValueRegExpStrings = ['monthName','shortMonthName','dayName','shortDayName'], _ctrlG = String.fromCharCode (7) ; /*** Utility Functions ***/ function _findValueInArrayCaseInsensitive (_values,_value) { /* TO DO: the Uize.indexIn method could be used if it had an option for doing a case insensitive search */ _value = _value.toLowerCase (); for (var _valueNo = -1, _valuesLength = _values.length; ++_valueNo < _valuesLength;) if (_value == _values [_valueNo].toLowerCase ()) return _valueNo ; return -1; } return Uize.package ({ format:_format, /*? Static Methods Uize.Date.Formatter.format Returns a string, being the specified date formatted using the specified formatting. SYNTAX ................................................................... dateStr = Uize.Date.Formatter.format (dateSTRorNUMorOBJ,formatSTR); ................................................................... The date to be formatted is specified using the =dateSTRorNUMorOBJ= parameter. Before the date is formatted, the value of the =dateSTRorNUMorOBJ= parameter is resolved to a date object using the =Uize.Date.resolve= static method of the =Uize.Date= module. The format to be used is specified as a `date format` string, where each of the `date component tokens` specified in the format string (enclosed in the curly braces ={= and =}=) is replaced by the corresponding `date component token value` derived from the specified date. Consider the following example... EXAMPLE ........................................................................................ Uize.Date.Formatter.format ('Sat Sep 8 2007','{YYYY}/{MM}/{DD}'); // RESULT: 2007/09/08 ........................................................................................ In the above example, the date value ='Sat Sep 8 2007'= is being formatted using the `date format` string ='{YYYY}/{MM}/{DD}'= to produce the result ='2007/09/08'=. MORE EXAMPLES ............................................................................ var date = 'Sat Sep 8 2007 18:03:05'; Uize.Date.Formatter.format (date,'{YY}-{MM}-{DD}'); // RESULT : 07-09-08 Uize.Date.Formatter.format (date,'{YYYY}/{MM}/{DD}'); // RESULT : 2007/09/08 Uize.Date.Formatter.format (date,'{YYYY}{MM}{DD}'); // RESULT : 20070908 Uize.Date.Formatter.format (date,'{dayNo} {shortMonthName} {YYYY}'); // RESULT : 8 Sep 2007 Uize.Date.Formatter.format (date,'{dayNo}{dayNoSuffix} {monthName} {YYYY}'); // RESULT : 8th September 2007 Uize.Date.Formatter.format ( date, '{monthName} {dayNo}{dayNoSuffix}, {YYYY} ({h12}:{mm}{ampm})' ); // RESULT : September 8th, 2007 (6:03pm) Uize.Date.Formatter.format (date,'{YYYY}/{MM}/{DD} ({hh}:{mm}:{ss})'); // RESULT : 2007/09/08 (18:03:05) Uize.Date.Formatter.format ( date, '{minutes} minutes and {seconds} seconds past {h12}{ampm}' ); // RESULT : 3 minutes and 5 seconds past 6pm Uize.Date.Formatter.format ( date, '{monthNo}/{dayNo}/{YYYY} is {YYYY}-{MM}-{DD} in ISO 8601' ); // RESULT : 9/8/2007 is 2007-09-08 in ISO 8601 ............................................................................ The above example shows how the date value ='Sat Sep 8 2007 18:03:05'= would be formatted using a variety of wildly different `date format` strings. VARIATION ......................................................... dateStr = Uize.Date.Formatter.format (dateSTRorNUMorOBJ); ......................................................... When no =formatSTR= parameter is specified, then the value for this parameter will be defaulted to ='{dayName}, {dayNo}{dayNoSuffix} {monthName} {YYYY}'=. This is equivalent to using the =Uize.Date.Formatter.toPretty= static method. NOTES - see the companion =Uize.Date.Formatter.parse= static method - see the related =Uize.Date.Formatter.toPretty= static method - when the value =''= (empty string), =null=, or =undefined= is specified for the =dateSTRorNUMorOBJ= parameter, then this parameter will be defaulted to the date at the time that the method is called (today's date, essentially) Uize.Date.Formatter.toPretty Returns a string, representing a "pretty" formatting of the specified date. SYNTAX ................................................................. prettyDateSTR = Uize.Date.Formatter.toPretty (dateSTRorNUMorOBJ); ................................................................. The date to be pretty-formatted can be specified using the =dateSTRorNUMorOBJ= value type. Using the =Uize.Date.Formatter.toPretty= method is equivalent to using the =Uize.Date.Formatter.format= method and specifying the following `date format` string value for its =formatSTR= parameter... PRETTY DATE FORMAT .................................................. {dayName}, {dayNo}{dayNoSuffix} {monthName} {YYYY} .................................................. Following are some examples of pretty-formatted dates... EXAMPLES ............................ Friday, 15th December 2006 Tuesday, 23rd February 1999 Friday, 4th July 2008 Thursday, 1st April 2004 Saturday, 2nd September 2006 ............................ NOTES - see the related =Uize.Date.Formatter.format= static method - when the value =''= (empty string), =null=, or =undefined= is specified for the =dateSTRorNUMorOBJ= parameter, then this parameter will be defaulted to the date at the time that the method is called (today's date, essentially) */ toPretty:_format, parse:function (_date,_format) { var _tokenName; /*** return early for dates specified as Date object, null, undefined, empty string, or number ***/ if (typeof _date == 'object' && _date && !(_date instanceof Date)) _date = _date.valueOf (); if (_date instanceof Date) return _date; if (_date == null || _date == '') return; if (typeof _date == 'number') return new Date (_date); /*** use Uize.Date.resolve method if no format is specified ***/ if (!_format) return _Uize_Date.resolve (_date); /*** re-initialize dynamic token value RegExp strings ***/ Uize.lookup (_dynamicTokenValueRegExpStrings,null,_tokenNameToValueRegExpString); if (!_tokenMatcherRegExp) _tokenMatcherRegExp = new RegExp ( '\\{(' + Uize.keys (_tokenNameToValueRegExpString).join ('|') + ')\\}','g' ) ; var _tokens = [], _tokenNo = 0, _matcher = new RegExp ( Uize.escapeRegExpLiteral ( _format.replace ( _tokenMatcherRegExp, function (_token,_tokenName) { _tokens.push (_tokenName); return _ctrlG; } ) ).replace ( /\s+/g,'\\s+' ).replace ( /\x07/g, function () { return ( '\\s*(' + ( _tokenNameToValueRegExpString [_tokenName = _tokens [_tokenNo++]] || (_tokenNameToValueRegExpString [_tokenName] = _Uize_Date [_tokenName + 's'].join ('|')) ) + ')\\s*' ); } ), 'i' ), _matchSegments = (_date + '').match (_matcher) ; if (_matchSegments) { var _fullYearFourDigit = 0, _monthNo = 1, _dayNo = 1, _hourNo, _h12 = 0, _minutes = 0, _seconds = 0, _milliseconds = 0, _isPm = false ; for ( var _matchSegmentNo = 0, _matchSegmentsLength = _matchSegments.length; ++_matchSegmentNo < _matchSegmentsLength; ) { var _matchSegmentValue = _matchSegments [_matchSegmentNo]; switch (_tokens [_matchSegmentNo - 1]) { /* NOTE: We don't need to do anything for the dayNoSuffix, dayName, and shortDayName tokens, because they are purely cosmetic. */ case 'YYYY': _fullYearFourDigit = +_matchSegmentValue; break; case 'YY': _fullYearFourDigit = 1900 + +_matchSegmentValue; break; case 'MM': case 'monthNo': _monthNo = +_matchSegmentValue; break; case 'monthName': _monthNo = _findValueInArrayCaseInsensitive (_Uize_Date.monthNames,_matchSegmentValue) + 1; break; case 'shortMonthName': _monthNo = _findValueInArrayCaseInsensitive (_Uize_Date.shortMonthNames,_matchSegmentValue) + 1; break; case 'DD': case 'dayNo': _dayNo = +_matchSegmentValue; break; case 'hh': _hourNo = +_matchSegmentValue; break; case 'h12': case 'hh12': _h12 = +_matchSegmentValue; break; case 'mm': case 'minutes': _minutes = +_matchSegmentValue; break; case 'ss': case 'seconds': _seconds = +_matchSegmentValue; break; case 'zzz': case 'milliseconds': _milliseconds = +_matchSegmentValue; case 'ampm': _isPm = /^pm$/i.test (_matchSegmentValue) } } return _Uize_Date ( _fullYearFourDigit, _monthNo, _dayNo, _hourNo !== undefined ? _hourNo : _h12 * (_h12 != 12) + _isPm * 12, _minutes, _seconds, _milliseconds ); } /*? Static Methods Uize.Date.Formatter.parse Returns a date object, that is parsed from the specified date that is formatted in the specified `date format`, or the value =undefined= if the specified date cannot be parsed. SYNTAX ................................................................ dateOBJ = Uize.Date.Formatter.parse (dateANYTYPE,dateFormatSTR); ................................................................ Whereas the =Uize.Date.Formatter.format= method can be used to format a date object using a specified `date format`, the =Uize.Date.Formatter.parse= method can be used to reverse that process and parse a date string that has been formatted using a specific `date format`. Consider the following example.... EXAMPLE ................................................................................... var date = new Date ('Sat Sep 8 2007 18:03:05'), dateFormat = '{h12}:{mm}:{ss}{ampm} on {dayNo}{dayNoSuffix} {monthName} {YYYY}', formattedDateStr = Uize.Date.Formatter.format (date,dateFormat), parsedDate = Uize.Date.Formatter.parse (formattedDateStr,dateFormat) ; alert (+date == +parsedDate); // alerts "true" ................................................................................... In the above example, the date "Sat Sep 8 2007 18:03:05" is being formatted to a date string using the date format ='{h12}:{mm}:{ss}{ampm} on {dayNo}{dayNoSuffix} {monthName} {YYYY}'=, which produces the date string ='6:03:05pm on 8th September 2007'=. Then, this date string is being parsed using the same date format, and the resulting date object is being assigned to the =parsedDate= variable. The =alert= statement compares the time in milliseconds of the original date against the time in milliseconds of the parsed date. They are identical, because the =Uize.Date.Formatter.parse= method is able to successfully parse a date using the same format that was used to format it with the =Uize.Date.Formatter.format= method. A Bad Date When a date string cannot be parsed, then the =Uize.Date.Formatter.parse= method will return the value =undefined=. This could occur if the date string is not a validly formatted date, or if it *is* a perfectly well formatted date that is simply not formatted according to the `date format` string specified when calling the =Uize.Date.Formatter.parse= method. EXAMPLES .................................................................................. Uize.Date.Formatter.parse ('this is not a date','{YYYY}-{MM}-{DD}'); // undefined Uize.Date.Formatter.parse ('2001/09/11','{YYYY}-{MM}-{DD}'); // undefined Uize.Date.Formatter.parse ('Tue Sep 11 2001','{YYYY}-{MM}-{DD}'); // undefined .................................................................................. All of the statements in the above example will return the value =undefined=. In the first statement, the value of the =dateANYTYPE= parameter is clearly not a date (it even says so). In the other statements, the date strings specified in the =dateANYTYPE= parameter do not match the formats specified in the =dateFormatSTR= parameter. Extraneous Text Ignored Any extraneous text in a date string around a portion of the date string that is matched by the specified `date format` will be ignored. Consider the following example... EXAMPLE ............................................................................... Uize.Date.Formatter.parse ('DATE --> 2001-09-11 <-- DATE','{YYYY}-{MM}-{DD}'); ............................................................................... In the above example, the text substring "2001-09-11" is matched by the `date format` ='{YYYY}-{MM}-{DD}'=. The extraneous text around the date that points with arrows to the ISO8601 formatted date is ignored. First Matching Date Wins When a date string contains multiple text substrings that match a specified `date format` string, then the date will be parsed from the first matching substring. Consider the following example... EXAMPLE ....................................................................... Uize.Date.Formatter.parse ('2000-08-08,2001-09-11','{YYYY}-{MM}-{DD}'); ....................................................................... In the above example, the date string that is being parsed contains two text substrings that are ISO8601 formatted dates. Only the first match for the `date format` string is used, and so the date object that is produced by the =Uize.Date.Formatter.parse= method will be for the 8th of August, 2000 - the "2001-09-11" text is ignored. Last Equivalent Date Component Token Wins If a `date format` string contains multiple of the same `date component token`, or multiple different `date component tokens` that are equivalent (such as ={DD}= and ={dayNo}=), then the value for the last equivalent token will override values for previous equivalent tokens. Consider the following example... EXAMPLE ..................................................................................... Uize.Date.Formatter.parse ('2001-09-11 5th','{YYYY}-{MM}-{DD} {dayNo}{dayNoSuffix}'); ..................................................................................... In the above example, a date string is being parsed that is formatted according to the `date format` ='{YYYY}-{MM}-{DD} {dayNo}{dayNoSuffix}'=. Now, this date format has two equivalent date component tokens in it - namely, the ={DD}= and ={dayNo}= tokens. Because the ={dayNo}= token is last in the date string, it wins, and so the produced date object is for the 5th September 2001 - not the 11th. Whitespace Handling In order to be flexible enough to parse a wider array of date strings, the =Uize.Date.Formatter.parse= method has some special rules around handling whitespace in date strings. Optional Token Value Padding All values for `date component tokens` can implicitly have whitespace / padding around them. Consider the following example... EXAMPLE ................................................................ Uize.Date.Formatter.parse ('2001 / 09 / 11','{YYYY}/{MM}/{DD}'); ................................................................ In the above example, the date string is being parsed using the `date format` ='{YYYY}/{MM}/{DD}'=. Now, even though there are no spaces around the slashes in the format, the values for the ={YYYY}=, ={MM}=, and ={DD}= tokens in the date string being parsed can implicitly have an arbitrary amount of surrounding whitespace padding. Therefore, the date string ='2001 / 09 / 11'=, even though it *does* have whitespace padding around the slashes, can be parsed successfully. It's not that the slashes can have padding around them, but that any `date component token value` may have padding around it. Flexible Static Text Whitespace Whitespace within `date format static text` is implicitly treated as flexible, so that some whitespace between non-whitespace characters within the static text will be matched against some whitespace within the corresponding static text of a date string being parsed. Consider the following example... EXAMPLE .................................................. Uize.Date.Formatter.parse ( 'HISTORICALLY IMPORTANT DATE: 2001-09-11', 'HISTORICALLY IMPORTANT DATE: {YYYY}-{MM}-{DD}' ); .................................................. In the above example, the date September 11th, 2001 will be successfully parsed from the date string, even though the static text in the date string contains more whitespace separating the words than the corresponding "HISTORICALLY IMPORTANT DATE" static text in the `date format` string. Static Text Whitespace Required Whitespace within `date format static text` in a `date format` string must exist within the corresponding static text in a date string being parsed in order for it to be parsed successfully. Consider the following example... EXAMPLE .................................................. Uize.Date.Formatter.parse ( 'HistoricallyImportantDate: 2001-09-11', 'Historically Important Date: {YYYY}-{MM}-{DD}' ); .................................................. In the above example, the =Uize.Date.Formatter.parse= method will return the value =undefined= because it will not be able to successfully parse the date string. This is because the whitespace separating the words in the static text of the `date format` string must exist within the corresponding static text of the date being parsed. The exact amount of whitespace is not important, as long as the words / non-whitespace substrings are separated by whitespace in the same spots in both the `date format` string and the date string being parsed. Case Insensitivity In order to be flexible enough to parse a wider array of date strings, the =Uize.Date.Formatter.parse= method performs case insensitive matching when `parsing a date string`. Case insensitivity applies to both the values of `date component tokens` as well as `date format static text`. Consider the following example... EXAMPLES ................................................................ Uize.Date.Formatter.parse ( 'tuesday 11th september 2001', '{dayName} {dayNo}{dayNoSuffix} {monthName} {YYYY}' ); Uize.Date.Formatter.parse ( 'TUE 11TH SEP 2001', '{shortDayName} {dayNo}{dayNoSuffix} {shortMonthName} {YYYY}' ); Uize.Date.Formatter.parse ( 'SePtEmBeR 11tH, 2001', '{monthName} {dayNo}{dayNoSuffix}, {YYYY}' ); Uize.Date.Formatter.parse ( 'historically important date: 2001-09-11', 'HISTORICALLY IMPORTANT DATE: {YYYY}-{MM}-{DD}' ); ................................................................ All of the above statements would correctly parse the date September 11th, 2001. NOTES - see the companion =Uize.Date.Formatter.format= static method - the =Uize.Date.Formatter.parse= method does currently not support parsing the ={date}= `date component token` */ } }); } }); import { PipelineOperatorTest } from './tasks/pipelineOperator/PipelineOperatorTest' import { JsonWithTypeTest } from './tasks/json/JsonWithTypeTest' import { StrX } from 'xbrief' import { GP } from 'elprimero' import { JsonFabTest } from './tasks/json/ObjectShallowCopyTest' test(PipelineOperatorTest.name, () => { PipelineOperatorTest.test() }) // GP.roughlyNow().tag(JsonWithTypeTest.name |> StrX.jv2py) test('JsonFabTest', () => { JsonFabTest.test() }) test('JsonWithTypeTest', () => { JsonWithTypeTest.test() })const util = require('../util'); const _ = require('lodash'); // const filePath = './inputTestB.txt'; const filePath = './input.txt'; function getAddressList(addressList) { if (_.includes(addressList[0], 'X')) { const newAddressList = _.reduce(addressList, (acc, address) => { acc.push(address.replace('X', '1')); acc.push(address.replace('X', '0')); return acc; }, []); return getAddressList(newAddressList); } else { return addressList; } } function main() { const input = util.loadInput(filePath); let currentMask = ''; let data = {}; _.forEach(input, (row) => { const [label, value] = row.split(' = '); if (label === 'mask') { currentMask = value.split(''); } else { const addressInt = _.parseInt(/.*\[(\d*)]/.exec(label)[1]); const valueInt = _.parseInt(value); const address1 = _.padStart(addressInt.toString(2), 36, '0').split(''); const address2 = _.map(currentMask, (maskChar, index) => { if (maskChar === '0') { return address1[index]; } else if (maskChar === '1') { return '1'; } else if (maskChar === 'X') { return 'X'; } }); const addressList = getAddressList([address2.join('')]) _.forEach(addressList, (addressSet) => { data[addressSet] = valueInt; }); } }); const total = _.reduce(data, (acc, value) => { return acc + value; }, 0); console.log('total', total); } main(); <reponame>oonsamyi/flow //@flow function composenum(f: (number)=>number, g: (number)=>number): (number)=>number { function ret(x:number): number { return f(g(x)); } return ret; } function id(x: number): number { return x; } var a: number = composenum(id, id)((42: any)); var b: $Trusted<number> = a; <gh_stars>1-10 // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; const common = require('../common'); const http = require('http'); const net = require('net'); const seeds = [ 3, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 ]; // Set up some timing issues where sockets can be destroyed // via either the req or res. const server = http.createServer(common.mustCall(function(req, res) { switch (req.url) { case '/1': return setImmediate(function() { req.socket.destroy(); server.emit('requestDone'); }); case '/2': return process.nextTick(function() { res.destroy(); server.emit('requestDone'); }); // in one case, actually send a response in 2 chunks case '/3': res.write('hello '); return setImmediate(function() { res.end('world!'); server.emit('requestDone'); }); default: res.destroy(); server.emit('requestDone'); } }, seeds.length)); // Make a bunch of requests pipelined on the same socket function generator(seeds) { const port = server.address().port; return seeds.map(function(r) { return `GET /${r} HTTP/1.1\r\n` + `Host: localhost:${port}\r\n` + '\r\n' + '\r\n'; }).join(''); } server.listen(0, common.mustCall(function() { const client = net.connect({ port: this.address().port }); let done = 0; server.on('requestDone', function() { if (++done === seeds.length) { server.close(); } }); // immediately write the pipelined requests. // Some of these will not have a socket to destroy! client.write(generator(seeds)); })); var class_j_b_toolkit_1_1_win_forms_1_1_abstract_control_description_provider = [ [ "AbstractControlDescriptionProvider", "db/d7d/class_j_b_toolkit_1_1_win_forms_1_1_abstract_control_description_provider.html#a8a5bfd84a3f47d729d320bbd1cdf988a", null ], [ "CreateInstance", "db/d7d/class_j_b_toolkit_1_1_win_forms_1_1_abstract_control_description_provider.html#a4db51d2ec2eaced5590c150a96a26a07", null ], [ "GetReflectionType", "db/d7d/class_j_b_toolkit_1_1_win_forms_1_1_abstract_control_description_provider.html#a7f0ce1b9b063d8c43f09b6354fe18ea7", null ] ];function solve() { let input = JSON.parse(document.getElementById('arr').value) let specialKey = input[0]; let patternSpecialKey = /(^|\s)([A-Za-z]+)/g; if(!patternSpecialKey.test(specialKey)) { return; } let pattern = new RegExp(`${specialKey}[\\s]+([!#$%A-Z]{8,10000})([\\.\\,\\s]|$)`, "gmi"); let patternMessage = /[^A-Z#$%!]/; let result = document.getElementById('result'); for(let i = 1; i < input.length; i++) { let m; let line = input[i]; let decodedMessage = ''; while((m = pattern.exec(input[i])) !== null) { let encodedMessage = m[1]; if(!patternMessage.test(encodedMessage)) { decodedMessage = decodeMessage(encodedMessage); line = line.replace(encodedMessage, decodedMessage); } } let paragraph = document.createElement('p'); paragraph.textContent = line; result.appendChild(paragraph); } function decodeMessage(message) { let messageArray = message.split(''); for(let i = 0; i < messageArray.length; i++) { if(messageArray[i] === '!') { messageArray[i] = '1' } else if (messageArray[i] === '%') { messageArray[i] = '2' } else if (messageArray[i] === '#') { messageArray[i] = '3' } else if (messageArray[i] === '$') { messageArray[i] = '4' } } message = messageArray.join('').toLowerCase(); return message; } } import Firebase from 'firebase/app'; import 'firebase/auth'; import 'firebase/firestore'; const clientCredentials = { apiKey: process.env.NEXT_PUBLIC_FIREBASE_PUBLIC_API_KEY, authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID, } // if a Firebase instance doesn't exist, create one if (!Firebase.apps.length) { Firebase.initializeApp(clientCredentials) } export default Firebase; <filename>app/components/getting_started/steps/plugin.js import { error } from 'loglevel' import * as _ from 'lodash' import { installChromeExtension } from '../../../common/browser/chrome' import { installFirefoxExtension } from '../../../common/browser/firefox' export default class GettingStartedBrowserPluginCtrl { constructor($uibModal, $document, $scope, browserStats) { this.modal = $uibModal this.document = $document this.browserStats = browserStats this.stepNumber = 2 this.allowSkip = true this.continue = false this.state = 'none' this.stateMessage = '' this.apply = _.bind($scope.$apply, $scope) } promptInstall(browser) { this.modal.open({ controller: PluginInstallPromptCtrl, controllerAs: '$$', templateUrl: 'promptTemplate', backdrop: false, appendTo: this.document.find('#p-getting-started').eq(0), resolve: { browser: () => browser } }).result.then(result => { if (result == 'yes') { this.install() } }) } install() { if (this.browserStats.browser == this.browserStats.CHROME) { this.installChrome() } else if (this.browserStats.browser == this.browserStats.FIREFOX) { this.installFirefox() } else { this.stateMessage = 'Could not detect selected browser' this.state = 'error' } } installChrome() { const self = this self.state = 'loading' self.stateMessage = 'Installing Chrome Extension...' installChromeExtension() .then(() => { self.state = 'success' self.stateMessage = 'Extension successfully installed, please restart Chrome.' self.continue = true self.apply() }).catch((err) => { self.state = 'error' self.stateMessage = err self.apply() error(err) }) } installFirefox() { const self = this self.state = 'loading' self.stateMessage = 'Downloading plugin...' let install = installFirefoxExtension() install.on('downloadComplete', () => { self.stateMessage = 'Opening Firefox...' self.apply() }) install.on('firefoxOpened', () => { self.state = 'success' self.stateMessage = 'Please continue installation in Firefox' self.continue = true self.apply() }) install.on('error', err => { self.state = 'error' self.stateMessage = err self.apply() error(err) }) } } class PluginInstallPromptCtrl { constructor($uibModalInstance, browser) { this.modal = $uibModalInstance this.browser = browser } install() { this.modal.close('yes') } }<filename>src/components/BookCardLists/BookCardList.js import React from 'react'; import { Grid } from 'material-ui'; import PropTypes from 'prop-types'; import BookCard from '../BookCard/BookCard'; const BookCardList = props => { const { books } = props; return ( <Grid container spacing={8}> {books.map((book, key) => { return ( <Grid item md={3} sm={6} xs={12} key={key}> <BookCard updateShelf={props.updateShelf} {...book} /> </Grid> ); })} </Grid> ); }; BookCard.propTypes = { books: PropTypes.array, }; export default BookCardList; import React, { Component } from 'react'; import { Modal, Form, Input, Row, Col, Upload, Button, Icon, Divider } from 'antd'; import { baseUrl } from '@/utils/config'; const FormItem = Form.Item; class EditorModal extends Component { constructor(props) { super(props); this.state = { visible: false, businessPic: [], medicalPic: [], defaultBusiness: [], defaultMedical: [], }; } getPicUrl = arr => { const newArr = []; arr.map((item, i) => newArr.push({ uid: `-${i}`, status: 'done', url: item, }) ); return newArr; }; getPath = arr => { const newArr = []; if (arr.length > 0) { arr.map(item => newArr.push({ ...item, url: `${baseUrl}${item.url}`, }) ); return newArr; } else { return []; } }; showModelHandler = e => { const { record: { licensePhotoPath, yiliaoPhotoPath }, } = this.props; if (e) e.stopPropagation(); this.setState({ visible: true, defaultBusiness: licensePhotoPath && licensePhotoPath !== '' ? this.getPicUrl(licensePhotoPath.split(',')) : [], defaultMedical: yiliaoPhotoPath && yiliaoPhotoPath !== '' ? this.getPicUrl(yiliaoPhotoPath.split(',')) : [], }); }; hideModelHandler = () => { const { form } = this.props; form.resetFields(); this.setState({ visible: false, }); }; okHandler = () => { const { onOk, form, record: { suppilerId }, } = this.props; const { businessPic, medicalPic, defaultMedical, defaultBusiness } = this.state; const getString = arr => { const newArr = []; arr.map(item => newArr.push(item.url)); return newArr.join(','); }; form.validateFields((err, values) => { const res = { ...values, suppilerId, licensePhotoPath: getString(defaultBusiness) || '', yiliaoPhotoPath: getString(defaultMedical) || '', }; if (!err) { const formData = new FormData(); Object.keys(res).map(key => formData.append(key, res[key])); businessPic.forEach(file => { formData.append('licensePhoto', file); }); medicalPic.forEach(file => { formData.append('yiliaoPhoto', file); }); onOk(formData); this.hideModelHandler(); form.resetFields(); this.setState({ defaultBusiness: [], defaultMedical: [], }); } }); }; render() { const { children, form, record, title = '' } = this.props; const { visible, businessPic, medicalPic, defaultBusiness, defaultMedical } = this.state; const { getFieldDecorator } = form; const { suppilerName = '', suppilerShortName = '', suppilerLicense = '', conractsName = '', conractsPhone = '', conractsEmail = '', conractsAddress = '', } = record; const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 }, }; const businessProps = { onRemove: file => { this.setState(state => { const index = state.businessPic.indexOf(file); const newFileList = state.businessPic.slice(); const res = defaultBusiness.filter(item => item.uid !== file.uid); newFileList.splice(index, 1); return { businessPic: newFileList, defaultBusiness: res, }; }); }, beforeUpload: file => { this.setState(state => ({ businessPic: [...state.businessPic, file], })); return false; }, businessPic, defaultFileList: [...this.getPath(defaultBusiness)], listType: 'picture', }; const medicalProps = { onRemove: file => { this.setState(state => { const index = state.medicalPic.indexOf(file); const newFileList = state.medicalPic.slice(); const res = defaultMedical.filter(item => item.uid !== file.uid); newFileList.splice(index, 1); return { medicalPic: newFileList, defaultMedical: res, }; }); }, beforeUpload: file => { this.setState(state => ({ medicalPic: [...state.medicalPic, file], })); return false; }, medicalPic, defaultFileList: [...this.getPath(defaultMedical)], listType: 'picture', }; return ( <span> <span onClick={this.showModelHandler}>{children}</span> <Modal width={800} title={title} visible={visible} onOk={this.okHandler} onCancel={this.hideModelHandler} > <Row justify="space-around"> <Col span={12} offset={2}> <Form horizontal onSubmit={this.okHandler}> <FormItem {...formItemLayout} label="所在机构全称" hasFeedback> {getFieldDecorator('suppilerName', { initialValue: suppilerName, rules: [{ required: true, message: '请输入所在机构' }], })(<Input />)} </FormItem> <FormItem {...formItemLayout} label="公司简称" hasFeedback> {getFieldDecorator('suppilerShortName', { initialValue: suppilerShortName, rules: [{ required: true, message: '请输入公司简称' }], })(<Input />)} </FormItem> <FormItem {...formItemLayout} label="许可证号" hasFeedback> {getFieldDecorator('suppilerLicense', { initialValue: suppilerLicense, rules: [{ required: true, message: '请输入许可证号' }], })(<Input />)} </FormItem> <FormItem {...formItemLayout} label="联系人" hasFeedback> {getFieldDecorator('conractsName', { initialValue: conractsName, rules: [{ required: true, message: '请输入联系人' }], })(<Input />)} </FormItem> <FormItem {...formItemLayout} label="联系人手机号" hasFeedback> {getFieldDecorator('conractsPhone', { initialValue: conractsPhone, rules: [{ required: true, message: '请输入联系人手机号' }], })(<Input />)} </FormItem> <FormItem {...formItemLayout} label="联系邮箱" hasFeedback> {getFieldDecorator('conractsEmail', { initialValue: conractsEmail, rules: [{ required: false, message: '请输入联系人邮箱' }], })(<Input />)} </FormItem> <FormItem {...formItemLayout} label="联系地址" hasFeedback> {getFieldDecorator('conractsAddress', { initialValue: conractsAddress, rules: [{ required: false, message: '请输入联系人手机号' }], })(<Input />)} </FormItem> </Form> </Col> <Col span={8}> <div> <Divider orientation="left">营业执照(上传照片)</Divider> <Upload {...businessProps}> <Button> <Icon type="upload" /> 上传 </Button> </Upload> </div> <div> <Divider orientation="left">医疗器械经营许可证</Divider> <Upload {...medicalProps}> <Button> <Icon type="upload" /> 上传 </Button> </Upload> </div> </Col> </Row> </Modal> </span> ); } } export default Form.create()(EditorModal); <reponame>KhanMRiaz/Albums import React from 'react' import { SafeAreaView, View, Text, StatusBar, TouchableOpacity, FlatList, Dimensions } from 'react-native' import styles from './Albums.style' import Icon from 'react-native-vector-icons/Ionicons' import { connect, useDispatch } from 'react-redux' import { fetchDataAlbum } from '../../stores/actions/albums.action' const screenHeight = Dimensions.get('window').height const Albums = ({ navigation, album, route }) => { const { userId } = route.params const dispatch = useDispatch() console.log('albums: ', album) function ListAlbum() { return ( <FlatList style={{ flex: 1, marginBottom: 0.1 * screenHeight }} data={album} renderItem={({ item }) => ( <TouchableOpacity onPress={() => navigation.navigate('Photos', { albumId: item.id })} style={styles.albumsRowContainer}> <View style={{ paddingHorizontal: '3%' }}> <Text style={[styles.text, { fontSize: 0.018 * screenHeight }]}> {item.id}. {item.title} </Text> </View> </TouchableOpacity> )} /> ) } return ( <> <StatusBar barStyle="dark-content" backgroundColor={'#f9f9f9'} /> <SafeAreaView style={styles.SafeAreaView2}> <View style={styles.outerWrapper}> <View style={{ alignItems: 'center', justifyContent: 'center', width: '100%', height: '20%' }}> <Icon name={'ios-albums'} size={100} color={'purple'} /> </View> <View> <TouchableOpacity style={styles.buttonStyle} onPress={() => dispatch(fetchDataAlbum(userId))}> <Text style={[styles.text, { fontSize: 0.022 * screenHeight }]}> Click here to show Album Titles: </Text> </TouchableOpacity> <ListAlbum /> </View> </View> <View style={{ marginBottom: 0.1 * screenHeight }} /> </SafeAreaView> </> ) } const mapStateToProps = state => { return { album: state.albumReducer.albums } } export default connect(mapStateToProps, null)(Albums) <reponame>tklebanoff/ComputeLibrary<gh_stars>10-100 var classarm__compute_1_1_g_c_g_e_m_m_interleave4x4 = [ [ "configure", "classarm__compute_1_1_g_c_g_e_m_m_interleave4x4.xhtml#aa029e9740bc43eb3301316be76be3b7e", null ] ];<gh_stars>0 /* * AuthPage * * This page groups all Auth forms like login, register, forgotPass, resetPass,... * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { compose } from 'redux'; import { FormattedMessage } from 'react-intl'; import { withStyles } from '@material-ui/core/styles'; import Form from 'components/Form'; import Typography from '@material-ui/core/Typography'; import MyLink from 'components/Link'; import { authUserStart } from 'containers/App/actions'; import messages from './messages'; import forms from './forms'; const styles = theme => ({ form: { display: 'grid', marginLeft: 'auto', marginRight: 'auto', marginTop: theme.spacing.unit * 2, marginBottom: theme.spacing.unit * 3, }, subtext: { textAlign: 'center', marginTop: theme.spacing.unit * 1, marginBottom: theme.spacing.unit * 5, }, }); class AuthPage extends React.PureComponent { constructor(props) { super(props); this.state = { authId: '', submitting: false, error: false, inputs: null, }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } getAuthType(location) { let loc; if (!location) { loc = this.props.location.pathname; } else { loc = location; } return loc.substr(loc.lastIndexOf('/') + 1); } componentWillMount() { const authId = this.getAuthType(null); const inputs = forms[authId]; this.setState({ inputs, authId, }); } componentWillReceiveProps(nextProps) { const authId = this.getAuthType(nextProps.location.pathname); const inputs = forms[authId]; this.setState({ inputs, authId, }); } handleChange(event) { this.handleChangeValue(event.target.name, event.target.value); } /** * * @param id * @param value */ handleChangeValue(id, value) { const { inputs } = this.state; // eslint-disable-next-line const validator = inputs[id].error.validator; let error = false; if (!validator(value)) { error = true; } // // CUSTOM VALIDATION // if (id.endsWith('password')) { // eslint-disable-next-line const secondPassword = inputs['_password']; if (secondPassword) { // eslint-disable-next-line if (id === '_password' && value !== inputs['password'].value) { error = true; } else if (id === 'password' && value !== secondPassword.value) { secondPassword.error.isErrored = true; } else { secondPassword.error.isErrored = false; } } } // // CUSTOM VALIDATION // this.setState({ ...this.state, inputs: { ...this.state.inputs, [id]: { ...this.state.inputs[id], value, error: { ...this.state.inputs[id].error, isErrored: error, }, }, }, }); } handleSubmit() { let error = false; const dataToSend = {}; Object.keys(this.state.inputs).every(key => { const input = this.state.inputs[key]; if (input.error.isErrored) { error = true; } dataToSend[key] = input.value; return !error; // continue while no error found }); this.setState({ error, }); if (!error) { this.setState({ submitting: true }); this.props.authUserStart({ authId: this.state.authId, data: dataToSend, }); if (this.state.authId !== 'register') { this.reset(); } } } reset() { const newInputs = {}; Object.keys(this.state.inputs).forEach(key => { const input = this.state.inputs[key]; input.value = ''; newInputs[key] = input; }); this.setState({ submitting: false, inputs: newInputs, }); } render() { const { inputs, authId } = this.state; const { classes, theme } = this.props; if (!authId) return null; return ( <div> <Form id={authId} inputs={inputs} messages={messages} classes={classes} onChange={this.handleChange} onSubmit={this.handleSubmit} /> {authId !== 'register' && ( <div className={classes.subtext}> <Typography variant="subheading" color="secondary"> <FormattedMessage {...messages.register_message} values={{ registerLink: ( <MyLink theme={theme} to="/auth/register"> <FormattedMessage {...messages.register} /> </MyLink> ), }} /> </Typography> </div> )} {authId !== 'login' && ( <div className={classes.subtext}> <Typography variant="subheading" color="secondary"> <FormattedMessage {...messages.login_message} values={{ loginLink: ( <MyLink theme={theme} to="/auth/login"> <FormattedMessage {...messages.login} /> </MyLink> ), }} /> </Typography> </div> )} </div> ); } } AuthPage.propTypes = { classes: PropTypes.object.isRequired, theme: PropTypes.object.isRequired, location: PropTypes.object.isRequired, // comes from Route element in parent authUserStart: PropTypes.func.isRequired, }; const mapDispatchToProps = dispatch => ({ authUserStart: data => dispatch(authUserStart(data)), }); const withConnect = connect( null, mapDispatchToProps, ); const themeConnected = withStyles(styles, { withTheme: true }); export default compose( themeConnected, withConnect, )(AuthPage); <gh_stars>0 /* eslint-disable no-await-in-loop */ import delay from 'delay'; import log from 'electron-log'; import AntiCaptcha from "anticaptcha"; import getValidationLink from '../../../../emails/imap'; import antiCaptchaKey from "../../../../../database/antiCaptcha"; const waitRandom = () => Math.floor(Math.random() * 501) const prefectures = [ {val:"1", prefecture:"北海道"}, {val:"2", prefecture:"青森県"}, {val:"3", prefecture:"岩手県"}, {val:"4", prefecture:"宮城県"}, {val:"5", prefecture:"秋田県"}, {val:"6", prefecture:"山形県"}, {val:"7", prefecture:"福島県"}, {val:"8", prefecture:"茨城県"}, {val:"9", prefecture:"栃木県"}, {val:"10", prefecture:"群馬県"}, {val:"11", prefecture:"埼玉県"}, {val:"12", prefecture:"千葉県"}, {val:"13", prefecture:"東京都"}, {val:"14", prefecture:"神奈川県"}, {val:"15", prefecture:"新潟県"}, {val:"16", prefecture:"富山県"}, {val:"17", prefecture:"石川県"}, {val:"18", prefecture:"福井県"}, {val:"19", prefecture:"山梨県"}, {val:"20", prefecture:"長野県"}, {val:"21", prefecture:"岐阜県"}, {val:"22", prefecture:"静岡県"}, {val:"23", prefecture:"愛知県"}, {val:"24", prefecture:"三重県"}, {val:"25", prefecture:"滋賀県"}, {val:"26", prefecture:"京都府"}, {val:"27", prefecture:"大阪府"}, {val:"28", prefecture:"兵庫県"}, {val:"29", prefecture:"奈良県"}, {val:"30", prefecture:"和歌山県"}, {val:"31", prefecture:"鳥取県"}, {val:"32", prefecture:"島根県"}, {val:"33", prefecture:"岡山県"}, {val:"34", prefecture:"広島県"}, {val:"35", prefecture:"山口県"}, {val:"36", prefecture:"徳島県"}, {val:"37", prefecture:"香川県"}, {val:"38", prefecture:"愛媛県"}, {val:"39", prefecture:"高知県"}, {val:"40", prefecture:"福岡県"}, {val:"41", prefecture:"佐賀県"}, {val:"42", prefecture:"長崎県"}, {val:"43", prefecture:"熊本県"}, {val:"44", prefecture:"大分県"}, {val:"45", prefecture:"宮崎県"}, {val:"46", prefecture:"鹿児島県"}, {val:"47", prefecture:"沖縄県"} ]; const signup = async (blogInfo, opts) => { const { browser } = opts; let scriptDir = './app'; log.info(`appPath:${process.env.NODE_APPPATH}`); if (process.env.NODE_ENV === 'production') { scriptDir = process.env.NODE_APPPATH; scriptDir = scriptDir.replace('app.asar', 'app.asar.unpacked'); } const notyJsPath = `${scriptDir}/node_modules/noty/lib/noty.min.js`; const notyCssPath = `${scriptDir}/node_modules/noty/lib/noty.css`; const notyThemePath = `${scriptDir}/node_modules/noty/lib/themes/mint.css`; const swa2Js = `${scriptDir}/node_modules/sweetalert2/dist/sweetalert2.all.min.js`; const swa2Css = `${scriptDir}/node_modules/sweetalert2/dist/sweetalert2.min.css`; log.info('--------->create yaplog blog account--------->'); log.info('-----------user----------'); log.info(blogInfo); log.info('-------------------------'); const page = await browser.newPage(); await page.setViewport({ width: 1024, height: 748 }); log.info('create: browser page'); try { // Yaplog login/signup page await page.goto(`https://www.yaplog.jp/`, { waitUntil: 'load' }); log.info('access: https://www.yaplog.jp/'); await delay(waitRandom()); await page.addScriptTag({ path: notyJsPath }); await page.addStyleTag({ path: notyCssPath }); await page.addStyleTag({ path: notyThemePath }); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'Yaplogトップページアクセス完了' }).show(); `); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'[新規登録]ボタンをクリック' }).show(); `); log.info('click [新規登録]ボタンクリック'); await page.click('#new'); await page.waitForSelector('input[name="email"]'); // mailAddress input & captcha await delay(waitRandom()); await page.addScriptTag({ path: notyJsPath }); await page.addStyleTag({ path: notyCssPath }); await page.addStyleTag({ path: notyThemePath }); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'メールアドレス入力開始' }).show(); `); await page.click('input[name="email"]'); await page.type('input[name="email"]', blogInfo.mailAddress, {delay: waitRandom()}); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'メールアドレス入力完了' }).show(); `); log.info(`mailAddress:${blogInfo.mailAddress}入力完了`); await delay(waitRandom()); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'[確認メールを送信]ボタンをクリック' }).show(); `); await page.click('input[name="btn_login"]'); log.info('click: 確認メール送信') await page.waitFor('h1.step01'); await page.addScriptTag({ path: notyJsPath }); await page.addStyleTag({ path: notyCssPath }); await page.addStyleTag({ path: notyThemePath }); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'仮登録完了' }).show(); `); log.info('Yaplog仮登録完了'); await delay(1000); await page.goto('https://tools.yoriki.cloud/countdown/'); log.info('メール到着60秒待機'); await page.waitForSelector('#blind', { timeout: 70000 }); // メールアカウントへのログイン情報 const mailacc = {}; mailacc.accountId = blogInfo.mailAccount.accountId; mailacc.mailAddress = blogInfo.mailAddress; mailacc.password = <PASSWORD>; mailacc.provider = blogInfo.mailAccount.provider; mailacc.blogProvider = blogInfo.provider; log.info('本登録URLを取得'); // メールアカウントへログインし、本登録URLを取得 let validationUrl = ''; try { const result = await getValidationLink(mailacc); if (result) { log.info(`本登録URL:${result[0]}`); // 本登録URLへアクセス プロフィールの入力ページ [validationUrl] = result; } else { throw new Error('registration link not found') } } catch (error) { log.warn(error.toString()); await page.goto('https://tools.yoriki.cloud/enter_url/index.html', { waitUntil: 'load' }); const { value: url } = await page.evaluate(` Swal.fire({ title: '本登録用リンクURLを貼付け', html: '<p>使用したメールアドレスにログインしてください。<span style="color: red;font-weight: bold;">本登録URLをコピー</span>して、以下のボックスへ貼りつけます。<b>OK</b>をクリックすると自動作成を続けます。</p><p><span style="color: red;font-weight: bold;">未入力でOK</span>をクリックすると<span style="color: red;font-weight: bold;">中止します。</span></p>', input: 'text', inputPlaceholder: '本登録URLを貼付け' })`); if (url) { console.log(`url: ${url}`); validationUrl = url; log.info(`set url: ${validationUrl}`); } else { await page.evaluate(` Swal.fire({ title: '中止しました。', html: '<p>ブログの作成を中止しました。</p><p>ブログ一覧に登録されているデータを削除してください。</p>', })`); log.info('quit:'); return; } } await page.goto(validationUrl); await page.waitForSelector('input[name="basePassword"]'); log.info('本登録URLへアクセス完了'); await delay(waitRandom()); await page.addScriptTag({ path: notyJsPath }); await page.addStyleTag({ path: notyCssPath }); await page.addStyleTag({ path: notyThemePath }); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'本登録URLへアクセス完了' }).show(); `); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'パスワード入力開始' }).show(); `); await delay(waitRandom()); await page.click('input[name="basePassword"]'); await delay(waitRandom()); await page.type('input[name="basePassword"]', blogInfo.password, {delay: waitRandom()}); log.info(`input password:${blogInfo.password}`); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'パスワード入力完了' }).show(); `); await delay(waitRandom()); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'パスワード(確認)入力開始' }).show(); `); await delay(waitRandom()); await page.click('input[name="basePasswordConfirm"]'); await delay(waitRandom()); await page.type('input[name="basePasswordConfirm"]', blogInfo.password, {delay: waitRandom()}); log.info(`input password confirm`); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'パスワード(確認)入力完了' }).show(); `); // yaplogID await delay(waitRandom()); await page.evaluate(` new Noty({ killer: true, type: 'success', layout: 'topLeft', text:'ヤプログ!ID入力開始' }).show(); `); await page.click('input[name="memberId"]'); await delay(waitRandom()); await page.type('input[name="memberId"]', blogInfo.accountId, {delay: waitRandom()}); log.info(`input: blogID:${blogInfo.accountId}`); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'ヤプログ!ID入力完了' }).show(); `); // title await delay(waitRandom()); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'ブログタイトル入力開始' }).show(); `); await page.click('input[name="blogName"]'); await delay(waitRandom()); await page.type('input[name="blogName"]', blogInfo.title, {delay: waitRandom()}); log.info(`input blog title:${blogInfo.title}`); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'ブログタイトル入力完了' }).show(); `); await delay(waitRandom() + 540); await page.evaluate(` new Noty({ killer: true, type: 'success', layout: 'topLeft', text:'性別選択開始' }).show(); `); if (blogInfo.gender === 0) { await page.click('#sexMLabel'); log.info('select gender male'); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'[男性]選択完了' }).show(); `); } else { await page.click('#sexFLabel'); log.info('select gender female'); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'[女性]選択完了' }).show(); `); } // birth date await delay(waitRandom()); const birthDateParts = blogInfo.birthDate.split('/'); await page.evaluate(` new Noty({ killer: true, type: 'success', layout: 'topLeft', text:'生年月日-[年]-選択開始' }).show(); `); await page.click(`select[name="birthYear"]`); await delay(waitRandom()); await page.select(`select[name="birthYear"]`, birthDateParts[0]); log.info(`input birth year:${birthDateParts[0]}`); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'生年月日-[年]-選択完了' }).show(); `); await delay(waitRandom()); await page.evaluate(` new Noty({ killer: true, type: 'success', layout: 'topLeft', text:'生年月日-[月]-選択開始' }).show(); `); await page.click(`select[name="birthMonth"]`); await delay(waitRandom()); await page.select(`select[name="birthMonth"]`, birthDateParts[1]); log.info(`input birth month:${birthDateParts[1]}`); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'生年月日-[月]-選択完了' }).show(); `); await delay(waitRandom()); await page.evaluate(` new Noty({ killer: true, type: 'success', layout: 'topLeft', text:'生年月日-[日]-選択開始' }).show(); `); await page.click(`select[name="birthDay"]`); await delay(waitRandom()); await page.select(`select[name="birthDay"]`, birthDateParts[2]); log.info(`input birth date:${birthDateParts[2]}`); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'生年月日-[日]-選択完了' }).show(); `); await delay(waitRandom()); // prefecture const prefecture = prefectures.find(p => p.prefecture === blogInfo.prefecture); await page.evaluate(` new Noty({ killer: true, type: 'success', layout: 'topLeft', text:'都道府県選択開始' }).show(); `); await page.click(`select[name="prefecture_code"]`); await delay(waitRandom()); await page.select(`select[name="prefecture_code"]`, prefecture.val); log.info(`input prefecture:${prefecture.val}-${prefecture.prefecture}`); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'都道府県選択完了' }).show(); `); await delay(waitRandom()); await page.evaluate(` new Noty({ type: 'success', layout: 'topLeft', text:'[規約に同意して進む]ボタンクリック' }).show(); `); await page.click('input[src^="/img/common/spacer.gif"]'); log.info('click:登録ボタン'); await page.waitFor('h1.step02'); // Yaplog登録完了ページ await delay(waitRandom()+620); log.info('access Yaplog登録完了ページ') await page.addScriptTag({ path: notyJsPath }); await page.addStyleTag({ path: notyCssPath }); await page.addStyleTag({ path: notyThemePath }); // captcha try { await page.evaluate(` new Noty({ killer: true, type: 'warning', layout: 'topLeft', text:'「私は、ロボットではありません。」を解決中...' }).show(); `); const AntiCaptchaAPI = new AntiCaptcha(antiCaptchaKey); console.log('start anti captcha'); const pageUrl = await page.url(); console.log(`page url:${pageUrl}`); let counter = 0; let precheck ; do { await delay(500); counter += 1; console.log(`counter:${counter}`); precheck = await page.$('.g-recaptcha'); } while (precheck === null || counter < 4); const siteKey = await page.$eval('.g-recaptcha', (el, attribute) => el.getAttribute(attribute), 'data-sitekey'); log.info('google reCaptcha found'); console.log(`pageUrl:${pageUrl}`); console.log(`siteKay:${siteKey}`); if (!pageUrl || !siteKey) { throw new Error('can not get page url or siteKey'); } log.info('start to resolve google reCaptcha'); const taskId = await AntiCaptchaAPI.createTask(pageUrl, siteKey); const response = await AntiCaptchaAPI.getTaskResult(taskId); log.info('done resolver'); console.log(response); await page.evaluate('Noty.closeAll()'); if ('errorId' in response) { if (response.errorId === 0) { // set resolver to textarea const frame = await page.frames().find(f => f.url().indexOf('https://www.google.com/recaptcha/api2/')); if (!frame) { log.warn('google reCaptcha frame has not found.') throw new Error('google reCaptcha frame has not found.') } log.info('found response frame.'); log.info(`response:${response.solution.gRecaptchaResponse}`); // #g-recaptcha-response await frame.$eval('#g-recaptcha-response', (el, value) => (el.value = value), response.solution.gRecaptchaResponse); } } else { log.warn('antiCaptcha has no result.') throw new Error('antiCaptcha has no result.'); } // input image src='/img/common/spacer.gif' const selector = 'input[src^="/img/common/spacer.gif"]'; await page.evaluate((selector) => document.querySelector(selector).click(), selector); log.info('click [上記の内容で登録]') } catch (error) { await page.addStyleTag({ path: swa2Css }); await page.addScriptTag({ path: swa2Js }); await page.evaluate(`Swal.fire({ title: '手順', text: '「私は、ロボットではありません。」にチェックを入れて、[上記の内容で登録]ボタンをクリックしてください。5分(300秒)を超えるとエラーになります。', showCancelButton: false, confirmButtonColor: '#4caf50', cancelButtonColor: '#f44336', confirmButtonText: '閉じる', cancelButtonText: 'ブラウザは、このまま', reverseButtons: true })`); } await page.waitFor('h1.step03', {timeout: 300000}); log.info('ブログ登録完了'); await page.addStyleTag({ path: swa2Css }); await page.addScriptTag({ path: swa2Js }); const closeConfirm = await page.evaluate(`Swal.fire({ title: 'Yaplog作成が完了しました。', text: 'ブラウザを閉じてもよろしいですか?', showCancelButton: true, confirmButtonColor: '#4caf50', cancelButtonColor: '#f44336', confirmButtonText: '閉じる', cancelButtonText: 'ブラウザは、このまま', reverseButtons: true })`); if (closeConfirm.value) { await page.close(); } } catch (error) { log.error(`error:${error.toString()}`); await page.addStyleTag({ path: swa2Css }); await page.addScriptTag({ path: swa2Js }); await page.evaluate(`Swal.fire({ title: 'エラー発生', text: 'エラーが発生しました。お手数ですが、手作業で続けていただくか、登録済みのアカウントを削除してください。', showCancelButton: false, confirmButtonColor: '#4caf50', cancelButtonColor: '#f44336', confirmButtonText: '閉じる', cancelButtonText: 'ブラウザは、このまま', reverseButtons: true })`); } }; export default signup; const mongoose = require('mongoose'); // connexion à la base de donnée require('../bdd/database')(); //Définir un type "objectId" const ObjectId = mongoose.Types.ObjectId; const schemaOptions = { timestamps: { // ajout de la date et l'heure à la création et modification createdAt: "created_at", updatedAt: "edited_at" } , versionKey: false }; // Schéma de données propres aux sous programmes const userSchema = mongoose.Schema({ email: { type: String, required: true } , password: { type: String, required: true } , avatar: { type: String } , programsList: { type: Array } , uuid: { type: String, required: true } // permet d'avoir un ID pour récupérer le user dans le passport }, schemaOptions); module.exports = class User { constructor() { this.db = mongoose.model('users', userSchema); } findUser(obj) { return new Promise((resolve, reject) => { this.db.findOne(obj, (err, doc) => { if (err) reject(err); resolve(doc); }); }); } add(user) { return new Promise((resolve, reject) => { this.db.create(user, (err, doc) => { if (err) reject(err); resolve(doc); }) }) } // docs : https://devdocs.io/mongoose/api/model#model_Model.findOneAndUpdate findAndUpdate(objToFind, objToUpdate) { return new Promise((resolve, reject) => { this.db.findOneAndUpdate( objToFind , objToUpdate , { new: true, useFindAndModify: false }) .then((err, doc) => { if (err) reject(err); resolve(doc); }) }) } }<gh_stars>1000+ import React from 'react'; import {View, Text, StyleSheet} from "react-native"; import Button from "react-native-button"; import {Actions} from "react-native-router-flux"; export default class extends React.Component { render(){ return ( <View style={[styles.container, this.props.sceneStyle]}> <Text style={styles.instructions}>routeName: {this.props.name}</Text> <Button onPress={Actions.pop}>pop</Button> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#F5FCFF", borderWidth: 2, borderColor: 'red', }, instructions: { textAlign: "center", color: "#333333", marginBottom: 5, }, smaller: { marginBottom: 5, fontSize: 12, }, }) const path = require("path"); const webpack = require("webpack"); const HTMLWebpackPlugin = require("html-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); const TerserWebpackPlugin = require("terser-webpack-plugin"); const ESLintPlugin = require("eslint-webpack-plugin"); const isDev = process.env.NODE_ENV === "development"; const isProd = !isDev; const optimization = () => { const config = { splitChunks: { chunks: "all", }, }; if (isProd) { config.minimize = true; config.minimizer = [new CssMinimizerPlugin(), new TerserWebpackPlugin()]; } return config; }; const filename = (ext) => isDev ? `[name].${ext}` : `[name].[fullhash].${ext}`; const cssLoaders = (extra) => { const loaders = [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: (resourcePath, context) => { return path.relative(path.dirname(resourcePath), context) + "/"; }, }, }, "css-loader", { loader: "postcss-loader", options: { postcssOptions: { plugins: [ [ "postcss-preset-env", { browsers: "last 3 versions", autoprefixer: { grid: true }, }, ], [ "postcss-sort-media-queries", { sort: "mobile-first", // default }, ], ], }, }, }, ]; if (extra) { loaders.push(extra); } return loaders; }; const babelOptions = (preset) => { const opts = { presets: [["@babel/preset-env", { useBuiltIns: "usage", corejs: 3 }]], plugins: ["@babel/plugin-proposal-class-properties"], }; if (preset) { opts.presets.push(preset); } return opts; }; const plugins = () => { const base = [ new HTMLWebpackPlugin({ template: "./index.html", minify: { collapseWhitespace: isProd, }, }), new CleanWebpackPlugin(), new CopyWebpackPlugin({ patterns: [ { from: path.resolve(__dirname, "src/favicon.ico"), to: path.resolve(__dirname, "dist"), }, ], }), new MiniCssExtractPlugin({ filename: `css/${filename("css")}`, }), ]; if (isDev) { base.push(new ESLintPlugin()); base.push(new webpack.HotModuleReplacementPlugin()); } return base; }; module.exports = { context: path.resolve(__dirname, "src"), mode: "development", entry: { main: ["@/index.js"], }, output: { filename: `js/${filename("js")}`, path: path.resolve(__dirname, "dist"), }, resolve: { extensions: [".js", ".json", ".html"], alias: { "@": path.resolve(__dirname, "src"), }, }, optimization: optimization(), devServer: { historyApiFallback: true, contentBase: path.resolve(__dirname, "./dist"), compress: true, port: 8100, hot: isDev, }, devtool: isDev ? "source-map" : false, plugins: plugins(), module: { rules: [ { test: /\.html$/i, loader: "html-loader", }, { test: /\.css$/, use: cssLoaders(), }, { test: /\.s[ac]ss$/, use: cssLoaders("sass-loader"), }, { test: /\.(?:ico|png|jpg|jpeg|svg|gif)$/, loader: "file-loader", options: { outputPath: "assets/images", name() { if (isDev) { return "[name].[ext]"; } return "[name].[hash].[ext]"; }, }, }, { test: /\.(ttf|woff|woff2|eot|otf)$/, loader: "file-loader", options: { outputPath: "assets/fonts", name() { if (isDev) { return "[name].[ext]"; } return "[name].[hash].[ext]"; }, }, }, { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: babelOptions(), }, }, ], }, }; let base_url = window.location.origin, imageUrl = `${base_url}/public/images`; const registeredBusinesses = [ { name: "appheart", logo: `${imageUrl}/appheart.png`, description: "Proferring creative solutions using state-of-art technologies, towards discovering happiness ❣", website: "https://appheartafrica.netlify.app", rating: 234, }, { name: "DataXpress", logo: `${imageUrl}/DataXpressLogo.png`, description: "Your top Professional Data Solution and Delivery Company with the right certified team of professionals in orienting Data solutions.", website: "https://dataxpressprofessionals.com", rating: 176, }, { name: "OGB Sports", logo: `${imageUrl}/ogbsports.png`, description: "The No. 1 sports clothing company with the goal of delivering authentic wears, sneakers and accessories to you as our only priority in our hearts.", website: "https://ogbsports.netlify.app", rating: 89, }, ]; const businessContainer = document.querySelector(".businesses"); function businessLayout(businesss) {} const populateBusinessContainer = registeredBusinesses.forEach((business) => { businessContainer.innerHTML += ` <!-- ${business.name}--> <div class="business" id="${business.name}"> <div class="business__info"> <div class="business__logo"> <img src="${business.logo}" alt="" class="logo" /> </div> <div class="business__desc"> <div class="business__about"> ${business.description} </div> <div class="business__name">${business.name}</div> </div> </div> <div class="business__rating"> <div class="stars-outer"> <div class="stars-inner"></div> </div> <div class="business__rating--count">${business.rating}</div> </div> <div class="business__connect"> <button> <a href="${business.website}" class="button" target='__blank' >Learn more</a > </button> </div> </div>`; }); module.exports = function reverse (n) { let arr = String(Math.abs(n)).split(""); arr.reverse(); return Number(arr.join("")); } import React from 'react'; import ReactDOM from 'react-dom'; import { create } from 'react-test-renderer'; import Adapter from '@wojtekmaj/enzyme-adapter-react-17'; import Enzyme from 'enzyme'; import App from '../App'; import ButtonPanel from '../ButtonPanel'; Enzyme.configure({ adapter: new Adapter() }); describe('ButtonPanel Component', () => { it('Renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<App />, div); }); it('renders correctly', () => { const app = create(<App />).toJSON(); expect(app).toMatchSnapshot(); }); it('Passes the clickHandler correctly to ButtonPanel', () => { const app = Enzyme.shallow(<App />); const instance = app.instance(); expect(app.find(ButtonPanel).get(0).props.clickHandler).toEqual(instance.handleClick); }); it('Updates the state correctly when clickHandler is invoked', () => { const app = Enzyme.shallow(<App />); const instance = app.instance(); instance.handleClick('1'); expect(app.state()).toEqual({ next: '1', operation: null, total: null }); }); it('Returns the correct value when using the `result` attribute getter', () => { const app = Enzyme.shallow(<App />); const instance = app.instance(); instance.setState({ next: '0', operation: '+', total: '15' }); expect(instance.result).toEqual('0+15'); instance.setState({ next: null, operation: null, total: null }); expect(instance.result).toEqual(''); }); }); <gh_stars>0 document.getElementsByTagName("img").onclick = function() { alert('clicou') }var searchData= [ ['main_2ecpp_0',['main.cpp',['../main_8cpp.html',1,'']]], ['mcp3428_5fsetup_1',['mcp3428_setup',['../main_8cpp.html#ac74aa5130065ed9be0357d2817911aef',1,'main.cpp']]], ['messwerte_2',['messwerte',['../structmesswerte.html',1,'']]] ]; import React, { useState, useRef, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import clsx from "clsx"; import { Box, Card, CardContent, Container, colors, Divider, Grid, Paper, Table, TableContainer, TableHead, TableRow, TableCell, TableBody, TextField, Typography, makeStyles, } from "@material-ui/core"; import { onError } from "src/libs/errorLib.js"; import Page from "src/components/Page"; import * as queries from "src/graphql/queries.js"; import { API, graphqlOperation } from "aws-amplify"; import moment from "moment"; import * as mutations from "src/graphql/mutations.js"; import LoaderButton from "src/components/LoaderButton.js"; import { UploadCloud as UploadIcon } from "react-feather"; import { Storage } from "aws-amplify"; import { green } from "@material-ui/core/colors"; const useStyles = makeStyles((theme) => ({ root: { backgroundColor: theme.palette.background.dark, minHeight: "100%", paddingBottom: theme.spacing(3), paddingTop: theme.spacing(3), }, avatar: { marginRight: theme.spacing(2), }, image: { width: 128, height: 128, }, img: { margin: "auto", display: "block", maxWidth: "100%", maxHeight: "100%", }, wrapper: { margin: "auto", position: "relative", }, buttonSuccess: { backgroundColor: green[500], "&:hover": { backgroundColor: green[700], }, }, buttonProgress: { color: green[500], position: "absolute", top: "50%", left: "50%", marginTop: -12, marginLeft: -12, }, table: { minWidth: 650, }, tableRow: { backgroundColor: colors.teal[400], }, tableRow2: { backgroundColor: colors.teal[200], }, })); const UpdateFinancialsForm = ({ className, value, ...rest }) => { const classes = useStyles(); const navigate = useNavigate(); const sub = value.userId; const [userId, setUserId] = useState(""); const [identityId, setIdentityId] = useState(""); const [financialsId, setFinancialsId] = useState(""); const [financials_attachment, setFinancials_attachment] = useState(""); const [balance_sheet_attachment, setBalance_sheet_attachment] = useState(""); const [ income_statement_attachment, setIncome_statement_attachment, ] = useState(""); const [current_assets, setCurrent_assets] = useState(""); const [cash_flow, setCash_flow] = useState(""); const [current_long_term_debt, setCurrent_long_term_debt] = useState(""); const [current_liabilities, setCurrent_liabilities] = useState(""); const [gross_margin, setGross_margin] = useState(""); const [operating_income, setOperating_income] = useState(""); const [other_expenses, setOther_expenses] = useState(""); const [ebt, setEbt] = useState(""); const [ebitda, setEbitda] = useState(""); const [current_ratio, setCurrent_ratio] = useState(""); const [debt_equity_ratio, setDebt_equity_ratio] = useState(""); const [debt_ebitda_ratio, setDebt_ebitda_ratio] = useState(""); const [inventory_turnover, setInventory_turnover] = useState(""); const [interest_coverage, setInterest_coverage] = useState(""); const [income_tax_expense, setIncome_tax_expense] = useState(""); const [ total_liabilities_and_equity, setTotal_liabilities_and_equity, ] = useState(""); const [marketable_securities, setMarketable_securities] = useState(""); const [accounts_receivable, setAccounts_receivable] = useState(""); const [inventory, setInventory] = useState(""); const [goodwill, setGoodwill] = useState(""); const [other_current_assets, setOther_current_assets] = useState(""); const [other_non_current_assets, setOther_non_current_assets] = useState(""); const [accumulated_depreciation, setAccumulated_depreciation] = useState(""); const [accured_expenses, setAccured_expenses] = useState(""); const [unearned_revenue, setUnearned_revenue] = useState(""); const [long_term_debt, setLong_term_debt] = useState(""); const [other_current_liabilities, setOther_current_liabilities] = useState( "" ); const [ other_long_term_liabilities, setOther_long_term_liabilities, ] = useState(""); const [income_tax_payable, setIncome_tax_payable] = useState(""); const [dividends_payable, setDividends_payable] = useState(""); const [total_liabilities, setTotal_liabilities] = useState(""); const [common_stock, setCommon_stock] = useState(""); const [preferred_stock, setPreferred_stock] = useState(""); const [paid_in_capital, setPaid_in_capital] = useState(""); const [retained_earnings, setRetained_earnings] = useState(""); const [total_equity, setTotal_equity] = useState(""); const [equity_book_value, setEquity_book_value] = useState(""); const [equity_market_value, setEquity_market_value] = useState(""); const [sales, setSales] = useState(""); const [cost_of_goods_sold, setCost_of_goods_sold] = useState(""); const [operating_expenses, setOperating_expenses] = useState(""); const [marketing_expenses, setMarketing_expenses] = useState(""); const [bad_debt_expenses, setBad_debt_expenses] = useState(""); const [ebit, setEbit] = useState(""); const [interest_expenses, setInterest_expenses] = useState(""); const [depreciation_expenses, setDepreciation_expenses] = useState(""); const [ sale_purchase_of_fixed_asset, setSale_purchase_of_fixed_asset, ] = useState(""); const [extraordinary_income, setExtraordinary_income] = useState(""); const [tax_expenses, setTax_expenses] = useState(""); const [net_profit, setNet_profit] = useState(""); const [financials_rating, setFinancials_rating] = useState(""); const [working_capital, setWorking_capital] = useState(""); const [ financials_reporting_period, setFinancials_reporting_period, ] = useState(""); const [total_assets, setTotal_assets] = useState(""); const [accounts_payable, setAccounts_payable] = useState(""); const [cash, setCash] = useState(""); const [short_term_debt, setShort_term_debt] = useState(""); const [financialsloading, setFinancialsLoading] = useState(false); const [financialssuccess, setFinancialsSuccess] = useState(false); const [balanceloading, setBalanceLoading] = useState(false); const [balancesuccess, setBalanceSuccess] = useState(false); const [incomeloading, setIncomeLoading] = useState(false); const [incomesuccess, setIncomeSuccess] = useState(false); const [balanceimg, setBalanceImg] = useState(""); const [balancepdf, setBalancepdf] = useState(""); const [incomeimg, setIncomeImg] = useState(""); const [incomepdf, setIncomepdf] = useState(""); const [sheet, setSheet] = useState(""); const [income, setIncome] = useState(""); const file = useRef(null); const balancelabel = "balance_sheet_attachment"; const balancename = "Balance Sheet"; const incomelabel = "income_statement_attachment"; const incomename = "Income Statement"; useEffect(() => { const sub = value.userId; const key = value.financialsId; var userId = sub; var sortkey = key; getFinancials({ userId, sortkey }); }, [value.financialsId, value.userId]); async function getFinancials(input) { try { const financials = await API.graphql( graphqlOperation(queries.getFinancials, input) ); const { data: { getFinancials: { userId, identityId, financialsId, financials_attachment, balance_sheet_attachment, income_statement_attachment, current_assets, cash_flow, current_long_term_debt, current_liabilities, gross_margin, operating_income, other_expenses, ebt, ebitda, current_ratio, debt_equity_ratio, debt_ebitda_ratio, inventory_turnover, interest_coverage, income_tax_expense, total_liabilities_and_equity, marketable_securities, accounts_receivable, inventory, goodwill, other_current_assets, other_non_current_assets, accumulated_depreciation, total_assets, short_term_debt, accounts_payable, accured_expenses, unearned_revenue, long_term_debt, other_current_liabilities, other_long_term_liabilities, income_tax_payable, dividends_payable, total_liabilities, common_stock, preferred_stock, paid_in_capital, retained_earnings, total_equity, equity_book_value, equity_market_value, sales, cost_of_goods_sold, operating_expenses, marketing_expenses, bad_debt_expenses, ebit, interest_expenses, depreciation_expenses, sale_purchase_of_fixed_asset, extraordinary_income, tax_expenses, net_profit, financials_rating, financials_reporting_period, cash, working_capital, }, }, } = financials; setUserId(userId); setIdentityId(identityId); setFinancialsId(financialsId); setFinancials_attachment(financials_attachment); setBalance_sheet_attachment(balance_sheet_attachment); setIncome_statement_attachment(income_statement_attachment); setCurrent_assets(current_assets); setCash_flow(cash_flow); setCurrent_long_term_debt(current_long_term_debt); setCurrent_liabilities(current_liabilities); setGross_margin(gross_margin); setOperating_income(operating_income); setOther_expenses(other_expenses); setEbt(ebt); setEbitda(ebitda); setCurrent_ratio(current_ratio); setDebt_equity_ratio(debt_equity_ratio); setDebt_ebitda_ratio(debt_ebitda_ratio); setInventory_turnover(inventory_turnover); setInterest_coverage(interest_coverage); setIncome_tax_expense(income_tax_expense); setTotal_liabilities_and_equity(total_liabilities_and_equity); setMarketable_securities(marketable_securities); setAccounts_receivable(accounts_receivable); setInventory(inventory); setGoodwill(goodwill); setOther_current_assets(other_current_assets); setOther_non_current_assets(other_non_current_assets); setAccumulated_depreciation(accumulated_depreciation); setTotal_assets(total_assets); setShort_term_debt(short_term_debt); setAccounts_payable(accounts_payable); setAccured_expenses(accured_expenses); setUnearned_revenue(unearned_revenue); setLong_term_debt(long_term_debt); setOther_current_liabilities(other_current_liabilities); setOther_long_term_liabilities(other_long_term_liabilities); setIncome_tax_payable(income_tax_payable); setDividends_payable(dividends_payable); setTotal_liabilities(total_liabilities); setCommon_stock(common_stock); setPreferred_stock(preferred_stock); setPaid_in_capital(paid_in_capital); setRetained_earnings(retained_earnings); setTotal_equity(total_equity); setEquity_book_value(equity_book_value); setEquity_market_value(equity_market_value); setSales(sales); setCost_of_goods_sold(cost_of_goods_sold); setOperating_expenses(operating_expenses); setMarketing_expenses(marketing_expenses); setBad_debt_expenses(bad_debt_expenses); setEbit(ebit); setInterest_expenses(interest_expenses); setDepreciation_expenses(depreciation_expenses); setSale_purchase_of_fixed_asset(sale_purchase_of_fixed_asset); setExtraordinary_income(extraordinary_income); setTax_expenses(tax_expenses); setNet_profit(net_profit); setFinancials_rating(financials_rating); setFinancials_reporting_period(financials_reporting_period); setCash(cash); setWorking_capital(working_capital); } catch (err) { console.log("error fetching data..", err); } } async function handleFinancialsSubmit() { setFinancialsSuccess(false); setFinancialsLoading(true); const ca = Number(cash) + Number(accounts_receivable) + Number(inventory) + Number(other_current_assets); const current_assets = Number(ca); const ta = current_assets + Number(sale_purchase_of_fixed_asset) + Number(goodwill) + Number(other_non_current_assets); const total_assets = Number(ta); const cl = Number(accounts_payable) + Number(current_long_term_debt) + Number(other_current_liabilities); const current_liabilities = Number(cl); const ll = Number(long_term_debt) + Number(other_long_term_liabilities); const total_liabilities = Number(ll) + Number(current_liabilities); const total_liabilities_and_equity = Number(total_equity) + Number(total_liabilities); const gm = Number(sales) - Number(cost_of_goods_sold); const gross_margin = Number(gm); const oi = Number(gross_margin) - Number(depreciation_expenses) - Number(operating_expenses); const operating_income = Number(oi); const ebt = Number(operating_income) - Number(interest_expenses) - Number(other_expenses); const ebit = Number(ebt) - Number(income_tax_expense); const net_profit = Number(ebit) - Number(extraordinary_income); const ebitda = Number(depreciation_expenses) + Number(interest_expenses) + Number(income_tax_expense) + Number(net_profit); const current_ratio = Number(current_assets) / Number(current_liabilities); const debt_equity_ratio = (Number(long_term_debt) + Number(current_long_term_debt)) / Number(total_equity); const debt_ebitda_ratio = (Number(long_term_debt) + Number(current_long_term_debt)) / Number(ebitda); try { const userId = sub; const sortkey = financialsId; await updateFinancials({ userId, sortkey, financials_attachment, balance_sheet_attachment, income_statement_attachment, current_assets, cash_flow, current_long_term_debt, current_liabilities, gross_margin, operating_income, other_expenses, ebt, ebitda, current_ratio, debt_equity_ratio, debt_ebitda_ratio, inventory_turnover, interest_coverage, income_tax_expense, total_liabilities_and_equity, marketable_securities, accounts_receivable, inventory, goodwill, other_current_assets, other_non_current_assets, accumulated_depreciation, total_assets, short_term_debt, accounts_payable, accured_expenses, unearned_revenue, long_term_debt, other_current_liabilities, other_long_term_liabilities, income_tax_payable, dividends_payable, total_liabilities, common_stock, preferred_stock, paid_in_capital, retained_earnings, total_equity, equity_book_value, equity_market_value, sales, cost_of_goods_sold, operating_expenses, marketing_expenses, bad_debt_expenses, ebit, interest_expenses, depreciation_expenses, sale_purchase_of_fixed_asset, extraordinary_income, tax_expenses, net_profit, financials_rating, financials_reporting_period, cash, working_capital, }); } catch (e) { onError(e); } setFinancialsSuccess(true); setFinancialsLoading(false); navigate("/admin/buyers"); } function updateFinancials(input) { return API.graphql( graphqlOperation(mutations.updateFinancials, { input: input }) ); } async function s3Up(file, name) { var fileExtension = file.name.split(".").pop(); const filename = `${userId}${financialsId}${name}.${fileExtension}`; const stored = await Storage.put(filename, file, { level: "private", identityId: identityId, contentType: file.type, }); return stored.key; } useEffect(() => { if (balance_sheet_attachment) { async function getbalanceimgurl() { var uploadext = balance_sheet_attachment.split(".").pop(); var imageExtensions = [ "jpg", "jpeg", "bmp", "gif", "png", "tiff", "eps", "svg", ]; const x = imageExtensions.includes(uploadext); if (x === true) { const y = await Storage.get(balance_sheet_attachment, { level: "private", identityId: identityId, }); setBalanceImg(y); } } getbalanceimgurl(); } }, [balance_sheet_attachment, identityId]); useEffect(() => { if (balance_sheet_attachment) { async function getbalancepdfurl() { var uploadext = balance_sheet_attachment.split(".").pop(); var imageExtensions = ["pdf", "PDF"]; const x = imageExtensions.includes(uploadext); if (x === true) { const y = await Storage.get(balance_sheet_attachment, { level: "private", identityId: identityId, }); setBalancepdf(y); } } getbalancepdfurl(); } }, [balance_sheet_attachment, identityId]); function balanceisimageorpdf(label, name) { var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-/]))?/; if (regex.test(balanceimg)) { return ( <> <Grid item md={12} xs={12}> <img className={classes.img} alt="complex" src={balanceimg} /> <div> <input id={balanceimg} accept="image/*,application/pdf" style={{ display: "none" }} type="file" onChange={(event) => handlebalanceChange(event)} /> <label htmlFor={balanceimg}> <LoaderButton id={balanceimg} fullWidth component="span" startIcon={<UploadIcon />} disabled={balanceloading} success={balancesuccess} loading={balanceloading} > {" "} Update File </LoaderButton> </label> </div> </Grid> </> ); } else if (regex.test(balancepdf)) { return ( <> <Grid item md={12} xs={12}> <iframe title="file" style={{ width: "100%", height: "100%" }} allowFullScreen src={balancepdf} /> <div> <input id={balancepdf} accept="image/*,application/pdf" style={{ display: "none" }} type="file" onChange={(event) => handlebalanceChange(event)} /> <label htmlFor={balancepdf}> <LoaderButton id={balancepdf} fullWidth component="span" startIcon={<UploadIcon />} disabled={balanceloading} success={balancesuccess} loading={balanceloading} > {" "} Update File </LoaderButton> </label> </div> </Grid> </> ); } else { return ( <> <Grid item md={12} xs={12}> <input name={balancename} id={balancelabel} accept="image/*,application/pdf" style={{ display: "none" }} type="file" onChange={(event) => handlebalanceChange(event)} /> <label htmlFor={balancelabel}> <LoaderButton id={balancelabel} fullWidth component="span" startIcon={<UploadIcon />} disabled={balanceloading} success={balancesuccess} loading={balanceloading} > {" "} {balancename} </LoaderButton> </label> </Grid> </> ); } } function handlebalanceChange(event) { file.current = event.target.files[0]; const newbalancefile = file.current; onbalanceChange(newbalancefile); } async function onbalanceChange(newfile) { setBalanceSuccess(false); setBalanceLoading(true); try { const u = newfile ? await s3Up(newfile, "balance_sheet_attachment") : null; var balance_sheet_attachment = u; const sortkey = financialsId; const userId = await value.userId; await updateFinancials({ sortkey, userId, balance_sheet_attachment, }); } catch (e) { onError(e); } setBalanceSuccess(true); setBalanceLoading(false); navigate("/admin/buyers"); } useEffect(() => { if (income_statement_attachment) { async function getincomeimgurl() { var uploadext = income_statement_attachment.split(".").pop(); var imageExtensions = [ "jpg", "jpeg", "bmp", "gif", "png", "tiff", "eps", "svg", ]; const x = imageExtensions.includes(uploadext); if (x === true) { const y = await Storage.get(income_statement_attachment, { level: "private", identityId: identityId, }); setIncomeImg(y); } } getincomeimgurl(); } }, [income_statement_attachment, identityId]); useEffect(() => { if (income_statement_attachment) { async function getincomepdfurl() { var uploadext = income_statement_attachment.split(".").pop(); var imageExtensions = ["pdf", "PDF"]; const x = imageExtensions.includes(uploadext); if (x === true) { const y = await Storage.get(income_statement_attachment, { level: "private", identityId: identityId, }); setIncomepdf(y); } } getincomepdfurl(); } }, [income_statement_attachment, identityId]); function incomeisimageorpdf(label, name) { var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-/]))?/; if (regex.test(incomeimg)) { return ( <> <Grid item md={12} xs={12}> <img className={classes.img} alt="complex" src={incomeimg} /> <div> <input id={incomeimg} accept="image/*,application/pdf" style={{ display: "none" }} type="file" onChange={(event) => handleincomeChange(event)} /> <label htmlFor={incomeimg}> <LoaderButton id={incomeimg} fullWidth component="span" startIcon={<UploadIcon />} disabled={incomeloading} success={incomesuccess} loading={incomeloading} > {" "} Update File </LoaderButton> </label> </div> </Grid> </> ); } else if (regex.test(incomepdf)) { return ( <> <Grid item md={12} xs={12}> <iframe title="file" style={{ width: "100%", height: "100%" }} allowFullScreen src={incomepdf} /> <div> <input id={incomepdf} accept="image/*,application/pdf" style={{ display: "none" }} type="file" onChange={(event) => handleincomeChange(event)} /> <label htmlFor={incomepdf}> <LoaderButton id={incomepdf} fullWidth component="span" startIcon={<UploadIcon />} disabled={incomeloading} success={incomesuccess} loading={incomeloading} > {" "} Update File </LoaderButton> </label> </div> </Grid> </> ); } else { return ( <> <Grid item md={12} xs={12}> <input name={incomename} id={incomelabel} accept="image/*,application/pdf" style={{ display: "none" }} type="file" onChange={(event) => handleincomeChange(event)} /> <label htmlFor={incomelabel}> <LoaderButton id={incomelabel} fullWidth component="span" startIcon={<UploadIcon />} disabled={incomeloading} success={incomesuccess} loading={incomeloading} > {" "} {incomename} </LoaderButton> </label> </Grid> </> ); } } function handleincomeChange(event) { file.current = event.target.files[0]; const newincomefile = file.current; onincomeChange(newincomefile); } async function onincomeChange(newfile) { setIncomeSuccess(false); setIncomeLoading(true); try { const u = newfile ? await s3Up(newfile, "income_statement_attachment") : null; var income_statement_attachment = u; const sortkey = financialsId; const userId = value.userId; await updateFinancials({ sortkey, userId, income_statement_attachment, }); } catch (e) { onError(e); } setIncomeSuccess(true); setIncomeLoading(false); navigate("/admin/buyers"); } useEffect(() => { if (balance_sheet_attachment) { async function getjson() { const y = await Storage.get( `${userId}${financialsId}balance_sheet_attachment.json`, { level: "private", identityId: identityId, download: true, } ); const s = await new Response(y.Body).json(); if (s) { const t = s[0].Blocks.map((item) => item.Text); setSheet(t); } } getjson(); } }, [userId, financialsId, balance_sheet_attachment, identityId]); useEffect(() => { if (income_statement_attachment) { async function getjson() { const y = await Storage.get( `${userId}${financialsId}income_statement_attachment.json`, { level: "private", identityId: identityId, download: true, } ); const s = await new Response(y.Body).json(); if (s) { const t = s[0].Blocks.map((item) => item.Text); setIncome(t); } } getjson(); } }, [userId, financialsId, income_statement_attachment, identityId]); return ( <Page title="Update Financials"> <Container> <form autoComplete="off" noValidate className={clsx(classes.root, className)} {...rest} > <Card> <CardContent> <Grid container spacing={3}> <Grid item md={6} xs={12}> <> <Typography>Balance Sheet:</Typography> {balanceisimageorpdf(balancelabel, balancename)} </> </Grid> <Grid item md={6} xs={12} style={{ width: "100%", maxWidth: 500, overflow: "auto" }} > <Typography>Balance Sheet Text:</Typography> <Typography>{sheet}</Typography> </Grid> <Divider></Divider> <Grid item md={12} xs={12}> <TableContainer component={Paper}> <Table className={classes.table} size="small" aria-label="Balance Sheet Table" > <TableHead> <TableRow> <TableCell></TableCell> <TableCell align="left"> <Box fontWeight="fontWeightBold"> {moment(financials_reporting_period).format( "YYYY" )} </Box> </TableCell> </TableRow> </TableHead> <TableBody> <TableRow className={classes.tableRow}> <TableCell component="th" scope="row"> Mandatory Fields </TableCell> <TableCell component="th" scope="row"></TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Cash </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setCash(e.target.value)} required value={cash || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Accounts Receivable </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setAccounts_receivable(e.target.value) } required value={accounts_receivable || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Inventory </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setInventory(e.target.value)} required value={inventory || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Other Current Assets </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setOther_current_assets(e.target.value) } required value={other_current_assets || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> Current Assets </Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={current_assets || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Fixed Assets (PPE) </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setSale_purchase_of_fixed_asset(e.target.value) } required value={sale_purchase_of_fixed_asset || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Intangibles/Goodwill </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setGoodwill(e.target.value)} required value={goodwill || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Other Non-Current Assets </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setOther_non_current_assets(e.target.value) } required value={other_non_current_assets || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold">Total Assets</Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={total_assets || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Accounts Payable </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setAccounts_payable(e.target.value) } required value={accounts_payable || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Current Portion of Long-Term Debt </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setCurrent_long_term_debt(e.target.value) } required value={current_long_term_debt || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Other Current Liabilities </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setOther_current_liabilities(e.target.value) } required value={other_current_liabilities || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> Current Liabilities </Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={current_liabilities || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Long Term Debt </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setLong_term_debt(e.target.value) } required value={long_term_debt || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Other Long Term Liabilities </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setOther_long_term_liabilities(e.target.value) } required value={other_long_term_liabilities || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> Total Liabilities </Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={total_liabilities || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Total Equity </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth required onChange={(e) => setTotal_equity(e.target.value)} value={total_equity || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> Total Equity and Liabilities </Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={total_liabilities_and_equity || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow className={classes.tableRow}> <TableCell component="th" scope="row"> Optional Fields </TableCell> <TableCell component="th" scope="row"></TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Marketable Securities </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setMarketable_securities(e.target.value) } required value={marketable_securities || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Accumulated Depreciation </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setAccumulated_depreciation(e.target.value) } required value={accumulated_depreciation || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Unearned Revenue </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setUnearned_revenue(e.target.value) } required value={unearned_revenue || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Accured Expenses </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setAccured_expenses(e.target.value) } required value={accured_expenses || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Income Tax Payable </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setIncome_tax_payable(e.target.value) } required value={income_tax_payable || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Dividends Payable </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setDividends_payable(e.target.value) } required value={dividends_payable || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Common Stock </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setCommon_stock(e.target.value)} required value={common_stock || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Preferred Stock </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setPreferred_stock(e.target.value) } required value={preferred_stock || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Paid In Capital </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setPaid_in_capital(e.target.value) } required value={paid_in_capital || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Retained Earnings </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setRetained_earnings(e.target.value) } required value={retained_earnings || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Equity Market Value </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setEquity_market_value(e.target.value) } required value={equity_market_value || ""} variant="outlined" /> </TableCell> </TableRow> </TableBody> </Table> </TableContainer> <Box display="flex" justifyContent="flex-end" p={2}> <LoaderButton startIcon={<UploadIcon />} disabled={financialsloading} success={financialssuccess} loading={financialsloading} onClick={handleFinancialsSubmit} > Update Balance Sheet </LoaderButton> </Box> </Grid> <Grid item md={6} xs={12}> <> <Typography>Income Statement:</Typography> {incomeisimageorpdf(incomelabel, incomename)} </> </Grid> <Grid item md={6} xs={12} style={{ width: "100%", maxWidth: 500, overflow: "auto" }} > <Typography>Income Statement Text:</Typography> <Typography>{income}</Typography> </Grid> <Grid item md={12} xs={12}> <TableContainer component={Paper}> <Table className={classes.table} size="small" aria-label="Balaance Sheet Table" > <TableHead> <TableRow> <TableCell></TableCell> <TableCell align="left"> {moment(financials_reporting_period).format("YYYY")} </TableCell> </TableRow> </TableHead> <TableBody> <TableRow className={classes.tableRow}> <TableCell component="th" scope="row"> Mandatory Fields </TableCell> <TableCell component="th" scope="row"></TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Sales </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setSales(e.target.value)} required value={sales || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Cost of Goods Sold </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setCost_of_goods_sold(e.target.value) } required value={cost_of_goods_sold || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold">Gross Margin</Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={gross_margin || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Depreciation Expenses </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setDepreciation_expenses(e.target.value) } required value={depreciation_expenses || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Operating Expenses </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setOperating_expenses(e.target.value) } required value={operating_expenses || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> Operating Income </Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={operating_income || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Interest Expenses </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setInterest_expenses(e.target.value) } required value={interest_expenses || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Other Expenses </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setOther_expenses(e.target.value) } required value={other_expenses || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold">EBT</Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={ebt || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Income Tax Expense </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setIncome_tax_expense(e.target.value) } required value={income_tax_expense || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold">EBIT</Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={ebit || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Extraordinary Income / Expense </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setExtraordinary_income(e.target.value) } required value={extraordinary_income || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold">Net Profit</Box> </TableCell> <TableCell component="th" scope="row"> <Box fontWeight="fontWeightBold"> <TextField type="number" fullWidth required value={net_profit || ""} variant="outlined" InputProps={{ readOnly: true, }} /> </Box> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Operating Cash Flow </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setCash_flow(e.target.value)} required value={cash_flow || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Inventory Turnover (COGS/ Average Inventory current and last year) </TableCell> <TableCell component="th" scope="row"> <TextField type="text" fullWidth onChange={(e) => setInventory_turnover(e.target.value) } value={inventory_turnover | ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Interest Coverage (IE + EBT / IE) </TableCell> <TableCell component="th" scope="row"> <TextField type="text" fullWidth onChange={(e) => setInterest_coverage(e.target.value) } value={interest_coverage | ""} variant="outlined" /> </TableCell> </TableRow> <TableRow className={classes.tableRow}> <TableCell component="th" scope="row"> Optional Fields </TableCell> <TableCell component="th" scope="row"></TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Marketing Expenses </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setMarketing_expenses(e.target.value) } required value={marketing_expenses || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Bad Debt Expenses </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setBad_debt_expenses(e.target.value) } required value={bad_debt_expenses || ""} variant="outlined" /> </TableCell> </TableRow> <TableRow> <TableCell component="th" scope="row"> Tax Expenses </TableCell> <TableCell component="th" scope="row"> <TextField type="number" fullWidth onChange={(e) => setTax_expenses(e.target.value)} required value={tax_expenses || ""} variant="outlined" /> </TableCell> </TableRow> </TableBody> </Table> </TableContainer> <Box display="flex" justifyContent="flex-end" p={2}> <LoaderButton startIcon={<UploadIcon />} disabled={financialsloading} success={financialssuccess} loading={financialsloading} onClick={handleFinancialsSubmit} > Update Income Statement </LoaderButton> </Box> </Grid> </Grid> </CardContent> </Card> </form> </Container> </Page> ); }; export default UpdateFinancialsForm; <filename>proc/scanner.js const fs = require('fs'); const path = require('path') const proc = require('child_process'); const conf = require('../common/config'); const dirfile = require('dirfile'); let handler = null; module.exports = { start: function(){ if(!handler){ dirfile(conf.input_file.DIR, false, false, function(filePath, stat){ return path.extname(filePath) == '.netxml'; }, function(filePath, stat){ fs.unlinkSync(filePath); return; }) handler = proc.spawn('sudo', [ 'airodump-ng', '-w', path.join(conf.input_file.DIR, conf.input_file.PREFIX), '--output-format', 'netxml', conf.INTERFACE ] ) handler.on('error', (err)=>{ console.log(err); }) // handler.stdout.on('data', (data)=>{ // console.log(data.toString()); // }) } return handler; } } 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fal'; var iconName = 'union'; var width = 320; var height = 512; var ligatures = []; var unicode = 'f6a2'; var svgPathData = 'M170.65 447.65C255.69 442.15 320 367.74 320 282.52V72c0-4.42-3.58-8-8-8h-16c-4.42 0-8 3.58-8 8v211.48c0 68.11-51.28 127.67-119.24 132.22C94.24 420.7 32 361.48 32 288V72c0-4.42-3.58-8-8-8H8c-4.42 0-8 3.58-8 8v216c0 91.89 77.46 165.69 170.65 159.65z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faUnion = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;//-- ================================================================================= --// //-- Summary :: Check that the login page is formatted correctly //-- Created :: 10Apr2022 //-- Author :: <NAME> (<EMAIL>) //-- ================================================================================= --// describe('001.003 - Login form is correctly formatted', () => { context('Page formatted correctly', () => { it('Opens the login page and checks that it is correctly setup', () => { cy.visit('/'); //-- Nav bar cy.get('[data-cy=link-login]').should('be.visible'); //-- Form cy.get('[data-cy=login-logo-pips]').should('be.visible'); cy.get('[data-cy=login-logo-study]').should('be.visible'); cy.get('[data-cy=login-title]').should('be.visible'); cy.get('[data-cy=login-title]').should('contain.text', 'Welcome to the OCTRU Participant Information PortalS'); cy.get('[data-cy=login-instruction]').should('be.visible'); cy.get('[data-cy=login-instruction]').should('contain.text', 'Please enter your email address and PIPS password to access your Portal'); cy.get('[data-cy=login-input-email-label]').should('be.visible'); cy.get('[data-cy=login-input-email-label]').should('contain.text', 'Email Address'); cy.get('[data-cy=login-input-email]').should('be.visible'); cy.get('[data-cy=login-input-email]').invoke('attr', 'type').should('eq', 'email'); cy.get('[data-cy=login-input-password-label]').should('be.visible'); cy.get('[data-cy=login-input-password-label]').should('contain.text', 'Password'); cy.get('[data-cy=login-input-password]').should('be.visible'); cy.get('[data-cy=login-input-password]').invoke('attr', 'type').should('eq', 'password'); cy.get('[data-cy=login-input-remember_me-label]').should('be.visible'); cy.get('[data-cy=login-input-remember_me-label]').should('contain.text', 'Remember Me'); cy.get('[data-cy=login-input-remember_me]').should('be.visible'); cy.get('[data-cy=login-input-remember_me]').invoke('attr', 'type').should('eq', 'checkbox'); cy.get('[data-cy=login-submit]').should('be.visible'); cy.get('[data-cy=login-submit]').invoke('attr', 'type').should('eq', 'submit'); cy.get('[data-cy=login-submit]').should('contain.text', 'Login'); cy.get('[data-cy=login-forgot-password]').should('be.visible'); cy.get('[data-cy=login-forgot-password]').should('contain.text', '<PASSWORD> Your Password?'); }); }) ; }); <filename>server/controller/comment.js const Post = require('../models/post'); module.exports = { new: (req, res) => { Post.findOne({ _id: req.body.post_id }) .exec((err, post) => { if (err) { throw err; } if (post) { post.post_comments.push({ comment_from: req.body.id, comment_text: req.body.comment }); post.save((err, data) => { if (err) { throw err; } post.populate({ path: 'post_comments.comment_from', select: 'photo_url display_name' }, (err, data) => { res.send({ message: 'Comment success', code: 200, data }); }); }); } }); }, }; <reponame>liorEhrlich/portfolio import styled from "@emotion/styled" const SectionWrapper = styled.div` margin-top:250px; ` export default SectionWrapperimport React from "react" import styled from "styled-components" import { Link as GatsbyLink } from "gatsby" export default function Logo({ siteTitle }) { return ( <StyledLink to="/"> <StyledLogo> Tiger<span>l</span>ine Golf Sites </StyledLogo> </StyledLink> ) } const StyledLink = styled(GatsbyLink)` text-decoration: none; ` const StyledLogo = styled.h1` color: #c7d1d5; font-size: 1.6em; :hover { color: ${props => props.theme.colors.action}; } span { color: ${props => props.theme.colors.action}; } ` <gh_stars>0 import React from 'react'; // == React Icons import { FaTimes } from 'react-icons/fa'; // == Assets import Img from '../../assets/img/portfolio/prendre-laire.gif'; // == CSS import './modal1.scss'; // == Composant const Modal1 = () => ( <div className="portfolio-modal modal fade" id="portfolioModal1" tabIndex="-1" role="dialog" aria-hidden="true"> <div className="modal-dialog"> <div className="modal-content"> <div className="close-modal" data-dismiss="modal"> <div className="lr"> <div className="rl" /> </div> </div> <div className="container"> <div className="row"> <div className="col-lg-8 mx-auto"> <div className="modal-body"> <h2 className="text-uppercase">Prendre l'aire</h2> <p className="item-intro text-muted">Site collaboratif concernant les aires d'autoroutes françaises.</p> <img className="img-fluid d-block mx-auto" src={Img} alt="" /> <p>C'est un projet de fin de formation réalisé en 15 jours.<br /> Nous étions un groupe de 5 développeurs :<br /> - 2 personnes en frontend sur React.js<br /> - 3 personnes en backend API sur Symfony. </p> <p>Prendre l'aire est un site collaboratif qui vise à mettre en relation les usagers des aires d'autoroutes françaises.</p> <p><a href="https://youtu.be/zgBx2B4Xwd4?t=4309">Vidéo de présentation disponible sur Youtube</a></p> <ul className="list-inline"> <li className="modal-li">Date: Février 2020</li> <li className="modal-li">Projet de fin de formation</li> <li className="modal-li">Categorie: Web App</li> </ul> <button className="btn btn-primary" data-dismiss="modal" type="button"> <FaTimes /> </button> </div> </div> </div> </div> </div> </div> </div> ); // == Export export default Modal1; import 'knockout'; import 'materialize-css'; import RayTracer from './widgets/RayTracer'; new RayTracer(document.querySelectorAll('[data-widget="RayTracer"]')[0]);<gh_stars>0 import axios from 'axios'; import {Map} from 'immutable'; import Auth from '../lib/Auth'; import QueryString from '../lib/QueryString'; import Logger from '../lib/Logger'; import Config from '../Config'; class API { constructor(config, axios) { Logger.log('debug', `API.constructor(###, ###)`); // config props this.environment = config.get('ENVIRONMENT'); this.base_url = config.get('API_BASE_URL'); this.app_key = config.get('API_APP_KEY'); // internal props this.axios = axios; this.authToken = null; this.authExpires = null; this.destroySession = null; } setAuthToken(authToken) { this.authToken = authToken; } setAuthExpires(authExpires) { this.authExpires = authExpires; } setDestroySession(destroySession) { this.destroySession = destroySession; } // destroy session data and redirect to auth screen _logout = () => { Logger.log('debug', `API._logout()`); this.destroySession(); } // get authentication token _getAuthToken() { Logger.log('debug', `API._getAuthToken()`); const authToken = this.authToken; const authExpires = this.authExpires; return Auth.isAuthTokenValid(authToken, authExpires) ? authToken : false; } // get request headers _getRequestHeaders(validateStatus=null, authenticate=true) { Logger.log('debug', `API._getRequestHeaders(${validateStatus}, ${authenticate})`); const authToken = this._getAuthToken(); if (authenticate && !authToken) { this._logout(); return false; } const authConfig = authToken ? {"auth": {"username": authToken}} : {}; const vaildateStatusConfig = validateStatus ? {"validateStatus": (status) => status < validateStatus} : {}; return {...authConfig, ...vaildateStatusConfig}; } // get full URI for an API endpoint _getUri(path) { Logger.log('debug', `API._getUri(${path})`); return this.base_url + path + (path.includes('?') ? '&' : '?') + 'app_key=' + this.app_key; } // generic API call helper async _callApi(method, path, payload=null, authenticate=true) { Logger.log('debug', `API._callApi(###, ${path}, ###, ${authenticate})`, payload); // get headers and check authentication token const requestHeaders = this._getRequestHeaders(500, authenticate); if (false === requestHeaders) { return Map({'status': 401, 'data': {'error': `Not Authenticated`}}); } if (payload) { // call API with payload return await method(path, payload, requestHeaders) .then(async function(response) { Logger.log('verbose', `API Response:`, response); if (response.status === 401) { this._logout(); } return Map(response); }) .catch(function(error) { Logger.log('error', `${error}`); return Map({'status': 500, 'data': {'error': `${error}`}}); }); } else { // call API without payload return await method(path, requestHeaders) .then(async function(response) { Logger.log('verbose', `API Response:`, response); if (response.status === 401) { this._logout(); } return Map(response); }) .catch(function(error) { Logger.log('error', `${error}`); return Map({'status': 500, 'data': {'error': `${error}`}}); }); } } // GET method async GET(path, authenticate=true) { Logger.log('debug', `API.GET(${path}, ${authenticate})`); return await this._callApi(this.axios.get, path, null, authenticate); } // POST method async POST(path, payload, authenticate=true) { Logger.log('debug', `API.POST(${path}, %j, ${authenticate})`, payload); return await this._callApi(this.axios.post, path, payload, authenticate); } // PUT method async PUT(path, payload, authenticate=true) { Logger.log('debug', `API.PUT(${path}, %j, ${authenticate})`, payload); return await this._callApi(this.axios.put, path, payload, authenticate); } // DELETE method async DELETE(path, authenticate=true) { Logger.log('debug', `API.DELETE(${path}, ${authenticate})`); return await this._callApi(this.axios.delete, path, null, authenticate); } // GET /token async getToken(username, password) { Logger.log('debug', `API.getToken(###, ###)`); // prep credentials header config const authConfig = { "auth": { "username": username, "password": password }, "validateStatus": function (status) { return status < 500; } } // call API const output = await this.axios.get(this._getUri(`/token`), authConfig) .then(async function(response) { Logger.log('verbose', "API Response: %j", response); return Map(response); }) .catch(function(error) { Logger.log('error', `${error}`); return Map({'status': 500, 'data': {'error': `${error}`}}); }); return output; } // GET /account async getAccount() { Logger.log('debug', `API.getAccount()`); return await this.GET(this._getUri(`/user_account`)); } // PUT /account async putAccount(payload) { Logger.log('debug', `API.putAccount(%j)`, payload); return await this.PUT(this._getUri(`/user_account`), payload); } // PUT /account/password async putAccountPassword(payload) { Logger.log('debug', `API.putAccountPassword(%j)`, payload); return await this.PUT(this._getUri(`/user_account/password`), payload); } // GET /categories async getCategories(page=1, limit=10) { Logger.log('debug', `API.getCategories(${page}, ${limit})`); return await this.GET(this._getUri(`/categories/${parseInt(page)}/${parseInt(limit)}`)); } // GET /roles async getRoles(page=1, limit=10, order=null, filter=null, type=null) { Logger.log('debug', `API.getRoles(${page}, ${limit}, ${order}, %j, ${type})`, filter); if (type) { return await this.GET(this._getUri(QueryString.append(`/roles/${type}/${parseInt(page)}/${parseInt(limit)}`, {order_by: order, ...filter}))); } else { return await this.GET(this._getUri(QueryString.append(`/roles/${parseInt(page)}/${parseInt(limit)}`, {order_by: order, ...filter}))); } } // GET /role/{id} async getRole(id) { Logger.log('debug', `API.getRole(${id})`); return await this.GET(this._getUri(`/role/${parseInt(id)}`)); } // POST /roles async postRoles(payload) { Logger.log('debug', `API.postRoles(%j)`, payload); return await this.POST(this._getUri(`/roles`), payload); } // PUT /role/{id} async putRole(id, payload) { Logger.log('debug', `API.putRole(${id}, %j)`, payload); return await this.PUT(this._getUri(`/role/${parseInt(id)}`), payload); } // DELETE /role/{id} async deleteRole(id) { Logger.log('debug', `API.deleteRole(${id})`); return await this.DELETE(this._getUri(`/role/${parseInt(id)}`)); } // GET /countries async getCountries(page=1, limit=250) { Logger.log('debug', `API.getCountries(${page}, ${limit})`); return await this.GET(this._getUri(`/countries/${parseInt(page)}/${parseInt(limit)}`)); } // GET /regions/{countryCode} async getRegions(countryCode, page=1, limit=100) { Logger.log('debug', `API.getRegions(${countryCode}, ${page}, ${limit})`); return await this.GET(this._getUri(`/regions/${countryCode}/${parseInt(page)}/${parseInt(limit)}`)); } // GET /users async getUsers(page=1, limit=10, order=null, filter=null) { Logger.log('debug', `API.getUsers(${page}, ${limit}, ${order}, %j)`, filter); return await this.GET(this._getUri(QueryString.append(`/users/${parseInt(page)}/${parseInt(limit)}`, {order_by: order, ...filter}))); } // GET /user/{id} async getUser(id) { Logger.log('debug', `API.getUser(${id})`); return await this.GET(this._getUri(`/user/${parseInt(id)}`)); } // POST /users async postUsers(payload) { Logger.log('debug', `API.postUsers(%j)`, payload); return await this.POST(this._getUri(`/users`), payload); } // PUT /user/{id} async putUser(id, payload) { Logger.log('debug', `API.putUser(${id}, %j)`, payload); return await this.PUT(this._getUri(`/user/${parseInt(id)}`), payload); } // DELETE /user/{id} async deleteUser(id) { Logger.log('debug', `API.deleteUser(${id})`); return await this.DELETE(this._getUri(`/user/${parseInt(id)}`)); } // GET /administrators async getAdministrators(page=1, limit=10, order=null, filter=null) { Logger.log('debug', `API.getAdministrators(${page}, ${limit}, ${order}, %j)`, filter); return await this.GET(this._getUri(QueryString.append(`/administrators/${parseInt(page)}/${parseInt(limit)}`, {order_by: order, ...filter}))); } // GET /administrator/{id} async getAdministrator(id) { Logger.log('debug', `API.getAdministrator(${id})`); return await this.GET(this._getUri(`/administrator/${parseInt(id)}`)); } // POST /administrators async postAdministrators(payload) { Logger.log('debug', `API.postAdministrators(%j)`, payload); return await this.POST(this._getUri(`/administrators`), payload); } // PUT /administrator/{id} async putAdministrator(id, payload) { Logger.log('debug', `API.putAdministrator(${id}, %j)`, payload); return await this.PUT(this._getUri(`/administrator/${parseInt(id)}`), payload); } // DELETE /administrator/{id} async deleteAdministrator(id) { Logger.log('debug', `API.deleteAdministrator(${id})`); return await this.DELETE(this._getUri(`/administrator/${parseInt(id)}`)); } // GET /app_keys async getAppKeys(page=1, limit=10, order=null, filter=null) { Logger.log('debug', `API.getAppKeys(${page}, ${limit}, ${order}, %j)`, filter); return await this.GET(this._getUri(QueryString.append(`/app_keys/${parseInt(page)}/${parseInt(limit)}`, {order_by: order, ...filter}))); } // GET /app_key/{id} async getAppKey(id) { Logger.log('debug', `API.getAppKey(${id})`); return await this.GET(this._getUri(`/app_key/${parseInt(id)}`)); } // POST /app_keys async postAppKeys(payload) { Logger.log('debug', `API.postAppKeys(%j)`, payload); return await this.POST(this._getUri(`/app_keys`), payload); } // PUT /app_key/{id} async putAppKey(id, payload) { Logger.log('debug', `API.putAppKey(${id}, %j)`, payload); return await this.PUT(this._getUri(`/app_key/${parseInt(id)}`), payload); } // DELETE /app_key/{id} async deleteAppKey(id) { Logger.log('debug', `API.deleteAppKey(${id})`); return await this.DELETE(this._getUri(`/app_key/${parseInt(id)}`)); } // GET /terms_of_services async getTermsOfServices(page=1, limit=10, order=null, filter=null) { Logger.log('debug', `API.getTermsOfServices(${page}, ${limit}, ${order}, %j)`, filter); return await this.GET(this._getUri(QueryString.append(`/terms_of_services/${parseInt(page)}/${parseInt(limit)}`, {order_by: order, ...filter}))); } // GET /terms_of_service/{id} async getTermsOfService(id) { Logger.log('debug', `API.getTermsOfService(${id})`); return await this.GET(this._getUri(`/terms_of_service/${parseInt(id)}`)); } // POST /terms_of_services async postTermsOfServices(payload) { Logger.log('debug', `API.postTermsOfServices(%j)`, payload); return await this.POST(this._getUri(`/terms_of_services`), payload); } // PUT /terms_of_service/{id} async putTermsOfService(id, payload) { Logger.log('debug', `API.putTermsOfService(${id}, %j)`, payload); return await this.PUT(this._getUri(`/terms_of_service/${parseInt(id)}`), payload); } // DELETE /terms_of_service/{id} async deleteTermsOfService(id) { Logger.log('debug', `API.deleteTermsOfService(${id})`); return await this.DELETE(this._getUri(`/terms_of_service/${parseInt(id)}`)); } // GET /logins async getLogins(page=1, limit=10, order=null, filter=null) { Logger.log('debug', `API.getLogins(${page}, ${limit}, ${order}, %j)`, filter); return await this.GET(this._getUri(QueryString.append(`/logins/${parseInt(page)}/${parseInt(limit)}`, {order_by: order, ...filter}))); } } const api = new API(Config, axios); export default api; Logger.log('debug', `API loaded.`); <reponame>phreed/webgme /*globals define */ /*jshint browser: true*/ /** * @author rkereskenyi / https://github.com/rkereskenyi */ define([], function () { 'use strict'; //define client-only string constants return { DRAG_ITEMS: 'DRAG_ITEMS', DRAG_EFFECTS: 'DRAG_EFFECTS', DRAG_INFO: 'DRAG_INFO', DRAG_PARAMS: 'DRAG_PARAMS' }; });/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(["dojo/dom", "dojo/dom-construct", "dojo/dom-class", "dojo/_base/window", "dijit/registry", "dojo/parser", "dojo/_base/lang", "dojo/_base/array", "dojo/_base/event", 'dojo/json', "dojo/query", "dojo/_base/connect", "qpid/common/properties", "dojox/html/entities", "qpid/common/util", "qpid/common/HexDumpWidget", "dojo/text!showMessage.html", 'dojo/_base/declare', 'dstore/Memory', 'dstore/Trackable', "dgrid/OnDemandGrid", "dgrid/extensions/DijitRegistry", "dijit/form/SimpleTextarea", "dojo/domReady!"], function (dom, construct, domClass, win, registry, parser, lang, array, event, json, query, connect, properties, entities, util, HexDumpWidget, template, declare, Memory, Trackable, OnDemandGrid, DijitRegistry) { function encode(val) { return typeof val === 'string' ? entities.encode(val) : val; } var populatedFields = []; var showMessage = {includeHeaders: true}; showMessage.hide = function () { registry.byId("showMessage") .hide(); }; showMessage.loadViewMessage = function (data) { var node = construct.create("div", null, win.body(), "last"); node.innerHTML = data; var that = this; parser.parse(node) .then(function (instances) { that.dialogNode = dom.byId("showMessage"); var closeButton = query(".closeViewMessage", that.dialogNode)[0]; registry.byNode(closeButton) .on("click", function (evt) { event.stop(evt); that.hide(); }); }); }; showMessage.createPreviewWidget = function(contentData, widgetDiv) { if (typeof contentData !== 'object') { return new dijit.form.SimpleTextarea({ value: contentData, rows: 4, readOnly: true }, widgetDiv); } else { if (Array.isArray(contentData)) { var isByteArray = true; for (var i = 0; i < contentData.length; i++) { var element = contentData[i]; if (!util.isInteger(element) || element < -128 || element > 127) { isByteArray = false; break; } } if (isByteArray) { return new HexDumpWidget({data: contentData}, widgetDiv); } else { var columns = { value: { label: 'Item' } }; var items = []; for (var i = 0; i < contentData.length; i++) { items.push({ id: i, value: json.stringify(contentData[i]) }); } var store = new (declare([Memory, Trackable]))({ data: items }); return new (declare([OnDemandGrid, DijitRegistry]))({ collection: store, columns: columns }, widgetDiv); } } else { var columns = { id: { label: 'Key' }, value: { label: 'Value' } }; var items = []; for (var i in contentData) { items.push({ id: i, value: json.stringify(contentData[i]) }); } var store = new (declare([Memory, Trackable]))({ data: items }); return new (declare([OnDemandGrid, DijitRegistry]))({ collection: store, columns: columns }, widgetDiv); } } } showMessage.populateShowMessage = function (management, modelObj, data, includesConfidential) { // clear fields set by previous invocation. if (populatedFields) { for (var i = 0; i < populatedFields.length; i++) { populatedFields[i].innerHTML = ""; } populatedFields = []; } for (var attrName in data) { if (data.hasOwnProperty(attrName)) { var fields = query(".message-" + attrName, this.dialogNode); if (fields && fields.length != 0) { var field = fields[0]; populatedFields.push(field); var val = data[attrName]; if (val != null) { if (domClass.contains(field, "map")) { var tableStr = "<table style='border: 1pt'><tr><th style='width: 6em; font-weight: bold'>Header</th><th style='font-weight: bold'>Value</th></tr>"; for (var name in val) { if (val.hasOwnProperty(name)) { tableStr += "<tr><td>" + encode(name) + "</td>"; tableStr += "<td>" + encode(val[name]) + "</td></tr>"; } } tableStr += "</table>"; field.innerHTML = tableStr; } else if (domClass.contains(field, "datetime")) { field.innerHTML = management.userPreferences.formatDateTime(val, { addOffset: true, appendTimeZone: true }); } else { field.innerHTML = encode(val); } } } } } var contentAndPreview = query('#contentAndPreview', this.dialogNode)[0]; var confidentialInformationWarning = query('#confidentialInformationWarning', this.dialogNode)[0]; confidentialInformationWarning.style.display = includesConfidential ? "none" : "block"; var confidentialCells = query('.confidential', this.dialogNode); for(var i = 0; i < confidentialCells.length; i++) { confidentialCells[i].style.display = includesConfidential ? "block" : "none"; } var confidentialPlaceholderCells = query('.confidentialPlaceholder', this.dialogNode); for(var i = 0; i < confidentialPlaceholderCells.length; i++) { confidentialPlaceholderCells[i].style.display = includesConfidential ? "none" : "block"; } if (includesConfidential) { var contentModelObj = { name: "getMessageContent", parent: modelObj, type: modelObj.type }; var parameters = {messageId: data.id}; var download = registry.byId('message-download', this.dialogNode); download.on("click", function () { management.download(contentModelObj, parameters); }); var limit = 1024; var previewParameters = lang.mixin({ limit: limit, returnJson: true }, parameters); management.load(contentModelObj, previewParameters, { handleAs: "json" }) .then(function (content) { if (showMessage.previewWidget) { showMessage.previewWidget.destroyRecursive(); } if (content == null || (Array.isArray(content) && content.length == 0)) { contentAndPreview.style.display = "none"; } else { contentAndPreview.style.display = "block"; var previewDetail = query('#preview-detail', contentAndPreview)[0]; previewDetail.innerHTML = (limit < data.size ? 'showing the first ' + limit + ' of ' + data.size + ' bytes' : 'showing all ' + data.size + ' bytes'); var previewContent = query("#message-content-preview", contentAndPreview)[0]; var widgetDiv = construct.create("div", null, previewContent, "last"); var contentWidget = showMessage.createPreviewWidget(content, widgetDiv); showMessage.previewWidget = contentWidget; contentWidget.startup(); } registry.byId("showMessage") .show(); }); } else { registry.byId("showMessage").show() } }; var loadMessage = function (management, modelObj, id, includeHeaders, errorHandler) { var obj = { name: "getMessageInfoById", parent: modelObj, type: modelObj.type }; management.load(obj, { messageId: id, includeHeaders: includeHeaders }) .then(function (data) { showMessage.populateShowMessage(management, modelObj, data, includeHeaders); }, errorHandler); }; showMessage.show = function (management, modelObj, message) { loadMessage(management, modelObj, message.id, this.includeHeaders, function (e) { if (showMessage.includeHeaders && e.response && e.response.status == 403) { showMessage.includeHeaders = false; loadMessage(management, modelObj, message.id, false); } else { management.errorHandler(e); } }); }; showMessage.loadViewMessage(template); return showMessage; }); <reponame>alavrenchenko/web-framework-js<filename>src/ui/js/component.js /* * Copyright 2018 <NAME> (http://alavrenchenko.com/). 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. */ /** * @abstract * @constructor * @implements {WebF.ui.IComponent} * @param {WebF.dom.DOMHelper} domHelper */ WebF.ui.Component = function (domHelper) { /** * @private * @readonly */ this._dom = domHelper; /** * The root DOM element of this component. * * @private * @type {Element} */ this._element = null; /** * @readonly * @type {number} */ this.id = WebF.ui.IdGenerator.current.getUniqueId(); /** * @private * @type {WebF.ui.Component} */ this._parent = null; /** * @type {string} */ this.name = null; /** * @private * @type {Array<WebF.ui.Component>} */ this._children = []; /** * @type {Object} */ this.tag = null; /** * @private */ this._disposed = false; /** * @private */ this._eventDispatcher = new WebF.events.EventDispatcher(this.onEventDispatcherAction.bind(this)); /* * @type {WebF.events.MultipleEventHandler<WebF.events.WFEvent>} */ //this.disposed = new WebF.events.MultipleEventHandler(); /** * @private */ this._isInDocument = false; /** * @private */ this._wasApplied = false; /** * @private * @type {Array<WebF.events.EventHandler>} */ this._nativeEventHandlers = []; }; /** * @param {string} type * @param {function} handler */ WebF.ui.Component.prototype.addEventHandler = function (type, handler) { this._eventDispatcher.addEventHandler(type, handler); }; /** * @param {string} type * @param {function} handler */ WebF.ui.Component.prototype.removeEventHandler = function (type, handler) { this._eventDispatcher.removeEventHandler(type, handler); }; /** * @param {string} type */ WebF.ui.Component.prototype.removeAllEventHandlers = function (type) { this._eventDispatcher.removeAllEventHandlers(type); }; /** * @param {WebF.events.WFEvent|Event|Object} e */ WebF.ui.Component.prototype.dispatchEvent = function (e) { this._eventDispatcher.dispatchEvent(e); }; /** * @returns {number} */ WebF.ui.Component.prototype.getEventTypeCount = function () { return this._eventDispatcher.getEventTypeCount(); }; /** * @param {string} [type] * @returns {number} */ WebF.ui.Component.prototype.getEventHandlerCount = function (type) { return this._eventDispatcher.getEventHandlerCount(type); }; /** * @param {string} [type] * @returns {Array<WebF.events.EventHandlers>} */ WebF.ui.Component.prototype.getEventHandlers = function (type) { return this._eventDispatcher.getEventHandlers(type); }; /** * @protected * @virtual * @param {WebF.events.EDActionEvent} e */ WebF.ui.Component.prototype.onEventDispatcherAction = function (e) { }; /** * @protected * @returns {Array<WebF.events.EventHandler>} */ WebF.ui.Component.prototype.getNativeEventHandlers = function () { return this._nativeEventHandlers; }; /** * Returns the component's parent, if any. * * @returns {WebF.ui.Component} */ WebF.ui.Component.prototype.getParent = function () { return this._parent; }; /** * * @param {WebF.ui.Component} parent The parent component. */ WebF.ui.Component.prototype.setParent = function (parent) { if (parent == this) { throw new Error('Unable to set parent component.'); } if (this._parent == parent) { return; } this._parent = parent; this.onParentChanged(); }; /** * @protected * @virtual */ WebF.ui.Component.prototype.onParentChanged = function () { }; /** * Gets the root DOM element of this component. * * @returns {Element} */ WebF.ui.Component.prototype.getElement = function () { return this._element; }; /** * Sets the root DOM element of this component. * * @protected * @param {Element} element */ WebF.ui.Component.prototype.setElement = function (element) { if (this._element != null) { return; } this._element = element; }; /** * Determines whether the component has been added to the document. * * @returns {boolean} */ WebF.ui.Component.prototype.isInDocument = function () { return this._isInDocument; }; /** * Determines whether an element was applied to the component. * * @returns {boolean} */ WebF.ui.Component.prototype.wasApplied = function () { return this._wasApplied; }; /** * Returns the dom helper that is being used on this component. * * @returns {WebF.dom.DOMHelper} */ WebF.ui.Component.prototype.getDOMHelper = function () { return this._dom; }; /** * @returns {string} */ WebF.ui.Component.prototype.getType = function () { return this.constructor.name; }; /** * @override * @returns {string} */ WebF.ui.Component.prototype.toString = function () { return this.constructor.name; }; /** * Renders the component. * * @virtual * @param {Element} parentElement * @param {Node} [beforeNode] */ WebF.ui.Component.prototype.render = function (parentElement, beforeNode) { if (!parentElement || this._isInDocument) { return; } if (!this._element) { this.onRender(); this.registerNativeEventHandlers(); } parentElement.insertBefore(this._element, beforeNode || null); if (this._parent) { if (!this._parent.isInDocument()) { return; } } else if (!parentElement.parentElement || !this._dom.documentContains(parentElement.parentElement)) { return; } this.enterDocument(); }; /** * @protected * @virtual */ WebF.ui.Component.prototype.onRender = function () { if (!this._element) { this._element = this._dom.getDocument().createElement('div'); } }; WebF.ui.Component.prototype.enterDocument = function () { this._isInDocument = true; for (var x = 0; x < this._children.length; x++) { var child = this._children[x]; if (!child.isInDocument() && child.getElement()) { child.enterDocument(); } } }; WebF.ui.Component.prototype.exitDocument = function () { for (var x = 0; x < this._children.length; x++) { var child = this._children[x]; if (child.isInDocument()) { child.exitDocument(); } } this._isInDocument = false; }; /** * @virtual * @param {Element} element */ WebF.ui.Component.prototype.apply = function (element) { if (this._isInDocument || !element) { return; } if (!this._element) { if (!this.canApply(element)) { throw new Error('Invalid element.'); } this._wasApplied = true; this._element = element; this.onApply(); this.registerNativeEventHandlers(); } /* if (!element.parentElement || !this._dom.documentContains(element.parentElement)) { return; } */ if (this._parent) { if (!this._parent.isInDocument()) { return; } } else if (!element.parentElement || !this._dom.documentContains(element.parentElement)) { return; } this.enterDocument(); }; /** * @virtual * @param {Element} element * @returns {boolean} */ WebF.ui.Component.prototype.canApply = function (element) { return true; }; /** * @protected * @virtual */ WebF.ui.Component.prototype.onApply = function () { }; /** * @protected * @virtual */ WebF.ui.Component.prototype.registerNativeEventHandlers = function () { }; /** * @protected * @virtual * @param {boolean} disposeChildren */ WebF.ui.Component.prototype.update = function (disposeChildren) { }; /** * @param {WebF.ui.Component} child * @param {boolean} render */ WebF.ui.Component.prototype.addChild = function (child, render) { this.insertChild(this._children.length, child, render); }; /** * @param {number} index * @param {WebF.ui.Component} child * @param {boolean} render */ WebF.ui.Component.prototype.insertChild = function (index, child, render) { if ((index < 0) || (index > this._children.length)) { throw new Error('Parameter "index" out of range.'); } var childParent = child.getParent(); if (childParent == this) { WebF.array.remove(this._children, child); } else if (childParent != null) { childParent.removeChild(child, false); } child.setParent(this); WebF.array.insert(this._children, index, child); if (child.isInDocument() || render) { if (!this._element) { this.onRender(); } var beforeNodeIndex = index + 1; var beforeNode = (beforeNodeIndex < this._children.length) ? this._children[beforeNodeIndex].element : null; if (child.isInDocument()) { WebF.dom.DOMHelper.removeChild(child.element); this._element.insertBefore(child.element, beforeNode); } else { child.render(this._element, beforeNode); } } else if (this._isInDocument && !child.isInDocument() && child.element && this._dom.documentContains(child.element)) { child.enterDocument(); } }; /** * Returns the number of children of this component. * * @returns {number} */ WebF.ui.Component.prototype.getChildCount = function () { return this._children.length; }; /** * @returns {boolean} */ WebF.ui.Component.prototype.hasChildren = function () { return (this._children.length > 0); }; /** * * @param {function(WebF.ui.Component): boolean} predicate * @returns {WebF.ui.Component} * * @example * component.getChild(function (x) { * return (x.name === 'componentName'); * }); */ WebF.ui.Component.prototype.getChild = function (predicate) { return WebF.array.find(this._children, predicate); }; /** * @param {number} id * @returns {WebF.ui.Component} */ WebF.ui.Component.prototype.getChildById = function (id) { return WebF.array.findById(this._children, id); }; /** * * @param {string} name The name of the child. * @returns {WebF.ui.Component} */ WebF.ui.Component.prototype.getChildByName = function (name) { return WebF.array.findByPropertyValue(this._children, 'name', name); }; /** * * @param {number} index The name of the cookie. * @returns {WebF.ui.Component} */ WebF.ui.Component.prototype.getChildAt = function (index) { return this._children[index] || null; }; /** * * @param {WebF.ui.Component} child * @returns {number} */ WebF.ui.Component.prototype.indexOfChild = function (child) { return (child ? this._children.indexOf(child) : -1); }; /** * * @param {WebF.ui.Component} child * @param {boolean} [unrender] The default is true. * @returns {WebF.ui.Component} */ WebF.ui.Component.prototype.removeChild = function (child, unrender) { /* if (!child || (child.getParent() != this)) { return null; } child = WebF.array.remove(this._children, child); if (!child) { return null; } if (unrender !== false) { child.exitDocument(); if (child.element) { WebF.dom.DOMHelper.removeChild(child.element); } } child.setParent(null); return child; */ if (!child || (child.getParent() != this)) { return null; } var index = this.indexOfChild(child); return (index > -1) ? this.removeChildAt(index, unrender) : null; }; /** * * @param {number} index * @param {boolean} [unrender] The default is true. * @returns {WebF.ui.Component} */ WebF.ui.Component.prototype.removeChildAt = function (index, unrender) { //return this.removeChild(this.getChildAt(index), unrender); var child = this._children[index]; if (!child) { return null; } child = WebF.array.removeAt(this._children, index); if (!child) { return null; } if (unrender !== false) { child.exitDocument(); if (child.element) { WebF.dom.DOMHelper.removeChild(child.element); } } child.setParent(null); return child; }; /** * @param {boolean} [unrender] The default is true. * @returns {Array<WebF.ui.Component>} */ WebF.ui.Component.prototype.removeChildren = function (unrender) { var removedChildren = []; // Chrome (v: 68.0.3440.75): < 50856 if ((this._children.length < 30000) || (!WebF.userAgent.browser.isChrome() && (this._children.length < 500000))) { while (this._children.length > 0) { var child = this.removeChildAt(0, unrender); if (child) { removedChildren.push(child); } } } else { while (this._children.length > 0) { var child = this.removeChildAt(this._children.length - 1, unrender); if (child) { removedChildren.push(child); } } removedChildren.reverse(); } return removedChildren; }; /** * @private * @param {WebF.events.WFEvent} e */ WebF.ui.Component.prototype._onDisposed = function (e) { this._eventDispatcher.dispatchEvent(e); //this.disposed.invoke(e); }; /** * @returns {boolean} */ WebF.ui.Component.prototype.isDisposed = function () { return this._disposed; }; /** * @virtual */ WebF.ui.Component.prototype.dispose = function () { if (this._disposed) { return; } this._disposed = true; this._isInDocument = false; this._eventDispatcher.removeAllEventHandlers(); var x; if (this._element) { for (x = 0; x < this._nativeEventHandlers.length; x++) { var neh = this._nativeEventHandlers[x]; neh.source.removeEventListener(neh.eventType, neh.handler); neh.handler = null; } } this._nativeEventHandlers = null; for (x = 0; x < this._children.length; x++) { this._children[x].dispose(); } if (!this._wasApplied && this._element && this._element.parentElement) { this._element.parentElement.removeChild(this._element); } this._element = null; this._parent = null; WebF.array.clear(this._children); var e = new WebF.events.WFEvent(WebF.ui.ComponentEventType.DISPOSED, this); this._onDisposed(e); //this.disposed.removeAllHandlers(); };<filename>src/store/index.js import { configureStore } from '@reduxjs/toolkit' import loadingReducer from '../feature/loading/loadingSlice' import libraryReducer from '../feature/library/librarySlice' import searchReducer from '../feature/search/searchSlice' export default configureStore({ reducer: { loading: loadingReducer, library: libraryReducer, search: searchReducer, }, })<gh_stars>1-10 function alert_fail(title='',msg=''){ var index = layer.load(0, {shade: false, offset: '400px'},{time:1000}); //0代表加载的风格,支持0-2 setTimeout(function() { layer.close(index); layer.msg(msg, { title:title //不自动关闭 ,time:1000 ,icon:5 , offset: '400px' }); },1000); setTimeout(function() { layer.closeAll(); },2000) } function alert_success_url(title='',msg='',url){ var index = layer.load(0, {shade: false , offset: '400px'},{time:3000}); //0代表加载的风格,支持0-2 setTimeout(function() { layer.close(index); layer.msg(msg, { title:title //不自动关闭 ,time:1000 ,icon:6 , offset: '400px' }); },1000) setTimeout(function () { window.location.href=url; layer.closeAll(); },2000) } function alert_success(title='',msg=''){ var index = layer.load(0, {shade: false , offset: '400px'},{time:3000}); //0代表加载的风格,支持0-2 setTimeout(function() { layer.close(index); layer.msg(msg, { title:title //不自动关闭 ,time:1000 ,icon:6 , offset: '400px' }); },1000) } function alert_ask(msg='',yes) { //询问框 layer.confirm(msg, { btn: ['确定','取消'] //按钮 , offset: '400px' }, function () { yes(); layer.closeAll() }, function () { }) } function alert_ask_btn(msg='',btn1='确定',btn2='自定义',btn3='取消',left, right) { //询问框 var index=layer.confirm(msg, { extend:'myskin/alertask.css', skin:'layer-ext-myskin', btn: [btn1,btn2,btn3] //按钮 , offset: '400px' }, function () { left(); layer.closeAll() }, function () { right(); }) } function formatDate(time){ var date = new Date(time); var year = date.getFullYear(), month = date.getMonth()+1,//月份是从0开始的 day = date.getDate(), hour = date.getHours(), min = date.getMinutes(), sec = date.getSeconds(); var newTime = year + '-' + (month < 10? '0' + month : month) + '-' + (day < 10? '0' + day : day) + ' ' + (hour < 10? '0' + hour : hour) + ':' + (min < 10? '0' + min : min) + ':' + (sec < 10? '0' + sec : sec); return newTime; } function encodeUnicode(str) { var res=[]; for (var i=0;i<str.length;i++){ res[i]=('00'+str.charCodeAt(i).toString(16)).slice(-4) } return "\\u"+res.join('\\u') } function decodeUnicode(str) { str=str.replace(/\\/g,'%'); return unescape(str) } function GetRequest() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; }<reponame>samuelhorn/prismic-cli import path from 'path'; import { snakelize, pascalize } from 'sm-commons/utils/str'; import { Files } from '../utils'; export default { apply(id, name, model, isLocal, lib, libPath) { if (!id || !name) return null; return { [name]: { id, lib, libPath: path.normalize(libPath), path: path.normalize(path.join(libPath, name, './model.json')), model, isLocal, }, }; }, fromModelPath(modelPath, isLocal, lib, libPath) { const name = modelPath .replace('/model.json', '') .split('/') .pop(); const id = snakelize(name); const model = Files.readJson(modelPath); return this.apply(id, name, model, isLocal, lib, libPath); }, nameFromId(id) { return pascalize(id); }, }; <reponame>neilZon/SubscriberProject //===================== Users.js ====================== const mongoose = require('mongoose'); // User schema const UserSchema = mongoose.Schema({ email: { type: String, required:true, unique:true }, hash: { type: String, required:true }, firstname: { type: String, required:true }, type: { type: String, required: true, default: "customer" } //TODO: add credit card token property from Stripe }); const User = module.exports = mongoose.model('User', UserSchema, 'users');<gh_stars>100-1000 // @flow import React, { Component } from 'react'; import PostCardList from 'components/common/PostCardList/PostCardList'; import type { State } from 'store'; import { ListingActions } from 'store/actionCreators'; import type { PostItem } from 'store/modules/listing'; import { connect } from 'react-redux'; import throttle from 'lodash/throttle'; import { getScrollBottom, preventStickBottom } from 'lib/common'; type Props = { posts: ?(PostItem[]), prefetched: ?(PostItem[]), prefetching: boolean, loading: boolean, width: number, hasEnded: boolean, selectedTag: ?{ name: string, posts_count: number, }, shouldCancel: boolean, currentTag: ?string, }; class TagPostCards extends Component<Props> { prevCursor: ?string = null; prefetch = async () => { const { posts, prefetching, loading, selectedTag, hasEnded } = this.props; if (!selectedTag || !posts || posts.length === 0 || prefetching || loading) return; const lastId = posts[posts.length - 1].id; if (this.props.prefetched) { ListingActions.revealPrefetched('tag'); await Promise.resolve(); // next tick } if (lastId === this.prevCursor) return; this.prevCursor = lastId; if (hasEnded) return; try { await ListingActions.prefetchTagPosts({ cursor: lastId, tag: selectedTag.name, }); } catch (e) { console.log(e); } preventStickBottom(); this.onScroll(); }; initialize = async () => { const { selectedTag, shouldCancel, currentTag, posts } = this.props; if (selectedTag && currentTag === selectedTag.name && posts && posts.length > 0) { return; } if (!selectedTag) return; try { if (!shouldCancel) { await ListingActions.getTagPosts({ tag: selectedTag.name, }); } await this.prefetch(); } catch (e) { console.log(e); } }; onScroll = throttle(() => { const scrollBottom = getScrollBottom(); if (scrollBottom > 1000) return; this.prefetch(); }, 250); listenScroll = () => { window.addEventListener('scroll', this.onScroll); }; unlistenScroll = () => { window.removeEventListener('scroll', this.onScroll); }; componentDidMount() { this.initialize(); this.listenScroll(); } componentDidUpdate(prevProps) { if (this.props.selectedTag !== prevProps.selectedTag) { this.initialize(); } } componentWillUnmount() { this.unlistenScroll(); } render() { const { selectedTag } = this.props; const placeholderCount = selectedTag ? selectedTag.posts_count : 5; return ( <PostCardList posts={this.props.posts} loading={this.props.loading} prefetching={ (this.props.prefetched && this.props.prefetched.length > 0) || this.props.prefetching } width={this.props.width} hasEnded={this.props.hasEnded} placeholderCount={placeholderCount > 10 ? 10 : placeholderCount} /> ); } } const mapStateToProps = ({ listing, pender, base, common }: State) => ({ posts: listing.tag.posts, prefetched: listing.tag.prefetched, prefetching: pender.pending['listing/PREFETCH_TAG_POSTS'], loading: pender.pending['listing/GET_TAG_POSTS'], width: base.windowWidth, hasEnded: listing.tag.end, selectedTag: common.tags.selected, shouldCancel: common.ssr && !common.router.altered, currentTag: listing.tag.currentTag, }); export default connect(mapStateToProps, () => ({}))(TagPostCards); import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { htmlIdGenerator } from "@elastic/eui/lib/services"; import { EuiBottomBar, EuiDragDropContext, euiDragDropReorder, EuiDraggable, EuiDroppable, EuiFlexGroup, EuiFlexItem, } from "@elastic/eui"; import CardFavorite from "components/CardFavorite"; import "./styles.css"; import { updatePosition } from "redux/actions/favorite"; export default function BottomBarFavorites() { const dispatch = useDispatch(); const [draggables, setDraggables] = useState([]); const { favorites, loading } = useSelector((state) => state.favorite); const droppableId = htmlIdGenerator()(); useEffect(() => { setDraggables(Object.keys(favorites)); }, [favorites]); const updateFavPosition = (source, destination, items) => { let start, end; if (source > destination) { start = destination; end = items.length; } else if (source < destination) { start = source; end = ++destination; } items.slice(start, end).forEach((index) => { dispatch(updatePosition(favorites[index].docRef, ++start)); }); }; const onDragEnd = ({ source, destination }) => { const lists = { [droppableId]: draggables }; const actions = { [droppableId]: setDraggables }; if (!source || !destination) { return; } const items = euiDragDropReorder( lists[destination.droppableId], source.index, destination.index ); actions[destination.droppableId](items); updateFavPosition(source.index, destination.index, items); }; return ( <> {!loading && ( <EuiBottomBar className="favorites__bottom-bar"> <EuiFlexGroup justifyContent="spaceBetween" responsive={false}> <EuiFlexItem> <EuiDragDropContext onDragEnd={onDragEnd}> <EuiDroppable className="euiFlexGroup favorites__bottom-bar-wrapper" droppableId={droppableId} direction="horizontal" spacing="none" > {draggables.map((draggable, index) => { const favorite = favorites[draggable]; return ( <EuiDraggable key={draggable} index={index} draggableId={draggable} spacing="m" disableInteractiveElementBlocking // Allows button to be drag handle > {(provided) => <CardFavorite {...favorite} />} </EuiDraggable> ); })} </EuiDroppable> </EuiDragDropContext> </EuiFlexItem> </EuiFlexGroup> </EuiBottomBar> )} </> ); } /** * Created by LeutrimNeziri on 30/03/2019. */ module.exports = { API_URL: 'http://5cdde1216f4437001467a3c8.mockapi.io/api', BREAKPOINTS: { FOUR_K: 3840, QHD: 2560, FULL_HD: 1920, HD: 1366, DVD_RIP: 720, DEFAULT: 0 }, PAGES: { HOME: 'home', LECTURE_1: { ID: 'lecture1', GETTING_STARTED: 'gettingStarted', PROJECT_SETTUP: 'projectSetup', AGILE_METHODOLOGY: 'agile', WAY_OF_WORKING: 'wayofWorking', WORKING_WITH_GIT: 'git' }, PLAYGROUND: 'playground', SUPPORT: { ID: 'support', GLOSSARY: 'glossary', RESOURCES: 'resources', PLAN_PROGRAM: 'program', TIPS_AND_TRICKS: 'tips_and_tricks' }, }, } <reponame>massa/eric-api const pug = require('pug') const emailData = require('../config/template').email const email = require('emailjs/email') const server = email.server.connect({ user: process.env.MAIL_USER, password: <PASSWORD>, host: process.env.MAIL_HOST, port: process.env.MAIL_PORT, ssl: true }) const sendMail = (options) => { const data = Object.assign({_email: emailData}, options.template.data) const mailPath = `${process.cwd()}/templates/mails/${options.template.path}.pug` const htmlstream = pug.renderFile(mailPath, data) const message = { from: '<NAME> ⚜️ 🔺 <<EMAIL>>', to: (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') ? '<EMAIL>' : (options.to), bcc: '<EMAIL>', subject: options.subject, attachment: [ {data: htmlstream, alternative: true} ] } server.send(message, (error, info) => { if (error) { console.log(JSON.stringify(error)) return {success: false, error: error} } return {success: true, info: info} }) } module.exports = { sendMail } <reponame>Juanhernandez1/market-api const { verifyGoogleSignUpToken } = require("../../../scripts/utils/jwt"); let oAuth2Verify = async (req, res, next) => { const { token } = req.body; const { success, payload } = await verifyGoogleSignUpToken(token); if (!success) { return res.status(401).json({ success, message: "El token no es valido !." }); } req.oauth2 = { avatar: payload.picture, name: payload.name, email: payload.email }; next(); }; module.exports = oAuth2Verify; <reponame>SantiagoPapa/ProjetoBEDU import React from 'react'; import LinkMenu from './LinkMenu'; import '../style/MenuNavegacao.css'; export default function MenuNavegacao (props) { return ( <div className="menu"> <h2>fixotel</h2> <nav className="nav-menu"> <ul className="menu-lista"> <LinkMenu titulo="Inicio" src="/inicio" /> <LinkMenu titulo="Tarefas e Problemas" src="/incidentes" /> {/* <LinkMenu titulo="Promoções" src="/promocoes" /> */} {/* <LinkMenu titulo="Passeios" src="/passeios" /> */} {/* <LinkMenu titulo="Cardápio" src="/cardapio" /> */} {/* <LinkMenu titulo="Informações Gerais" src="/info" /> */} <LinkMenu titulo="Sair" src="/" /> </ul> </nav> </div> ); }import axios from "axios"; const downloadFile = url => { return axios({ method: "get", url: `${url}`, responseType: "blob" //二进制流 }).then(res => { // 处理返回的文件流 console.log(res); const content = res; const blob = new Blob([content], { type: "application/vnd.ms-excel;charset=utf-8" }); var date = new Date().getFullYear() + "" + (new Date().getMonth() + 1) + "" + new Date().getDate() + "" + new Date().getHours() + "" + new Date().getMinutes() + "" + new Date().getSeconds() + "" + new Date().getMilliseconds(); const fileName = date + "." + ext; if ("download" in document.createElement("a")) { // 非IE下载 const elink = document.createElement("a"); elink.download = fileName; elink.style.display = "none"; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); // 释放URL 对象 document.body.removeChild(elink); } else { // IE10+下载 navigator.msSaveBlob(blob, fileName); } }); }; module.exports = downloadFile; /* Electron Docs v10.1.1 https://www.electronjs.org/docs/api/app#appsetuseractivity `app.setUserActivity()` */ /** * [Description] * * @return {undefined} [Description] */ const setUserActivity = function () { }; module.exports = setUserActivity; <reponame>toplan/react-hold import PropTypes from 'prop-types' import { color, width, height, cancelHold, targetProps } from '../shapes' describe("Holder's default prop types", () => { it('has "color" type', () => { expect(color).toBe(PropTypes.string) }) it('has "width" type', () => { expect(width).toBe(PropTypes.number) }) it('has "height" type', () => { expect(height).toBe(PropTypes.number) }) it('has "cancelHold" type', () => { expect(cancelHold).toBe(PropTypes.func) }) it('has "targetProps" type', () => { expect(targetProps).toBe(PropTypes.object) }) }) /** * esnext-coverage reporter plugin for Karma. * @module karma-plugin */ const EsnextCoverageReporter = require('./esnext-coverage-reporter'); /** * Main entry point exposing the reporter plugin. * @type {Object} * @property {String} reporter:esnext-coverage - Karma-specific declaration. */ module.exports = { 'reporter:esnext-coverage': ['type', EsnextCoverageReporter] }; /*eslint no-unused-vars: ["error", { "args": "none" }]*/ import DefaultLayout from '~/layouts/Default.vue'; // Default bootstrap stuff. import BootstrapVue from 'bootstrap-vue'; // Prismjs stuff. import 'gridsome-plugin-remark-prismjs-all/themes/tomorrow.css'; // Our custom CSS stuff (Including the CSS stuff ror vue-now-kit). import './assets/styles/main.scss'; // Creative Tim vue-now-kit stuff. import globalDirectives from './plugins/globalDirectives'; import globalMixins from './plugins/globalMixins'; import globalComponents from './plugins/globalComponents'; import lang from 'element-ui/lib/locale/lang/en'; import locale from 'element-ui/lib/locale'; locale.use(lang); // Font Awesome Icons import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'; import { config, library } from '@fortawesome/fontawesome-svg-core'; import { faGithub, faTwitter, faGooglePlusSquare, faDiscord } from '@fortawesome/free-brands-svg-icons'; import '@fortawesome/fontawesome-svg-core/styles.css'; config.autoAddCss = false; library.add(faGithub, faTwitter, faGooglePlusSquare, faDiscord); // Import the Auth0 configuration import { domain, clientId } from '../auth_config.json'; // Import the plugin here import { Auth0Plugin } from './plugins/auth0.js'; export default function (Vue, { router, head, isClient }) { // Install the authentication plugin here only if we are running client side. if(isClient){ Vue.use(Auth0Plugin, { domain, clientId, onRedirectCallback: appState => { router.push( appState && appState.targetUrl ? appState.targetUrl : window.location.pathname ); } }); } // Default bootstrap stuff. Vue.use(BootstrapVue); Vue.component('Layout', DefaultLayout); // Creative Tim vue-now-kit stuff. Vue.use(globalDirectives); Vue.use(globalMixins); Vue.use(globalComponents); // Font awesome stuff. Vue.component('font-awesome', FontAwesomeIcon); } <filename>src/node/vsm-store.js (function(exports) { const fs = require('fs'); const path = require('path'); const { logger, } = require('rest-bundle'); const { exec, } = require('child_process'); const { version, } = require('../../package'); const SuttaStore = require('./sutta-store'); const SoundStore = require('./sound-store'); const Playlist = require('./playlist'); const Voice = require('./voice'); const AWS = require("aws-sdk"); const PATH_VSM = path.join(__dirname, '../../local/vsm'); const MANIFEST = "manifest.json"; const tmp = require('tmp'); var suttaStore = new SuttaStore(); class VsmStore extends SoundStore { constructor(opts) { super((opts = VsmStore.options(opts))); logger.info(`VsmStore.ctor(${this.storePath})`); this.soundStore = opts.soundStore; this.lang = opts.lang || 'pli'; this.author = opts.author || 'mahasangiti'; this.voice = opts.voice; this.zip = opts.zip || 'gzip -f '; this.importMap = {}; this.s3 = opts.s3 || new AWS.S3(); } static options(opts={}) { var { storePath, storeName, soundStore, voice, } = opts; voice = voice || Voice.createVoice({ name: "aditi", usage: 'recite', languageUnknown: "pli", language: 'hi-IN', stripNumbers: true, stripQuotes: true, }); storeName = storeName || `vsm`; storePath = storePath || PATH_VSM; soundStore = soundStore || voice.soundStore; return Object.assign({}, { storePath, storeName, type: "VsmStore", soundStore, voice, }); } importGuidFiles(guid, volume) { var that = this; return new Promise((resolve, reject) => { (async function() { try { var srcStore = that.soundStore; var pathOpts = { guid, volume, }; var srcDir = path.dirname(srcStore.guidPath(pathOpts)); var dstDir = path.dirname(that.guidPath(pathOpts)); var srcFiles = path.join(srcDir, `${guid}.*`); var cmd = `cp -v ${srcFiles} ${dstDir}`; var cmdOpts = {}; var cp = exec(cmd, cmdOpts, (error, stdout, stderr) => { if (error) { reject(error); console.log(`stderr`, stderr); console.error(error.stack); return; } var files = stdout.split('\n'); files = files.reduce((acc,line) => { var parts = line.split(' -> '); parts.length === 2 && acc.push(parts[1]); return acc; }, []); resolve({ files, }); }); } catch(e) {reject(e);}})(); }); } importSpeakResult(speakResult) { var guid = speakResult.signature.guid; var result = this.importMap[guid]; if (result) { return Promise.resolve(result); } var that = this; return new Promise((resolve, reject) => { (async function() { try { var srcStore = that.soundStore; var volume = speakResult.signature.volume; var guidResult = await that.importGuidFiles(guid, volume); var importResult = Object.assign({}, speakResult); importResult.file = importResult.file .replace(srcStore.storePath, that.storePath); that.importMap[guid] = importResult; resolve(importResult); } catch(e) {reject(e);}})(); }); } speak(text, opts={}) { var { importMap, } = this; var that = this; var { sutta_uid, voice, lang, author, volume, } = opts; sutta_uid = sutta_uid || 'other'; lang = lang || that.lang; author = author || that.author; voice = voice || that.voice; volume = volume || Playlist.volumeName(sutta_uid, lang, author, voice.name); return new Promise((resolve, reject) => { (async function() { try { var speakOpts = Object.assign({ volume, lang, author, }, opts); var speakResult = await voice.speak(text, speakOpts); var result = await that.importSpeakResult(speakResult); resolve(result); }catch(e) {reject(e);}})(); }); } archiveVolume(opts={}) { var that = this; if (typeof opts === 'string') { opts = { volume: opts, } } var { volume, voice, archiveDir, archiveFile, } = opts; voice = voice || that.voice; archiveDir = archiveDir || that.storePath; archiveFile = archiveFile || volume || 'archive'; var volPath = path.join(that.storePath, volume); if (!fs.existsSync(volPath)) { return Promise.reject(new Error( `archiveVolume() no volume:${volume}`)); } return new Promise((resolve, reject) => { (async function() { try { var manifest = Object.assign({}, opts, { archived: new Date(), archiveDir, archiveFile, volume, version, voice, }); var manifestPath = path.join(that.storePath, volume, MANIFEST); fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2)); var tarPath = path.join(archiveDir, `${archiveFile}.tar`); var zip = that.zip var cmd = `tar -cf ${tarPath} ${volume} ; ${zip} ${tarPath}`; var cmdOpts = { cwd: that.storePath, }; var execResult = exec(cmd, cmdOpts, (error, stdout, stderr) => { if (error) { reject(error); console.log(`stderr`, stderr); console.error(error.stack); return; } resolve(manifest); }); } catch(e) {reject(e);} })(); }); } restoreVolume(opts={}) { var that = this; return new Promise((resolve, reject) => { (async function() { try { var { volume, voice, soundStore, archiveDir, archiveFile, clearVolume, } = opts; voice = voice || that.voice; archiveDir = archiveDir || that.storePath; archiveFile = archiveFile || volume || 'archive'; soundStore = soundStore || that.soundStore; clearVolume = clearVolume === false ? false : true; var filesDeleted = 0; var volumePath = path.join(soundStore.storePath, volume); if (clearVolume && fs.existsSync(volumePath)) { logger.info(`restoreVolume(${volume}) clearVolume`); var clearResult = await soundStore.clearVolume(volume); filesDeleted = clearResult.filesDeleted; } var zipFile = archiveFile.startsWith('/') ? archiveFile : path.join(archiveDir, archiveFile); if (!fs.existsSync(zipFile)) { var altZipFile = `${zipFile}.tar.gz`; if (!fs.existsSync(altZipFile)) { throw new Error(`VSM archive not found:${zipFile}`); } zipFile = altZipFile; } var cwd = soundStore.storePath; var cmd = `gunzip -ck ${zipFile} | tar -x`; var cmdOpts = { cwd, }; var execResult = exec(cmd, cmdOpts, (error, stdout, stderr) => { if (error) { reject(error); console.log(`stderr`, stderr); console.error(error.stack); return; } resolve({ filesDeleted, }); }); } catch(e) { reject(e);} })(); }); } importSutta(sutta, opts = {}) { var { lang, author, voice, volume, } = opts; var sutta_uid = sutta.sutta_uid; lang = lang || this.lang; author = author || this.author; voice = voice || this.voice; volume = volume || Playlist.volumeName(sutta_uid, lang, author, voice.name); var that = this; return new Promise((resolve, reject) => { (async function() { try { var result = { lang, author, voice, volume, sutta_uid, }; var guids = []; for (var i = 0; i<sutta.segments.length; i++) { var seg = sutta.segments[i]; var text = seg[lang]; var speakResult = await that.speak(text, { volume, }); guids.push(speakResult.signature.guid); } resolve({ sutta_uid, volume, guids, }); } catch(e) {reject(e);} })(); }); } } module.exports = exports.VsmStore = VsmStore; })(typeof exports === "object" ? exports : (exports = {})); <gh_stars>10-100 module.exports=/[\u0100-\u017F]/import classNames from 'classnames'; import {Confirm, Table} from 'reactjs-components'; import {Link} from 'react-router'; import mixin from 'reactjs-mixin'; /* eslint-disable no-unused-vars */ import React from 'react'; /* eslint-enable no-unused-vars */ import {StoreMixin} from 'mesosphere-shared-reactjs'; import AlertPanel from '../../components/AlertPanel'; import CollapsingString from '../../components/CollapsingString'; import DCOSStore from '../../stores/DCOSStore'; import defaultServiceImage from '../../../img/services/icon-service-default-small@2x.png'; import Icon from '../../components/Icon'; import MarathonActions from '../../events/MarathonActions'; import NestedServiceLinks from '../../components/NestedServiceLinks'; import ResourceTableUtil from '../../utils/ResourceTableUtil'; import StatusBar from '../../components/StatusBar'; import StringUtil from '../../utils/StringUtil'; import TimeAgo from '../../components/TimeAgo'; const columnHeading = ResourceTableUtil.renderHeading({ id: 'AFFECTED SERVICES', startTime: 'STARTED', location: 'LOCATION', status: 'STATUS', action: '' }); const COLLAPSING_COLUMNS = ['location', 'startTime', 'action']; const METHODS_TO_BIND = [ 'renderAffectedServices', 'renderAffectedServicesList', 'renderLocation', 'renderStartTime', 'renderStatus', 'renderAction', 'handleRollbackClick', 'handleRollbackCancel', 'handleRollbackConfirm', 'onMarathonStoreDeploymentRollbackSuccess', 'onMarathonStoreDeploymentRollbackError' ]; // collapsing columns are tightly coupled to the left-align caret property; // this wrapper allows ordinary columns to collapse. function columnClassNameGetter(prop, sortBy, row) { let classSet = ResourceTableUtil.getClassName(prop, sortBy, row); if (COLLAPSING_COLUMNS.includes(prop)) { return classNames(classSet, 'hidden-mini'); } return classSet; } class DeploymentsTab extends mixin(StoreMixin) { constructor() { super(...arguments); this.state = {}; this.store_listeners = [ {name: 'dcos', events: ['change']}, { name: 'marathon', events: ['deploymentRollbackSuccess', 'deploymentRollbackError'] } ]; METHODS_TO_BIND.forEach((method) => { this[method] = this[method].bind(this); }, this); } onMarathonStoreDeploymentRollbackSuccess(data) { let {deploymentToRollback} = this.state; if (deploymentToRollback != null && deploymentToRollback.getId() === data.originalDeploymentID) { this.setState({ awaitingRevertDeploymentResponse: false, deploymentToRollback: null, deploymentRollbackError: null }); } } onMarathonStoreDeploymentRollbackError(data) { let {deploymentToRollback} = this.state; if (deploymentToRollback != null && deploymentToRollback.getId() === data.originalDeploymentID) { this.setState({ awaitingRevertDeploymentResponse: false, deploymentRollbackError: data.error }); } } renderAffectedServices(prop, deployment) { return ( <dl className="deployment-services-list flush-top flush-bottom tree-list"> <dt className="deployment-id text-uppercase"> <CollapsingString string={deployment.getId()} /> </dt> {this.renderAffectedServicesList(deployment.getAffectedServices())} {this.renderStaleServicesList(deployment.getStaleServiceIds())} </dl> ); } renderStaleServicesList(serviceIds) { if (serviceIds == null) { return; } return serviceIds.map(function (serviceId) { return ( <dd key={`stale_${serviceId}`}> <span className="icon icon-small icon-image-container icon-app-container deployment-service-icon"> <img src={defaultServiceImage} /> </span> {serviceId} </dd> ); }); } renderAffectedServicesList(services) { return services.map(function (service) { const id = encodeURIComponent(service.getId()); const image = service.getImages()['icon-small']; return ( <dd key={`service_${id}`}> <Link to="services-detail" params={{id}} className="deployment-service-name"> <span className="icon icon-small icon-image-container icon-app-container deployment-service-icon"> <img src={image} /> </span> {service.getName()} </Link> </dd> ); }); } renderLocation(prop, deployment) { const services = deployment.getAffectedServices(); const items = services.map(function (service, index) { return ( <li key={index}> <NestedServiceLinks serviceID={service.getId()} className="deployment-breadcrumb" majorLinkClassName="deployment-breadcrumb-service-id" minorLinkWrapperClassName="deployment-breadcrumb-crumb" /> </li> ); }); return ( <ol className="deployment-location-list list-unstyled flush-bottom"> {items} </ol> ); } renderStartTime(prop, deployment) { return ( <TimeAgo className="deployment-start-time" time={deployment.getStartTime()} /> ); } renderStatus(prop, deployment) { const currentStep = deployment.getCurrentStep(); const totalSteps = deployment.getTotalSteps(); const title = `Step ${currentStep} of ${totalSteps}`; const statusBar = this.renderStatusBar(currentStep, totalSteps); const services = deployment.getAffectedServices(); let currentActions = {}; if (deployment.currentActions && deployment.currentActions.length > 0) { currentActions = deployment.currentActions.reduce(function (memo, action) { memo[action.app] = action.action; return memo; }, {}); } const items = services.map(function (service, index) { let statusText = service.getStatus(); if (currentActions[service.id] != null) { statusText += ` (${currentActions[service.id]})`; } return ( <li key={index}> {statusText} </li> ); }); return ( <div> {statusBar} <span className="deployment-step">{title}</span> <ol className="deployment-status-list list-unstyled flush-bottom">{items}</ol> </div> ); } renderStatusBar(currentStep, totalSteps) { let data = [ {className: 'color-4', value: currentStep - 1}, {className: 'staged', value: 1}, {className: '', value: totalSteps - currentStep} ]; return ( <StatusBar className="progress-bar flex-box status-bar deployment-status-bar" data={data} /> ); } renderAction(prop, deployment) { if (deployment != null) { let linkText = 'Rollback'; if (deployment.isStarting()) { linkText = linkText + ' & Remove'; } return ( <a className="deployment-rollback button button-link button-danger table-display-on-row-hover" onClick={this.handleRollbackClick.bind(null, deployment)}> {linkText} </a> ); } } handleRollbackClick(deployment) { this.setState({deploymentToRollback: deployment}); } handleRollbackCancel() { this.setState({ awaitingRevertDeploymentResponse: false, deploymentToRollback: null, deploymentRollbackError: null }); } handleRollbackConfirm() { let {deploymentToRollback} = this.state; if (deploymentToRollback != null) { this.setState({awaitingRevertDeploymentResponse: true}); MarathonActions.revertDeployment(deploymentToRollback.getId()); } } getColumns() { return [ { className: columnClassNameGetter, heading: columnHeading, prop: 'id', render: this.renderAffectedServices }, { className: columnClassNameGetter, heading: columnHeading, prop: 'location', render: this.renderLocation }, { className: columnClassNameGetter, heading: columnHeading, prop: 'startTime', render: this.renderStartTime }, { className: columnClassNameGetter, heading: columnHeading, prop: 'status', render: this.renderStatus }, { className: columnClassNameGetter, heading: columnHeading, prop: 'action', render: this.renderAction } ]; } getColGroup() { return ( <colgroup> <col style={{width: '300px'}} /> <col className="hidden-mini" /> <col className="hidden-mini" style={{width: '120px'}} /> <col style={{width: '240px'}} /> <col className="hidden-mini" style={{width: '160px'}} /> </colgroup> ); } renderEmpty() { return ( <AlertPanel title="No Deployments" icon={<Icon id="services" color="white" size="jumbo" />}> <p className="flush">Active deployments will be shown here.</p> </AlertPanel> ); } renderLoading() { return ( <div className="container container-fluid container-pod text-align-center vertical-center inverse"> <div className="row"> <div className="ball-scale"> <div /> </div> </div> </div> ); } renderPopulated(deploymentsItems) { let deploymentsCount = deploymentsItems.length; let deploymentsLabel = StringUtil.pluralize('Deployment', deploymentsCount); return ( <div> <h4 className="inverse"> {deploymentsCount} Active {deploymentsLabel} </h4> <Table className="table inverse table-borderless-outer table-borderless-inner-columns flush-bottom deployments-table" columns={this.getColumns()} colGroup={this.getColGroup()} data={deploymentsItems.slice()} /> {this.renderRollbackModal()} </div> ); } renderRollbackModal() { let { awaitingRevertDeploymentResponse, deploymentToRollback, deploymentRollbackError } = this.state; if (deploymentToRollback != null) { return ( <Confirm closeByBackdropClick={true} disabled={!!awaitingRevertDeploymentResponse} footerContainerClass="container container-pod container-pod-short container-pod-fluid flush-top flush-bottom" onClose={this.handleRollbackCancel} leftButtonCallback={this.handleRollbackCancel} leftButtonText="Cancel" rightButtonClassName="button button-danger" rightButtonCallback={this.handleRollbackConfirm} rightButtonText="Continue Rollback"> <div className="container-pod container-pod-short text-align-center"> <h3 className="flush-top">You're About To Rollback The Deployment</h3> <p>{this.getRollbackModalText(deploymentToRollback)}</p> {this.renderRollbackError(deploymentRollbackError)} </div> </Confirm> ); } } getRollbackModalText(deploymentToRollback) { let serviceNames = deploymentToRollback.getAffectedServices() .map(function (service) { return StringUtil.capitalize(service.getName()); }); let listOfServiceNames = StringUtil.humanizeArray(serviceNames); let serviceCount = serviceNames.length; let service = StringUtil.pluralize('service', serviceCount); let its = (serviceCount === 1) ? 'its' : 'their'; let version = StringUtil.pluralize('version', serviceCount); if (deploymentToRollback.isStarting()) { return `This will stop the current deployment of ${listOfServiceNames} and start a new deployment to remove the affected ${service}.`; } return `This will stop the current deployment of ${listOfServiceNames} and start a new deployment to revert the affected ${service} to ${its} previous ${version}.`; } renderRollbackError(deploymentRollbackError) { if (deploymentRollbackError != null) { return ( <p className="text-error-state flush-bottom"> {deploymentRollbackError} </p> ); } } render() { let deployments = DCOSStore.deploymentsList.getItems(); let loading = !DCOSStore.dataProcessed; if (loading) { return this.renderLoading(); } if (deployments.length === 0) { return this.renderEmpty(); } else { return this.renderPopulated(deployments); } } } module.exports = DeploymentsTab; <gh_stars>0 let timestamp = Date.now(); // The current time as a timestamp (a number). let now = new Date(); // The current time as a Date object. let ms = now.getTime(); // Convert to a millisecond timestamp. let iso = now.toISOString(); console.log(timestamp); console.log(now); console.log(ms); console.log(iso.split("T")[0]); console.log(iso.substring(0, 10)); let euro = "€"; let love = "❤"; console.log(euro); console.log(love); console.log("one\ long\ line"); console.log(`the newline character at the end of this line is included literally in this string`); let s = "Hello, world"; // Start with some text. // Obtaining portions of a string console.log(s.substring(1, 4)); // => "ell": the 2nd, 3rd, and 4th characters. console.log(s.slice(1, 4)); // => "ell": same thing console.log(s.slice(-3)); // => "rld": last 3 characters console.log(s.split(", ")); console.log(s[s.length - 1]); let name = "Bill"; let greeting = `Hello ${name}.`; console.log(greeting); console.log(!!undefined); console.log(!!null); console.log(!!0); console.log(!!-0); console.log(!!NaN); console.log(!!""); let o = { x: 1 }; // Start with an object o.x = 2; // Mutate it by changing the value of a property o.y = 3; if (o) console.log("o is defined", o); else console.log("o is undefined"); console.log(typeof 42); console.log(typeof ""); console.log(typeof {}); console.log(typeof []); let a = [1, 2, 3]; // Arrays are also mutable a[0] = 0; // Change the value of an array element a[3] = 4; console.log(a); a = ["a", "b", "c"]; // An array we want to copy let b = []; // A distinct array we'll copy into for (let i = 0; i < a.length; i++) { // For each index of a[] b[i] = a[i]; // Copy an element of a into b } let c = Array.from(b); console.log(a); console.log(b); console.log(c); let d = a.map((x) => x); console.log(d); let e = []; a.forEach((x) => e.push(x)); console.log(e); console.log({ x: 1, y: 2 }.toString()); console.log(JSON.stringify({ x: 1, y: 2 })); console.log(typeof JSON.stringify({ x: 1, y: 2 })); let obj = { x: 1, y: 2 }; let ostr = JSON.stringify(obj); console.log(ostr); let obj1 = JSON.parse(ostr); console.log(obj === obj1); console.log(obj.x === obj1.x && obj.y === obj1.y); console.log(JSON.stringify(obj1)); let [x, y] = [1, 2]; // Same as let x=1, y=2 console.log(x, y); [x, y] = [x + 1, y + 1]; // Same as x = x + 1, y = y + 1 console.log(x, y); [x, y] = [y, x]; // Swap the value of the two variables console.log(x, y); let obj2 = { x: 1, y: 2 }; // The object we'll loop over console.log(JSON.stringify(Object.entries(obj2))); let obj3 = {}; for (const [name, value] of Object.entries(obj2)) { console.log(name, value); // Prints "x 1" and "y 2" obj3[name] = value; } console.log("obj3=", obj3); let obj4 = Object.entries(obj2).reduce((acc, cur) => { acc[cur[0]] = cur[1]; return acc; }, {}); console.log(obj4); [x, ...y] = [1, 2, 3, 4]; console.log(x); console.log(y); console.log(...[2, 3, 4]); let sp1 = [...[2, 3, 4]]; console.log(sp1); sp1 = { ...{ x: 1, y: 2 } }; console.log(sp1); let [first, ...rest] = "Hello"; console.log(first, rest); let transparent = { r: 0.1, g: 0.2, b: 0.3, a: 1.0 }; // A RGBA color let {r,g,b} = transparent; let selObj = {r,g,b}; console.log("selObj=",selObj); selObj = (({ r,g,b }) => ({ r,g,b }))(transparent); console.log("selObj=",selObj); let { r: r, g: g, b: b1 } = transparent; // r == 0.0; g == 0.0; b == 0.0 console.log(r, g, b1); x = 1; y = 2; console.log(x, y); obj = { x, y }; console.log(obj); obj = { x: x, y: y }; console.log(obj); const { sin, cos, tan } = Math; console.log(Math.sin(0.1)); console.log(sin(0.1)); let points = [ { x: 1, y: 2 }, { x: 3, y: 4 }, ]; // An array of two point objects let [{ x: x1, y: y1 }, { x: x2, y: y2 }] = points; console.log(x1, y1, x2, y2); <gh_stars>0 import { Meteor } from "meteor/meteor"; import { Mongo } from "meteor/mongo"; import { check } from "meteor/check"; export const UserData = new Mongo.Collection("UserData"); if (Meteor.isServer) { // This code only runs on the server Meteor.publish('UserData', function userDataPublication() { //return UserData.find(); if (!this.userId) { return this.ready(); } return UserData.find({ userId: this.userId }, { fields: UserData.publicFields }); }); } Meteor.methods({ "UserData.createUserData"() { UserData.insert({ type: "USER", userId: this.userId, coins: 1000, InBet: 0 }); }, "UserData.getAll"() { let all = UserData.find({}).fetch(); console.log("All user data: "); console.log(all); //Lo Anterior funciona return all; }, "UserData.getData"(userId) { check(userId, String); let res = UserData.find( { userId: userId } ).fetch(); return res; }, "UserData.updateCoins"(aUserId, e1) { UserData.update( { userId: aUserId }, { $inc: { coins: e1 } } ); }, "UserData.removeBetCoins"(aUserId) { UserData.update( { userId: aUserId }, { $set: { InBet: 0 } } ); }, "UserData.addCoins"(aUserId, numCoins) { UserData.update( { userId: aUserId }, { $inc: { coins: numCoins } } ); }, "UserData.removeNewBetCoins"(numCoins) { UserData.update( { userId: this.userId }, { $inc: { coins: -numCoins, InBet: numCoins } } ); } }); <reponame>dmmdjs/dmmd.js "use strict"; // Imports const bColor = require("../utils/bColor.js"); const parse = require("../utils/parse.js"); /** * Creates a color from rgb value * @param {string} s String * @param {number} r Red * @param {number} g Green * @param {number} b Blue * @param {boolean} bg Background mode * @returns {string} */ function rgb(s, r, g, b, bg) { let { r: pr, g: pg, b: pb } = parse("rgb", r, g, b); return bColor(`38;2;${pr};${pg};${pb}`, `48;2;${pr};${pg};${pb}`, s, bg); }; // Exports module.exports = rgb;import React, {PropTypes} from 'react'; class DirectionIcon extends React.Component { constructor(props, context) { super(props, context); } calculateClass(angle) { let calculatedClass = "wi wi-wind "; calculatedClass += "from-" + Math.round(angle) + "-deg"; return calculatedClass; } render () { const angle = this.props.angle; let calculatedClass = this.calculateClass(angle); return ( <i className={calculatedClass}></i> ); } } DirectionIcon.propTypes = { angle: PropTypes.number.isRequired }; export default DirectionIcon; var saml2 = require('saml2-js'); var fs = require('fs'); var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true })); // Create service provider var sp_options = { entity_id: "https://sp.example.com/metadata.xml", private_key: fs.readFileSync("key-file.pem").toString(), certificate: fs.readFileSync("cert-file.crt").toString(), assert_endpoint: "https://sp.example.com/assert" }; var sp = new saml2.ServiceProvider(sp_options); // Create identity provider var idp_options = { sso_login_url: "https://idp.example.com/login", sso_logout_url: "https://idp.example.com/logout", certificates: [fs.readFileSync("cert-file1.crt").toString(), fs.readFileSync("cert-file2.crt").toString()] }; var idp = new saml2.IdentityProvider(idp_options); // ------ Define express endpoints ------ // Endpoint to retrieve metadata app.get("/metadata.xml", function(req, res) { res.type('application/xml'); res.send(sp.create_metadata()); }); // Starting point for login app.get("/login", function(req, res) { sp.create_login_request_url(idp, {}, function(err, login_url, request_id) { if (err != null) return res.send(500); res.redirect(login_url); }); }); // Assert endpoint for when login completes app.post("/assert", function(req, res) { var options = {request_body: req.body}; sp.post_assert(idp, options, function(err, saml_response) { if (err != null) return res.send(500); // Save name_id and session_index for logout // Note: In practice these should be saved in the user session, not globally. name_id = saml_response.user.name_id; session_index = saml_response.user.session_index; res.send("Hello #{saml_response.user.name_id}!"); }); }); // Starting point for logout app.get("/logout", function(req, res) { var options = { name_id: name_id, session_index: session_index }; sp.create_logout_request_url(idp, options, function(err, logout_url) { if (err != null) return res.send(500); res.redirect(logout_url); }); }); app.listen(3000); <filename>test/chunking-form/samples/improved-dynamic-chunks/dynamic-import-dynamic/_expected/cjs/generated-dynamic1.js<gh_stars>1000+ 'use strict'; const value = 'shared'; console.log('dynamic1', value); Promise.resolve().then(function () { return require('./generated-dynamic2.js'); }); exports.value = value; // @flow function hadnleMatch(matched: string): string { return matched[0] + '-' + matched[1].toLowerCase(); } const cached = {}; // converts `fooBar` to `foo-bar`. export default function hyphenize(str: string): string { if (cached.hasOwnProperty(str)) { return cached[str]; } const result = str.replace(/[a-z][A-Z]/g, hadnleMatch); cached[str] = result; return result; } 'use babel'; import GhcrtaView from './ghcrta-view'; import GhcrtaDir from './ghcrta-modal-dir'; import { CompositeDisposable } from 'atom'; export default { subscriptions: null, activate(state) { console.log(atom.config.get('ghcrta.token')) /*atom.config.set('ghcrta.key', 'otap') console.log(atom.config.get('ghcrta.key'))*/ this.modalPanel = atom.workspace.addModalPanel({ item: new GhcrtaDir, visible: false }); // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable this.subscriptions = new CompositeDisposable( atom.workspace.addOpener(uri => { if (uri === 'atom://ghcrta') { if(!this.credentials) this.credentials = new GhcrtaView() return this.credentials; } }), ); // Register command that toggles this view this.subscriptions.add(atom.commands.add('atom-workspace', { 'ghcrta:toggle': () => this.toggle(), 'ghcrta:dir': () => this.toggleModalDir() })); }, deactivate() { this.subscriptions.dispose(); }, deserializeGhcrtaView(serialized){ this.activate(serialized) atom.workspace.toggle('atom://ghcrta'); }, toggle() { atom.workspace.toggle('atom://ghcrta'); }, toggleModalDir(){ return ( this.modalPanel.isVisible() ? this.modalPanel.hide() : this.modalPanel.show() ); } }; var global = require('../internals/global'); var trim = require('../internals/string-trim').trim; var whitespaces = require('../internals/whitespaces'); var $parseFloat = global.parseFloat; var FORCED = 1 / $parseFloat(whitespaces + '-0') !== -Infinity; // `parseFloat` method // https://tc39.es/ecma262/#sec-parsefloat-string module.exports = FORCED ? function parseFloat(string) { var trimmedString = trim(String(string)); var result = $parseFloat(trimmedString); return result === 0 && trimmedString.charAt(0) == '-' ? -0 : result; } : $parseFloat; <reponame>Benjaminshafa/blue-cart<gh_stars>0 // for configuring web server on express. const express = require('express') var responseTime = require('response-time') const app = express() const port = 3000; app.use(express.json()); app.use(express.urlencoded({extended: true})); require('dotenv').config(); // for configuring mongoDB connection const MongoClient = require('mongodb').MongoClient; const uri = "mongodb+srv://"+process.env["MONGO_DB_USERNAME"]+":"+process.env["MONGO_DB_PASSWORD"]+"@"+process.env["MONGO_DB_CLUSTER_ADDRESS"]+"?retryWrites=true&w=majority"; const client = new MongoClient(uri, { useNewUrlParser: true }); var mongodbConnection = null; client.connect(function(err,connection){ if(err){ console.log(err); } else{ mongodbConnection = connection.db(); app.listen(port, () => console.log(`Example app listening on port ${port}!`)) } }); var controller = require('./Controller'); app.post('/product',function(req,res){ controller.insert_Product(mongodbConnection,req.body,function(mongoItem){ if(mongoItem.insertedCount < 1){ return res.status(500).send({"message": "failed!"}); } else{ return res.status(200).send({}); } }) }); app.get('/product',function(req,res){ controller.retrieve_Product_By_Id(mongodbConnection,req.header.id,function(product_Info){ if(!product_Info){ return res.status(404).send({"message": "not found!"}); } else{ return res.status(200).send({productInfo: product_Info}); } }) }); <filename>cli/run-docs.js<gh_stars>0 const { npm, npx } = require('./run-utils'); const { exit } = require('process'); const jsdoc = () => npx('jsdoc', '--configure', 'jsdoc.json', 'lib' ); if (require.main === module) { npm('install') .then(() => require('./run-clean')('docs')) .then(jsdoc).catch(exit); } module.exports = jsdoc; import React from 'react'; import Link from 'gatsby-link'; import BlueButton from '../../components/BlueButton/BlueButton'; import Coverflow from 'react-coverflow'; import './About.scss'; import mattCut from '../../images/matt-header2-noleg.png'; import mattAbout4 from '../../images/mat-4.jpg'; import mattAbout2 from '../../images/matt-about-2.jpg'; import mattAbout3 from '../../images/matt-about-3.jpg'; import mattAbout1 from '../../images/matt-about-1.jpg'; const Images = () => ( <Coverflow width="960" height="500" displayQuantityOfSide={2} navigation={false} enableScroll={true} clickable={true} active={0} > <div onClick={() => fn()} onKeyDown={() => fn()} role="menuitem" tabIndex="0" > <img src="image/path" alt="title or description" style={{ display: 'block', width: '100%', }} /> </div> <img src={mattAbout1} alt="title or description" data-action="http://andyyou.github.io/react-coverflow/" /> <img src={mattAbout2} alt="title or description" data-action="http://andyyou.github.io/react-coverflow/" /> </Coverflow> ); export default Images; <gh_stars>0 angular.module('AppClientes',['ngRoute','angularUtils.directives.dirPagination','Methods','ngCookies']) .controller('Clientes',function($scope,$http,$location,$methodsService){ //Variables $scope.currentPage = 1; // Página actual, para paginación $scope.pageSize = 5; // Tamaño de la página, para paginación. $scope.mostrarbuscando = true; $scope.mostrarcontent = false; $scope.showfilter = false; $scope.clitr = 0; //Funciones $scope.AplicarBiotest = function(id) { bootbox.confirm("Desea aplicar el biotest a este cliente?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/BiotestMenu').search({Cliente:id}); }); }//if }); }//AplicarBiotest $scope.RutinaCliente = function(id) { bootbox.confirm("Desea ir al apartado de rutinas para clientes?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/ClientesRutina').search({id:id}); }); }//if }); }//RutinaCliente $scope.Selecciontr = function(tr) { //Verificando que no se le hizo click al mismo tr if(tr.cli.id == $scope.clitr) { //Si es el mismo tr se le asigna un 0. $scope.clitr = 0; idtr = "#table"+tr.cli.id; $(idtr).removeClass("bg-blue"); console.log($scope.clitr); }//if else { $("tr").removeClass("bg-blue"); $scope.clitr = tr.cli.id; idtr = "#table"+tr.cli.id; $(idtr).addClass("bg-blue"); console.log($scope.clitr); } //añadiendo la clase al tr }//Selecciontr $scope.Agregar = function() { bootbox.confirm("Desea Agregar un Cliente?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/AgregarCliente').search({}); }); }//if }); }//Agregar $scope.Editar = function() { if($scope.clitr!=0) { bootbox.confirm("Desea Editar este Cliente?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/EditarCliente').search({cliente:$scope.clitr}); }); }//if }); }//if else{$methodsService.alerta(2,"Favor de seleccionar un Cliente");} }//Agregar $scope.Eliminar = function() { if($scope.clitr!=0) { bootbox.confirm("Desea Editar este Cliente?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ params = $methodsService.Json("EliminarCliente",$scope.clitr); //Enviando por ajax la peetición var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; exitocli = data.exitocli; switch(true) { case exito==1 && exitocli==1: $scope.clientes = data.clientes; $methodsService.alerta(1,"Cliente Eliminado"); break; case exito!=1 && exitocli!=1: $methodsService.alerta(2,"algo falló, disculpe las molestias"); break; }//switch }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }); }//if }); }//if else{$methodsService.alerta(2,"Favor de seleccionar un Cliente");} }//Eliminar $scope.Filtrar = function() { params = $methodsService.Json("FiltrarClientes",$scope.cliente.opcion); //Filtrando los clientes. var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; if(exito==1) { $scope.clientes = data.clientes; $methodsService.alerta(1,"Clientes Filtrados!"); }//if else{$methodsService.alerta(2,"algo falló, disculpe las molestias");} }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }//Filtrar $scope.form = function(cliente) { bootbox.confirm("Desea realizar el formulario a este cliente?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/Formulario').search({cliente:cliente}); }); }//if }); } //Buscando los clientes //Buscando las pruebas por la número 1, condición física params = $methodsService.Json("Clientes",1); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; exitoent = data.exito; switch(true) { case exito==1 && exitoent==1: $scope.clientes = data.clientes; $scope.entrenadores = data.entrenadores; $scope.mostrarbuscando = false; $scope.mostrarcontent = true; console.log($scope.entrenadores); break; case exito!=1 && exitoent!=1: $methodsService.alerta(2,"algo falló, disculpe las molestias"); break; }//switch if(exito==1) { }//if else{$methodsService.alerta(2,"algo falló, disculpe las molestias");} }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); })//Clientes .controller('ClientesAgregar',function($scope,$http,$location,$methodsService){ //Generando los datos para el formulario //Días $scope.dias = $methodsService.dias(); //meses $scope.meses =$methodsService.meses(); //años $scope.years = $methodsService.years(); //Variable para desactivar el botón de agregar $scope.btnen = true; //funciones $scope.Agregar = function() { //verificando el tipo de cuerpo if($scope.cliente.id_cuerpo== undefined) { bootbox.confirm("Favor de elegir un tipo de cuerpo", function(result) {}); //bootbox } else { bootbox.confirm("Desea Agregar un tipo de rutina?", function(result) { console.log(result); if(result==true) { $scope.btnen = false; //Mandando la petición AJAX al controller. $scope.cliente.Accion = "AgregarCliente"; params = JSON.stringify($scope.cliente); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; if(exito==1) { $methodsService.alerta(1,"Cliente Agregado!"); $scope.cliente = {}; $scope.btnen = true; }else{$methodsService.alerta(2,"algo falló, disculpe las molestias");} }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }//if });//botbox }//else }//Agregar $scope.modal = function() { $("#ModalCuerpo").modal("show"); }//modal $scope.Redirigir = function(direccion) { $methodsService.Redirigir(direccion); }//Redirigir }) .controller('ClientesEditar',function($scope,$http,$location,$methodsService,$routeParams){ //Variables //Días $scope.dias = $methodsService.dias(); //meses $scope.meses =$methodsService.meses(); //años $scope.years = $methodsService.years(); //Variable para desactivar el botón de agregar $scope.btnen = true; //Funciones $scope.modal = function() { $("#ModalCuerpo").modal("show"); }//modal $scope.Editar = function() { bootbox.confirm("Desea Editar este cliente?", function(result) { console.log(result); if(result==true) { $scope.btnen = false; $scope.cliente.Accion = "Editarcliente"; params = JSON.stringify($scope.cliente); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; if(exito==1) { $methodsService.alerta(1,"Cliente Editado"); $scope.btnen = true; }else{$methodsService.alerta(2,"algo falló, disculpe las molestias");} }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }//if });//bootbox }//Editar $scope.Redirigir = function(direccion) { $methodsService.Redirigir(direccion); }//Redirigir $scope.id = $routeParams.cliente; params = $methodsService.Json("InfoCliente",$scope.id); //Mandando por ajax el ejercicio a eliminar var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; if(exito==1) { $scope.cliente = data.cliente; console.log($scope.cliente); }//if else{$methodsService.alerta(2,"algo falló, disculpe las molestias");} }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); })//ClientesEditar .controller('formcontroller',function($scope,$http,$location,$methodsService,$routeParams,respservice,$cookies){ //Variables $scope.cliente = $routeParams.cliente; params = $methodsService.Json("InfoFormulario",$scope.cliente); $scope.mostrarbuscando = true; $scope.mostrarcontent = false; //Mandando por ajax el ejercicio a eliminar var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.respuestas; if(exito!="Error") { $scope.resp = data.respuestas; console.log($scope.resp); $scope.mostrarbuscando = false; $scope.mostrarcontent = true; }//if else{$methodsService.alerta(2,"algo falló, disculpe las molestias");} }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); $scope.SiguienteForm = function() { bootbox.confirm("Desea pasar al siguiente formulario?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ var resps = JSON.stringify($scope.resp); $cookies.put('resp', resps) $location.path('/Formulario2').search({}); });//apply } }); }//SiguienteForm $scope.Redirigir = function(direccion) { $methodsService.Redirigir(direccion); }//Redirigir })//formcontroller .controller('formcontroller2',function($scope,$http,$location,$methodsService,$routeParams,respservice,$cookies){ $scope.resp = JSON.parse($cookies.get('resp')); console.log($scope.resp); //funciones $scope.Redirigir = function(direccion) { $methodsService.Redirigir(direccion); }//Redirigir $scope.RegistrarForm = function() { bootbox.confirm("Desea pasar al siguiente formulario?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $scope.resp.Accion = "RegistrarForm"; //Enviadno los datos por ajax. params = JSON.stringify($scope.resp); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; if(exito==1) { $methodsService.alerta(1,"Datos Guardados!"); $cookies.remove("resp"); }//if else { $methodsService.alerta(2,"algo falló, disculpe las molestias"); } }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); });//apply }//if });//botbox }//RegistrarForm }) .controller('RutinaClientes',function($scope,$http,$location,$methodsService,$routeParams){ $scope.id_cliente = $routeParams.id; $params = $methodsService.Json("InfoClienteRutinas",$scope.id_cliente); $scope.currentPage = 1; // Página actual, para paginación $scope.pageSize = 5; // Tamaño de la página, para paginación. //Funciones $scope.CrearRutina = function(id) { bootbox.confirm("Desea crear una rutina a este cliente?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/Rutinas_Registrar').search({Cliente:$scope.id_cliente}); });//apply }//if });//botbox }//CrearRutina $scope.InfoRutina = function(id) { bootbox.confirm("Desea ver la rutina de este cliente?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ var params = $methodsService.Json("ObtenerRutinaPorCliente",$scope.id_cliente); var url = 'modulos/Biotest/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { rutina = data.rutina; $location.path('/RutinaOrdenC').search({Rut:rutina,Cliente:$scope.id_cliente}); }) .error(function(data, status, headers, config){$methodsService.alerta(2,"algo falló, disculpe las molestias");}); });//apply }//if });//botbox }//InfoRutina $scope.RedirigirRutina = function(id) { bootbox.confirm("Desea asignar una rutina a este cliente?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/RutinasAsignar').search({id:id}); });//apply }//if });//botbox }//RedirigirRutina var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; if(exito==1) { $scope.datos = data.resultado; }//if }) .error(function(data, status, headers, config){$methodsService.alerta(2,"algo falló, disculpe las molestias");}); })//RutinaClientes .controller('AsignarRutinas',function($scope,$http,$location,$methodsService,$routeParams){ $scope.currentPage = 1; // Página actual, para paginación $scope.pageSize = 5; // Tamaño de la página, para paginación. $scope.id = $routeParams.id; $scope.showfilter = false; $scope.disablebtn = false; $scope.rutina = {entrenador:"",tipo_rutina:"",genero:"",Accion:""}; $scope.mostrarbuscando = false; $scope.mostrarcontent = true; // Verificando que el cliente no tenga rutnia asignada. //Buscando las rutinas params = $methodsService.Json("ExisteRutinaCliente",$scope.id); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { cantidad = data.cantidad; if(cantidad>0) { pagina = 1; }//if else{pagina = 0;} $scope.obtenerdir(pagina); console.log($scope.url); }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); $scope.FiltrarRutinas = function() { $scope.rutina.Accion = "FiltrarRutinas"; params = JSON.stringify($scope.rutina); $scope.disablebtn = true; var url = 'modulos/Rutinas/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { $scope.disablebtn = false; exito = data.exito; if(exito==1) { cantidad = data.cantidad; if(cantidad>0) { $methodsService.alerta(1,"Rutinas Filtradas"); $scope.rutinas = data.rutinas; }//if else{$methodsService.alerta(2,"No existen rutinas con estos criterios");} } else { $methodsService.alerta(2,"algo falló, disculpe las molestias"); } }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }//FiltrarRutinas $scope.CategoriasporEnt = function() { if($scope.rutina.entrenador!=undefined) { //Buscando las catgegorias params = $methodsService.Json("BuscarCategoriasPorEntrenador",$scope.rutina.entrenador); var url = 'modulos/Rutinas/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; exitog = data.exitog; if(exito==1) { $scope.tipos_rut = data.tipos_rut; $scope.generos = data.generos; }//if }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }//if }//CategoriasporEnt $scope.AsignarRutina = function(id) { bootbox.confirm("Desea asignar la rutina a este cliente?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $scope.rutina.Accion = "AsignarRutinaCliente"; $scope.mostrarbuscando = true; $scope.mostrarcontent = false; $scope.rutina.Cliente = $scope.id; $scope.rutina.id_rutina = id; console.log($scope.rutina); params = JSON.stringify($scope.rutina); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; if(exito==1) { var id_rutina = data.id_rutinacliente; $location.path('/RutinaOrdenC').search({Rut:id_rutina,Cliente:$scope.id}); }//if }) .error(function(data, status, headers, config){$methodsService.alerta(2,"algo falló, disculpe las molestias");}); }); }//if }); }//AsignarRutina $scope.ContinuarR = function() { bootbox.confirm("Desea eliminar la rutina del cliente?.", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ params = $methodsService.Json("DesactivarRutina",$scope.id); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; if(exito==1) { $location.path('/ClientesRutina').search({id:$scope.id}); }//if }) .error(function(data, status, headers, config){$methodsService.alerta(2,"algo falló, disculpe las molestias");}); }); }//if }); }//ContinuarR $scope.CancelarR = function() { bootbox.confirm("Desea cancelar la operación?.", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/Clientes').search({}); }); }//if }); }//CancelarR $scope.obtenerdir = function(pagina) { var direccion=""; switch(pagina) { case 0: direccion = 'modulos/Clientes/paginas/rutinas_asignas.html'; //Buscando la información //Buscando las rutinas params = $methodsService.Json("Rutinas",1); var url = 'modulos/Rutinas/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; exitot = data.exitot; exitog = data.exitog; exitoe = data.exitoe; switch(true) { case exito==1 && exitot==1 && exitog==1 && exitoe==1: console.log(data); $scope.rutinas = data.rutinas; $scope.entrenadores = data.entrenadores; $scope.mostrarbuscando = false; $scope.mostrarcontent = true; $scope.url = 'modulos/Clientes/paginas/rutinas_asignas.html'; break; case exito!=1 || exitot!=1 || exitog!=1 || exitoe!=1: $methodsService.alerta(2,"algo falló, disculpe las molestias"); break; }//switch if(exito==1) { }//if else{$methodsService.alerta(2,"algo falló, disculpe las molestias");} }) .error(function(data, status, headers, config){$methodsService.alerta(2,"algo falló, disculpe las molestias");}); break; case 1: $scope.url = 'modulos/Clientes/paginas/rutinas_desasignar.html'; break; }//switch return direccion; }//obtenerdir })//AsignarRutinas .controller('RutinaOrdenC',function($scope,$http,$location,$methodsService,$routeParams){ //Contenedores de los ejercicios de cada dia. $scope.lunes = []; $scope.martes = []; $scope.miercoles = []; $scope.jueves = []; $scope.viernes = []; $scope.sabado = []; $scope.domingo = []; //Funciones $scope.CambiarDia = function(id_par,dia_semana) { //Obtener el tr que está encima var idJquery = "#"+id; var Padre = $(idJquery).prev()[0]; var son = $(idJquery).next()[0]; id = parseInt(id_par); //Situación en la que el ejercicio que se ha movido no tiene un nodo padre. if(Padre == undefined) { var id_Padre = 0; var AccionCambio = "SinPadre"; }else {id_Padre = Padre.id;} //Situación en la que el ejercicio que se ha movido no tiene un nodo hijo. if(son == undefined) { var id_Hijo = 0; var AccionCambio = "SinHijo"; }else {id_Hijo = son.id;} if(Padre != undefined && son !=undefined) { var id_Padre = Padre.id; var id_Hijo = son.id; //verificando si se bajó o subió posiciones // 1) si el padre es mayor, es por que se bajó la posición if(id_Padre>id) { var AccionCambio = "ConAmbosBajoPosicion"; var Cantidad_Puestos = id_Padre - id; }//if if(id_Padre<id) { AccionCambio = "ConAmbosSubioPosicion"; var Cantidad_Puestos = id - id_Hijo; }//if }//if // Escenarios posibles del cambio de lugar // 1) Cuando no se tiene padre -> Esto significa que se movió al primer puesto de la lista if (id_Padre == 0) { //Tomar la cantidad de puestos que se movió var Cantidad_Puestos = id-id_Hijo; } // id_Padre == 0 if (id_Hijo == 0) { Cantidad_Puestos = id_Padre-id; } //Tomando los valores para mandarlos al controller $scope.valores = { id_rutina: $scope.id_rutina, id_cambio: id, id_Hijo: id_Hijo, id_Padre: id_Padre, Cantidad_Puestos: Cantidad_Puestos, AccionCambio: AccionCambio, Accion: "CambioLugarEjercicio" }; console.log($scope.valores); var Params= JSON.stringify($scope.valores); //Validación, si el hijo es mayor por solo 1 o el padre menor por 1 Cantidad_DiferenciaHijo = id_Hijo - id; //Diferencia entre id_hijo y el id que fue movido Cantidad_DiferenciaPadre = id - id_Padre; Actividad_Sola = 0; MismoLugar_Hijo = 0; MismoLugar_Padre = 0; console.log(Cantidad_DiferenciaHijo+" diferencia"); //Verificando, si no tiene ni padre o hijio, es que es una sola actividad if(id_Hijo==0 && id_Padre==0 ) { Actividad_Sola = 1; }//if if(Cantidad_DiferenciaHijo!=1 && Cantidad_DiferenciaPadre!=1 && Actividad_Sola!=1 ) { var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:Params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; console.log(data); if(exito==1) { var id_diaCambio = data.dia; var ejercicios = data.ejercicios; $scope.AsignarEjercicios(id_diaCambio,ejercicios); }//if }) //success .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }//if }//CambiarDia $scope.AsignarEjercicios = function(dia,ejercicios) { switch(dia) { case '1': $scope.lunes = ejercicios; $("#lunesbody").empty(); $("#lunesbody").css("display","none"); $scope.AgregarEjerciciosTabla($scope.lunes,"#lunesbody"); $("#lunesbody").fadeIn(3000); $scope.InicializarTablas(); break; case '2': $scope.martes = ejercicios; $("#martesbody").empty(); $("#martesbody").css("display","none"); $scope.AgregarEjerciciosTabla($scope.martes,"#martesbody"); $("#martesbody").fadeIn(3000); $scope.InicializarTablas(); break; case '3': $scope.miercoles = ejercicios; $("#miercolesbody").css("display","none"); $("#miercolesbody").empty(); $scope.AgregarEjerciciosTabla($scope.miercoles,"#miercolesbody"); $("#miercolesbody").fadeIn(3000); $scope.InicializarTablas(); break; case '4': $scope.jueves = ejercicios; $("#juevesbody").css("display","none"); $("#juevesbody").empty(); $scope.AgregarEjerciciosTabla($scope.jueves,"#juevesbody"); $("#juevesbody").fadeIn(3000); $scope.InicializarTablas(); break; case '5': $scope.viernes = ejercicios; $("#viernesbody").css("display","none"); $("#viernesbody").empty(); $scope.AgregarEjerciciosTabla($scope.viernes,"#viernesbody"); $("#viernesbody").fadeIn(3000); $scope.InicializarTablas(); break; case '6': $scope.sabado = ejercicios; $("#sabadobody").css("display","none"); $("#sabadobody").empty(); $scope.AgregarEjerciciosTabla($scope.sabado,"#sabadobody"); $("#sabadobody").fadeIn(3000); $scope.InicializarTablas(); break; case '7': $scope.domingo = ejercicios; $("#domingobody").css("display","none"); $("#domingobody").empty(); $scope.AgregarEjerciciosTabla($scope.domingo,"#domingobody"); $("#domingobody").fadeIn(3000); $scope.InicializarTablas(); break; }//switch }//AsignarEjercicios $scope.AgregarEjerciciosTabla = function(ejercicios,tabla) { for(i=0; i<ejercicios.length; i++) { var eje = ejercicios[i]; var tr = '<tr class="text-center" id="'+eje.id_posicionejercicio+'"><td>'+eje.id_posicionejercicio+'</td><td>'+eje.nb_ejercicio+'</td><td>'+eje.nb_musculo+'</td></tr>' $(tabla).append(tr); }//for }//AgregarEjerciciosTabla $scope.definirEjercicioDia = function(dia,ejercicio) { switch(dia) { case '1': $scope.lunes.push(ejercicio); break; case '2': $scope.martes.push(ejercicio); break; case '3': $scope.miercoles.push(ejercicio); break; case '4': $scope.jueves.push(ejercicio); break; case '5': $scope.viernes.push(ejercicio); break; case '6': $scope.sabado.push(ejercicio); break; case '7': $scope.domingo.push(ejercicio); break; }//switch }//definirEjercicioDia $scope.InicializarTablas = function () { //Drag and drop table $("#table-1").tableDnD(); $("#table-2").tableDnD(); $("#table-3").tableDnD(); $("#table-4").tableDnD(); $("#table-5").tableDnD(); $("#table-6").tableDnD(); $("#table-7").tableDnD(); //Acciones // día lunes // $('#table-1').tableDnD({ onDrop: function(table, row) { //Tomando los datos del row que se movió id = row.id; dia_semana = "Actualiza_Lunes"; $scope.CambiarDia(id,dia_semana) } //onDrop }); // día Martes // $('#table-2').tableDnD({ onDrop: function(table, row) { //Tomando los datos del row que se movió id = row.id; dia_semana = "Actualiza_Martes"; $scope.CambiarDia(id,dia_semana) } }); // día miércoles// $('#table-3').tableDnD({ onDrop: function(table, row) { //Tomando los datos del row que se movió id = row.id; dia_semana = "Actualiza_Miercoles"; $scope.CambiarDia(id,dia_semana); } }); // día Jueves// $('#table-4').tableDnD({ onDrop: function(table, row) { //Tomando los datos del row que se movió id = row.id; dia_semana = "Actualiza_Jueves"; $scope.CambiarDia(id,dia_semana); } }); // día Viernes// $('#table-5').tableDnD({ onDrop: function(table, row) { console.log(row); //Tomando los datos del row que se movió id = row.id; dia_semana = "Actualiza_Viernes"; $scope.CambiarDia(id,dia_semana); } }); // día Sábado// $('#table-6').tableDnD({ onDrop: function(table, row) { //Tomando los datos del row que se movió id = row.id; dia_semana = "Actualiza_Sabado"; $scope.CambiarDia(id,dia_semana) } }); // día Domingo// $('#table-7').tableDnD({ onDrop: function(table, row) { //Tomando los datos del row que se movió id = row.id; dia_semana = "Actualiza_Domingo"; $scope.CambiarDia(id,dia_semana) } }); }//InicializarTablas $scope.RutinaPrefinal = function() { bootbox.confirm("Desea ir al final de la rutina?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/RutinaPrefinalC').search({Rut:$scope.id_rutina,Cliente:$scope.cliente}); }); }//if }); }//RutinaPrefinal //Tomadno los datos $scope.id_rutina = $routeParams.Rut; $scope.cliente = $routeParams.Cliente; var params = $methodsService.Json("InfoRutinaCliente",$scope.id_rutina); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { //Pegando los datos en las tblas. exito = data.exito; if(exito==1) { $scope.ejercicios = data.ejercicios; var cantidad = $scope.ejercicios.length; //definiendo los ejercicios por dia. for(i=0; i<cantidad; i++) { var id_dia = $scope.ejercicios[i].id_dia; $scope.definirEjercicioDia(id_dia,$scope.ejercicios[i]); }//for //Pegando los ejercicios para cada lista con jquery. for(i=0; i<$scope.lunes.length;i++) { var eje = $scope.lunes[i]; var tr = '<tr class="text-center" id="'+eje.id_posicionejercicio+'"><td>'+eje.id_posicionejercicio+'</td><td>'+eje.nb_ejercicio+'</td><td>'+eje.nb_musculo+'</td></tr>' $("#lunesbody").append(tr); }//for for(i=0; i<$scope.martes.length;i++) { var eje = $scope.martes[i]; var tr = '<tr class="text-center" id="'+eje.id_posicionejercicio+'"><td>'+eje.id_posicionejercicio+'</td><td>'+eje.nb_ejercicio+'</td><td>'+eje.nb_musculo+'</td></tr>' $("#martesbody").append(tr); }//for for(i=0; i<$scope.miercoles.length;i++) { var eje = $scope.miercoles[i]; var tr = '<tr class="text-center" id="'+eje.id_posicionejercicio+'"><td>'+eje.id_posicionejercicio+'</td><td>'+eje.nb_ejercicio+'</td><td>'+eje.nb_musculo+'</td></tr>' $("#miercolesbody").append(tr); }//for for(i=0; i<$scope.jueves.length;i++) { var eje = $scope.jueves[i]; var tr = '<tr class="text-center" id="'+eje.id_posicionejercicio+'"><td>'+eje.id_posicionejercicio+'</td><td>'+eje.nb_ejercicio+'</td><td>'+eje.nb_musculo+'</td></tr>' $("#juevesbody").append(tr); }//for for(i=0; i<$scope.viernes.length;i++) { var eje = $scope.viernes[i]; var tr = '<tr class="text-center" id="'+eje.id_posicionejercicio+'"><td>'+eje.id_posicionejercicio+'</td><td>'+eje.nb_ejercicio+'</td><td>'+eje.nb_musculo+'</td></tr>' $("#viernesbody").append(tr); }//for for(i=0; i<$scope.sabado.length;i++) { var eje = $scope.sabado[i]; var tr = '<tr class="text-center" id="'+eje.id_posicionejercicio+'"><td>'+eje.id_posicionejercicio+'</td><td>'+eje.nb_ejercicio+'</td><td>'+eje.nb_musculo+'</td></tr>' $("#sabadobody").append(tr); }//for for(i=0; i<$scope.domingo.length;i++) { var eje = $scope.domingo[i]; var tr = '<tr class="text-center" id="'+eje.id_posicionejercicio+'"><td>'+eje.id_posicionejercicio+'</td><td>'+eje.nb_ejercicio+'</td><td>'+eje.nb_musculo+'</td></tr>' $("#domingobody").append(tr); }//for $scope.InicializarTablas(); }//if }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); })//RutinaOrdenC .controller('RutinaprefinalC',function($scope,$http,$location,$methodsService,$routeParams){ // Variables $scope.Rut = $routeParams.Rut; $scope.Cliente = $routeParams.Cliente; //Funciones $scope.EnviarRutina = function() { bootbox.confirm("Desea enviar la rutina?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ alert("hola"); var url = 'modulos/Clientes/CrearPdf.php'; $http({method: "post",url: url,data: $.param({id_rutina:$scope.Rut}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }); }//if }); }//EnviarRutina $scope.CambioTabla = function(id,newValue) { if($(id2).hasClass("Repeticiones")) { if($.isNumeric(newValue)) { id_rutina = $("#id_rutina").val(); idEjercicio = id.split("Val"); console.log("el id es: "+idEjercicio[1]+" Las repeticiones son : "+newValue); $scope.InsertarRepeticionesBD(idEjercicio[1], newValue,id_rutina); }//if else { bootbox.confirm("Favor de ingresar un número válido.", function(result) {}); }//else }//If class if($(id2).hasClass("Circuitos")) { if($.isNumeric(newValue)) { id_rutina = $("#id_rutina").val(); idEjercicio = id.split("ValRu"); console.log("el id es: "+idEjercicio[1]+" Los Circuitos son : "+newValue); $scope.InsertarCircuitosBD(idEjercicio[1], newValue) } else { alert("Favor de ingresar un número válido."); }//else }//if if($(id2).hasClass("Relacion")) { id_rutina = $("#id_rutina").val(); idEjercicio = id.split("ValRe"); console.log("el id es: "+idEjercicio[1]+" La relación es : "+newValue); $scope.InsertarRelacionEjerciciosBD(idEjercicio[1],newValue); }//if }//CambioTabla $scope.FinalizarRutina = function() { bootbox.confirm("Desea ir al apartado de Clientes?", function(result) { console.log(result); if(result==true) { $scope.$apply(function(){ $location.path('/Clientes').search({}); }); }//if }); }//FinalizarRutina $scope.InsertarCircuitosBD = function (id, circuitos,id_rutina) { //Objeto con la información a guardar en la BD var Arr=new Object(); Arr['id_rutina'] = id_rutina; Arr['id_ejercicio'] = id; Arr['num_circuitos'] = circuitos; Arr['Accion'] = "AgregarCircuitosEjercicio"; params = JSON.stringify(Arr); console.log(params); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); } $scope.InsertarRepeticionesBD = function (id, repeticiones,id_rutina) { //Objeto con la información a guardar en la BD var Arr = new Object(); Arr['id_rutina'] = $scope.Rut; Arr['id_ejercicio'] = id; Arr['num_repeticiones'] = repeticiones; Arr['Accion'] = "AgregarRepeticionesEjercicio"; params = JSON.stringify(Arr); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) {}) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }//InsertarRepeticionesBD $scope.InsertarRelacionEjerciciosBD = function (id,relacion) { //Objeto con la información a guardar en la BD var Arr=new Object(); Arr['id_ejercicio'] = id; Arr['relacion'] = relacion; Arr['Accion'] = "AgregarRelacionEjercicio"; params = JSON.stringify(Arr); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) {}) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }//InsertarRelacionEjerciciosBD //Tomando los datos de las rutina del cliente. params = $methodsService.Json("EjerciciosRutinaOrden",$scope.Rut); var url = 'modulos/Clientes/Funciones.php'; $http({method: "post",url: url,data: $.param({Params:params}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data, status, headers, config) { exito = data.exito; if(exito==1) { $scope.ejercicios = data.ejercicios; var cantidad = $scope.ejercicios.length; //definiendo los ejercicios por dia. for(i=0; i<cantidad; i++) { var eje = $scope.ejercicios[i]; circuitos = (eje.num_circuitos!=null)?eje.num_circuitos:0; repet = (eje.num_repeticiones!=null)?eje.num_repeticiones:0; rel = (eje.ejercicio_relacion!=null)?eje.ejercicio_relacion:""; var tr = '<tr class="text-center" id="'+eje.id_rutinacliente+'">'; tr+='<td>'+eje.id_posicionejercicio+'</td><td>'+eje.nb_rutina+'</td>'; tr+='<td>'+eje.nb_ejercicio+'</td><td id="Val'+eje.id_ejercicio+'" class="Repeticiones">'+repet+'</td>'; tr+='<td id="ValRu'+eje.id_ejercicio+'" class="Circuitos">'+circuitos+'</td>'; tr+='<td>'+eje.nb_dia+'</td><td>'+eje.nb_tiporutina+'</td>'; tr+='<td>'+eje.nb_musculo+'</td>'; tr+='<td>'+eje.fh_creacion+'</td>'; tr+='<td id="ValRe'+eje.id_ejercicio+'" class="Relacion">'+rel+'</td></tr>'; $("#tablecontent").append(tr); }//for $('#listados').editableTableWidget(); $('table td').on('change', function(evt, newValue) { id=evt.currentTarget.id; id2="#"+id; $scope.CambioTabla(id2,newValue); }); }//if }) .error(function(data, status, headers, config){ $methodsService.alerta(2,"algo falló, disculpe las molestias"); }); }) .service('respservice', function() { var respuestas = []; var addresp = function(newObj) { respuestas = newObj; }; var getresp = function(){ return respuestas; }; return { addresp: addresp, getresp: getresp }; }); <reponame>Problem-Solver0216/millix<filename>src/js/services/bitcore.js<gh_stars>100-1000 'use strict'; angular.module('copayApp.services') .factory('bitcore', function bitcoreFactory(bwcService) { var bitcore = bwcService.getBitcore(); return bitcore; }); <reponame>lechristian/personal-website<gh_stars>0 /* ========================================================================== * ./src/shared/components/sent.js * * Message Sent * ========================================================================== */ import React, { Component } from 'react'; import { Link } from 'react-router'; class MessageSent extends Component { constructor(props) { super(props); } render() { return ( <div className="message-sent"> <h3 className="center">Message Sent!</h3> <h5 className="center light">I'll get back to you as soon as I can.</h5> <div className="nav-links"> <Link to={'/blurbs'} className="inline">Blurbs</Link> <div className="inline">|</div> <Link to={'/photos'} className="inline">Photos</Link> <div className="inline">|</div> <Link to={'/'} className="inline">Home</Link> </div> </div> ); } } export default MessageSent; /** * Created by ishaan.puniani on 2016-12-23. */ export function moodCssClassForColor(moodscore){ if(moodscore < 33){ return "danger"; } else if(moodscore > 33 && moodscore < 66){ return "warning" } else { return "success"; } };<filename>src/wrappings.js<gh_stars>1-10 const quotations = { '\"': '\"', '\“': '\”', '«': '»', '‹': ' ›', '‘': '’', '‚': '‘', '„': '“', } const brackets = { '(': ')', '[': ']', '{': '}', '<': '>', '⌈': '⌉', '⌊': '⌋', '⸢': '⸣', '⸤': '⸥' } const wrappings = Object.assign(quotations, brackets); function toUnicode(ch) { return `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`; } function constructStartingRegex() { const str = Object.keys(wrappings).map(toUnicode).join(''); return new RegExp(`^[${str}]+`, 'g'); } function constructEndingRegex() { const str = Object.values(wrappings).map(toUnicode).join(''); return new RegExp(`[${str}]+$`, 'g'); } function constructUnwrapRegex() { const startChars = Object.keys(wrappings).map(toUnicode).join(''); const endChars = Object.values(wrappings).map(toUnicode).join(''); return new RegExp(`[${startChars + endChars}]+`, 'g'); } export const COMPLETE_REGEX_START = constructStartingRegex(); export const COMPLETE_REGEX_END = constructEndingRegex(); export const COMPLETE_REGEX_UNWRAP = constructUnwrapRegex(); export default wrappings;import Mixin from '@ember/object/mixin'; import { inject as service } from '@ember/service'; import { get, set } from '@ember/object'; export default Mixin.create({ _feedback: service('feedback'), init: function() { this._super(...arguments); const feedback = get(this, '_feedback'); const route = this; set(this, 'feedback', { execute: function() { feedback.execute(...[...arguments, route.controller]); }, }); }, }); <gh_stars>10-100 /* Copyright 2012 MarkLogic Corporation 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. */ var m = window.mljs || {}; var b = m.bindings || {}; b.xhr = function() { // constructor }; if (typeof XMLHttpRequest === "undefined") { XMLHttpRequest = function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} // Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant throw new Error("This browser does not support XMLHttpRequest."); }; } b.xhr.supportsAdmin = function() { return false; // can only access our own REST HTTP Server }; b.xhr.configure = function(username,password,logger) { this.logger = logger; this.username = username; this.password = password; }; b.xhr.request = function(reqname,options,content,callback) { var xmlhttp = new XmlHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState === 4){ if (xmlhttp.status == 200) { // success var res = {}; res.inError = false; res.statusCode = xmlhttp.status; res.doc = JSON.parse(xmlhttp.responseText); // successes are JSON // TODO support XML returned too callback(res); } else { // failure // get failure code to determine what to do next var res = {}; if (xmlhttp.status == 303) { res.location = xmlhttp.getHeader("location"); // for newly created document / upload } res.inError = true; res.statusCode = xmlhttp.status; res.doc = xmlhttp.responseText; // failures are returned in XML callback(res); } } }; xmlhttp.open(options.method, options.path, true,this.username,this.password); xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xmlhttp.send(content); }; <filename>third_party/silabs/gecko_sdk_suite/v1.0/protocol/flex_1.1/documentation/API_RAIL_HTML/dir_33be2c2db3aeb0fc1f3a539c794f152f.js var dir_33be2c2db3aeb0fc1f3a539c794f152f = [ [ "rf", "dir_0da7176af749054cc8f902e4eff1ec64.html", "dir_0da7176af749054cc8f902e4eff1ec64" ], [ "rail_chip_specific.h", "rail__chip__specific_8h.html", "rail__chip__specific_8h" ], [ "rail_efr32xg1x_interrupts.h", "rail__efr32xg1x__interrupts_8h.html", "rail__efr32xg1x__interrupts_8h" ] ];const mongoose = require('mongoose'); const Schema = mongoose.Schema; const RekapKursiSchema = new Schema({ id: { type: Schema.Types.ObjectId, },dapil: { type: String, required: true, index: true },hasil:{ type:Array, required:true }, updatedAt: { type: Date }, createdAt: { type: Date, default: Date.now() } },{ autoCreate: true }); const RekapKursi = mongoose.model('rekapkursi', RekapKursiSchema); module.exports = RekapKursi;<gh_stars>0 $(document).ready(function () { 'use strict'; if ($('#map-leaflet').length) { var map = L.map('map-leaflet', { zoom: 12, maxZoom: 20, tap: false, gestureHandling: true, center: [40.761077, -73.88] }); var marker_cluster = L.markerClusterGroup(); map.scrollWheelZoom.disable(); var OpenStreetMap_Mapnik = L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', { scrollWheelZoom: false, attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); $.ajax('js/markers3.json', { success: function (markers) { $.each(markers, function (index, value) { var icon = L.divIcon({ html: value.icon, iconSize: [50, 50], iconAnchor: [50, 50], popupAnchor: [-20, -42] }); var marker = L.marker(value.center, { icon: icon }).addTo(map); marker.bindPopup( '<div class="listing-window-image-wrapper">' + '<a href="single-property.html">' + '<div class="listing-window-image" style="background-image: url(' + value.image + ');"></div>' + '<div class="listing-window-content">' + '<div class="info">' + '<h2>' + value.title + '</h2>' + '<p>' + value.desc + '</p>' + '<h3>' + value.price + '</h3>' + '</div>' + '</div>' + '</a>' + '</div>' ); marker_cluster.addLayer(marker); }); map.addLayer(marker_cluster); } }); } }); <filename>utils/request.js /* http 请求封装 @author maybe */ // 导入封装的request框架 import Http from '@/js_sdk/luch-request/luch-request/index.js' import store from '@/store'; import { getToken } from './auth' export const request = new Http({ timeout: 300000 //超时时长5分钟 }) // 环境前缀添加 let baseURL = null; if (process.env.NODE_ENV === 'development') { // 开发环境 baseURL = 'http://172.16.17.32:80/' //baseURL = 'http://192.168.127.12:8080/' } else { baseURL = 'http://172.16.17.32:80/' // 生产环境 // baseURL = 'https://movie.lzzzero.com/api' } request.config.baseURL = baseURL // 错误弹框提示 const errorToast = (msg) => { uni.showToast({ title: msg || 'fetch data error.', icon: 'none' }) } /** * 自定义响应错误逻辑 */ const handleCustomError = (res) => { console.info(res) switch (res.statusCode) { case 404: console.info('很抱歉,资源未找到') errorToast('很抱歉,资源未找到') break case 403: case 401: errorToast('很抱歉,您无法访问该资源,可能是因为没有相应权限或者登录已失效') break default: errorToast(res.msg) break; } } request.interceptors.request.use((config) => { let token = getToken(); console.info(config) if (token && config.url!='/v1/tuser/login' && config.url!='/v1/tuser/sendsms' && !(config.method=='POST' && config.url=='/v1/tuser') ) { config.header['Authorization'] = token; } console.log(config) uni.showNavigationBarLoading() return config }) request.interceptors.response.use((response) => { uni.hideNavigationBarLoading() console.log(response) // 服务器正确响应拦截逻辑处理 // code = 200 是逻辑正确响应的状态码可自行修改 if(response.data!=null){ if(response.data.Message=="服务器繁忙"){ // uni.navigateTo({ // url: '/pages/login/login' // }) uni.showToast({ icon: "none", title: "连接已过期,请重新登陆", }) store.dispatch('user/logout'); return Promise.reject(new Error("连接已过期,请重新登陆")) } } if ( response.statusCode !== 200) { //handleCustomError(response); return Promise.reject(new Error(response.msg)) } return Promise.resolve(response.data) }, (err) => { uni.hideNavigationBarLoading() handleCustomError(err) //errorToast(err.errMsg) return Promise.reject(new Error(err.errMsg)) }) //export default request // 创建新的实例请求对象 export const create = () => { return new Http(); } /** * 上传头像 */ export const uploadPhoto2 = (url, tempFilePaths ,successCb,errorCb)=>{ let token = getToken() uni.showLoading({ title: '上传中...' }); uni.uploadFile({ url: baseURL + url, filePath: tempFilePaths, fileType: 'image', name: 'myfile', header: { 'Authorization': token }, formData: { 'method': 'images.upload', 'myfile': tempFilePaths }, success: (uploadFileRes) => { console.info(uploadFileRes) successCb(JSON.parse(uploadFileRes.data)); }, fail: (error) => { if (error && error.response) { errorToast(error.response); errorCb && errorCb(error.response) } }, complete: () => { setTimeout(function() { uni.hideLoading(); }, 250); }, }); } /** * 上传图片 * @param {string} url * @param {Function} successCb * @param {number} maxCount * @param {Function} errorCb */ export const uploadImage = (url, successCb, maxCount = 1, errorCb) => { let token = getToken() uni.chooseImage({ count: maxCount, success: (res) => { uni.showLoading({ title: '上传中...' }); let tempFilePaths = res.tempFilePaths for (var i = 0; i < tempFilePaths.length; i++) { uni.uploadFile({ url: baseURL + url, filePath: tempFilePaths[i], fileType: 'image', name: 'file', header: { 'token': token }, formData: { 'method': 'images.upload', 'upfile': tempFilePaths[i] }, success: (uploadFileRes) => { successCb(JSON.parse(uploadFileRes.data)); }, fail: (error) => { if (error && error.response) { errorToast(error.response); errorCb && errorCb(error.response) } }, complete: () => { setTimeout(function() { uni.hideLoading(); }, 250); }, }); } } }); } <reponame>ustrico/job<gh_stars>0 /*! UIkit 2.22.0 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ !function (t) { "use strict"; t.component("cover", { defaults: {automute: !0}, boot: function () { t.ready(function (i) { t.$("[data-uk-cover]", i).each(function () { var i = t.$(this); if (!i.data("cover")) { t.cover(i, t.Utils.options(i.attr("data-uk-cover"))) } }) }) }, init: function () { if (this.parent = this.element.parent(), t.$win.on("load resize orientationchange", t.Utils.debounce(function () { this.check() }.bind(this), 100)), this.on("display.uk.check", function () { this.element.is(":visible") && this.check() }.bind(this)), this.check(), this.element.is("iframe") && this.options.automute) { var i = this.element.attr("src"); this.element.attr("src", "").on("load", function () { this.contentWindow.postMessage('{ "event": "command", "func": "mute", "method":"setVolume", "value":0}', "*") }).attr("src", [i, i.indexOf("?") > -1 ? "&" : "?", "enablejsapi=1&api=1"].join("")) } }, check: function () { this.element.css({width: "", height: ""}), this.dimension = { w: this.element.width(), h: this.element.height() }, this.element.attr("width") && !isNaN(this.element.attr("width")) && (this.dimension.w = this.element.attr("width")), this.element.attr("height") && !isNaN(this.element.attr("height")) && (this.dimension.h = this.element.attr("height")), this.ratio = this.dimension.w / this.dimension.h; var t, i, e = this.parent.width(), n = this.parent.height(); e / this.ratio < n ? (t = Math.ceil(n * this.ratio), i = n) : (t = e, i = Math.ceil(e / this.ratio)), this.element.css({ width: t, height: i }) } }) }(UIkit);<gh_stars>1-10 'use strict'; angular.module('bucleApp.core') .directive('ccElement', [ '$sce', 'Cc', 'Writers', function ($sce, Cc, Writers) { return { templateUrl: 'components/templates/cc.html', link: function(scope, element, attrs) { scope.work = JSON.parse(attrs.work); scope.license = Cc.get(scope.work.license); var writerId = scope.work.writerId; var writer = Writers.filter( function(writerObj) { return writerObj.id == writerId; }); writer = writer[0]; var html = scope.license.html; html = html.replace("{{TITLE}}", scope.work.title); html = html.replace("{{AUTHOR}}", writer.name); html = html.replace("{{AUTHOR_URL}}", writer.url); scope.html = $sce.trustAsHtml(html); }, replace: true }; } ]); <filename>src/blocks/formLayouts/ContactUs/Form.js /* eslint-disable react/no-unescaped-entities */ import React from 'react'; import { useFormik } from 'formik'; import * as yup from 'yup'; import Box from '@mui/material/Box'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import Grid from '@mui/material/Grid'; import TextField from '@mui/material/TextField'; import Button from '@mui/material/Button'; import { useTheme } from '@mui/material/styles'; const validationSchema = yup.object({ firstName: yup .string() .trim() .min(2, 'Please enter a valid name') .max(50, 'Please enter a valid name') .required('Please specify your first name'), lastName: yup .string() .trim() .min(2, 'Please enter a valid name') .max(50, 'Please enter a valid name') .required('Please specify your last name'), email: yup .string() .trim() .email('Please enter a valid email address') .required('Email is required.'), message: yup.string().trim().required('Please specify your message'), }); const ContactUs = ({ title, description }) => { const theme = useTheme(); const initialValues = { firstName: '', lastName: '', email: '', message: '', }; const onSubmit = (values) => { return values; }; const formik = useFormik({ initialValues, validationSchema: validationSchema, onSubmit, }); return ( <Box maxWidth={600} margin={'0 auto'}> <Box marginBottom={4}> <Typography variant={'h3'} sx={{ fontWeight: 700 }} align={'center'} gutterBottom > {title} </Typography> <Typography color="text.secondary" align={'center'}> {description} </Typography> </Box> <Box paddingBottom={6}> <form onSubmit={formik.handleSubmit}> <Grid container spacing={4}> <Grid item xs={12} sm={6}> <TextField sx={{ height: 54 }} label="<NAME>" variant="outlined" color="primary" size="medium" name="firstName" fullWidth value={formik.values.firstName} onChange={formik.handleChange} error={ formik.touched.firstName && Boolean(formik.errors.firstName) } helperText={formik.touched.firstName && formik.errors.firstName} /> </Grid> <Grid item xs={12} sm={6}> <TextField sx={{ height: 54 }} label="<NAME>" variant="outlined" color="primary" size="medium" name="lastName" fullWidth value={formik.values.lastName} onChange={formik.handleChange} error={ formik.touched.lastName && Boolean(formik.errors.lastName) } helperText={formik.touched.lastName && formik.errors.lastName} /> </Grid> <Grid item xs={12}> <TextField sx={{ height: 54 }} label="Email" type="email" variant="outlined" color="primary" size="medium" name="email" fullWidth value={formik.values.email} onChange={formik.handleChange} error={formik.touched.email && Boolean(formik.errors.email)} helperText={formik.touched.email && formik.errors.email} /> </Grid> <Grid item xs={12}> <TextField label="Message" multiline rows={6} variant="outlined" color="primary" size="medium" name="message" fullWidth value={formik.values.message} onChange={formik.handleChange} error={formik.touched.message && Boolean(formik.errors.message)} helperText={formik.touched.message && formik.errors.message} /> </Grid> <Grid item container justifyContent={'center'} xs={12}> <Button sx={{ height: 54, minWidth: 150 }} variant="contained" color="secondary" size="medium" type="submit" > Submit </Button> </Grid> <Grid item xs={12}> <Divider /> </Grid> <Grid item container justifyContent={'center'} xs={12}> <Box> <Typography component="p" variant="body2" align="left"> By clicking on "submit" you agree to our{' '} <Box component="a" href="/legal/privacy-policy/" color={theme.palette.text.primary} fontWeight={'700'} > Privacy Policy </Box> . </Typography> </Box> </Grid> </Grid> </form> </Box> </Box> ); }; export default ContactUs; <gh_stars>0 /** * File: /Users/youngcao/Desktop/xbsp/CBCenter/src/pages/storesCargo/storesCargoCU/checkSearch.js * Project: /Users/youngcao/Desktop/xbsp/CBCenter * Created Date: Tuesday November 21st 2017 7:52:36 pm * Author: youngcao * ----- * Last Modified:Wednesday December 6th 2017 2:55:22 pm * Modified By: chengpu * ----- * Copyright (c) 2017 MagCloud */ import React, { Component } from 'react'; import { Select } from 'antd'; import { getProductByKeywordRequest, getProductMsgByCodeRequest } from '../../api/api'; const Option = Select.Option; let timeout; let currentValue; let result; function query(value, providerCode, callback) { if (timeout) { clearTimeout(timeout); timeout = null; } currentValue = value; async function fake() { const response = await getProductByKeywordRequest({ productName: value, providerCode }); // console.log(response); if (currentValue === value) { result = response.obj || []; const data = []; result.forEach((r) => { data.push({ value: r.productId, text: r.productName, }); }); callback(data, result); } } timeout = setTimeout(fake, 300); } async function getProMsyByCode(el, target) { const response = await getProductMsgByCodeRequest({ code: el.productCode }); el.elseProObj = response.obj; target.props.onSelect(el); } export class SearchInput extends Component { state = { data: [], } handleChange = (value) => { if (value || value === 0 || value === false) { query(value, this.props.providerCode, (data) => { this.setState({ data }); }); } else { this.props.onSelect(null); } } handleSelect = (value) => { if (this.props.onSelect) { result.some((el) => { if (el.productName === value) { getProMsyByCode(el, this); return true; } return false; }, this); } } render() { const options = this.state.data.map(d => ( <Option title={d.text.toString()} key={d.value.toString()} value={d.text.toString()} >{d.text} </Option>) ); return ( <Select disabled={this.props.disabled} mode="combobox" placeholder={this.props.placeholder} notFoundContent="" defaultValue={this.props.value || ''} style={this.props.style} defaultActiveFirstOption={false} showArrow={false} filterOption={false} onChange={this.handleChange} onSelect={this.handleSelect} className={this.props.className} > {options} </Select> ); } } export const SearchII = (props) => { const handleSelect = (value) => { if (props.onSelect) { props.list.some((el) => { if (el.name === value) { props.onSelect(el); return true; } return false; }, this); } }; return ( <Select disabled={props.disabled} showSearch placeholder="档口" style={{ width: '100%' }} className="ant-select-open" // mode="multiple" mode="combobox" onSelect={handleSelect} filterOption={ (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } > { props.list.map(x => ( <Option key={`${x.id}`} value={`${x.name}`} >{x.name} </Option>) )} </Select> ); }; <reponame>pursuccess/vue-admin-template<filename>mock/weixin.js import Mock from 'mockjs' const data = Mock.mock({ 'items|100': [{ id: '@id', userLevel: '高级会员', name: '@first', registerTime: '@date', mail: '<EMAIL>' }] }) const list = data.items export default [ { url: '/weixin/template/users', type: 'post', response: config => { const { page = 1, pagesize = 10 } = config.body const pageList = list.filter((item, index) => index < pagesize * page && index >= pagesize * (page - 1)) return { result: 1, data: { total: list.length, list: pageList } } } }, { url: '/weixin/template/filterUsers', type: 'post', response: config => { const { page = 1, pagesize = 10 } = config.body const pageList = list.filter((item, index) => index < pagesize * page && index >= pagesize * (page - 1)) return { result: 1, data: { total: list.length, list: pageList } } } }, { url: '/weixin/template/add-to-users', type: 'post', response: config => { return { result: 1, data: 'success' } } }, { url: '/weixin/template/task-start', type: 'post', response: config => { return { result: 1, data: 'success' } } } ] <filename>src/js/scenes/submit_score.js import Phaser from 'phaser'; import ApiModule from '../../scoreApi'; export default class SubmitScore extends Phaser.Scene { constructor() { super('SubmitScore'); } create() { const submitLabel = this.add.text(15, 250, 'Please enter your user: ', { fontSize: '24px', fill: '#fff', align: 'left', wordwrap: { width: 100 }, }); const element = this.add.dom(400, 600).createFromCache('form_for_username'); element.setPerspective(800); element.addListener('click'); element.on('click', (event) => { if (event.target.name === 'confirm') { const username = element.getChildByName('username'); if (username.value !== '') { const loadingMessage = this.add.text(350, 350, 'Please wait...', { fontSize: '24px', fill: '#fff', align: 'left', }); ApiModule.writeScore(username.value, localStorage.getItem('score')).then(() => { loadingMessage.destroy(); element.scene.scene.start('Menu'); }).catch(() => { alert('Error. Unable to save your score'); }); } else { element.scene.tweens.add({ targets: submitLabel, alpha: 0.1, duration: 300, ease: 'Power2', yoyo: true, }); } } }); this.tweens.add({ targets: element, y: 300, duration: 3000, ease: 'Power3', }); } }'use strict'; var ko = require('../herocalc_knockout'); var constants = require("../constants"); var StatModel = require("../StatModel"); var AbilityModel = require("../AbilityModel"); var BuffViewModel = require("../BuffViewModel"); var InventoryViewModel = require("../inventory/InventoryViewModel"); var diffProperties = require("./diffProperties"); var HeroDamageMixin = require("./HeroDamageMixin"); var TalentController = require("./TalentController"); var totalExp = require("./totalExp"); var nextLevelExp = require("./nextLevelExp"); var illusionData = require("../illusion/illusionData"); var findWhere = require("../util/findWhere"); var extend = require("../util/extend"); var HeroModel = function (heroData, itemData, h) { var self = this; self.heroId = ko.observable(h); self.illusionId = ko.observable(''); self.isIllusion = ko.observable(false); self.selectedHeroLevel = ko.observable(1); self.inventory = new InventoryViewModel(itemData, self); self.selectedInventory = ko.observable(-1); self.buffs = new BuffViewModel(itemData); self.buffs.hasScepter = self.inventory.hasScepter; self.debuffs = new BuffViewModel(itemData); self.heroData = ko.pureComputed(function () { return heroData['npc_dota_hero_' + self.heroId()]; }); self.heroCompare = ko.observable(self); self.enemy = ko.observable(self); self.unit = ko.observable(self); self.clone = ko.observable(self); self.talents = [ ko.observable(-1), ko.observable(-1), ko.observable(-1), ko.observable(-1) ]; self.selectedTalents = ko.pureComputed(function () { var arr = []; for (var i = 0; i < 4; i++) { if (self.talents[i]() !== -1) { arr.push(self.heroData().talents[i][self.talents[i]()]); } } return arr; }); self.skillPointHistory = ko.observableArray(); self.ability = ko.computed(function () { var a = new AbilityModel(ko.observableArray(JSON.parse(JSON.stringify(self.heroData().abilities))), self); switch (self.heroId()) { case 'earth_spirit': case 'ogre_magi': a._abilities[3].level(1); break; case 'monkey_king': a._abilities[5].level(1); break; case 'invoker': for (var i = 5; i < 16; i++) { a._abilities[i].level(1); } break; } self.skillPointHistory.removeAll(); a.hasScepter = self.inventory.hasScepter return a; }); self.availableSkillPoints = ko.computed(function () { var c = self.selectedHeroLevel(); for (var i = 0; i < 4; i++) { if (self.selectedHeroLevel() < i * 5 + 10) self.talents[i](-1); } c -= self.talents.filter(function (talent) { return talent() !== -1 }).length; for (var i = 0; i < self.ability().abilities().length; i++) { switch(self.ability().abilities()[i].abilitytype) { case 'DOTA_ABILITY_TYPE_ULTIMATE': if (self.heroId() === 'invoker') { /*while ( ((self.ability().abilities()[i].level() == 1) && (parseInt(self.selectedHeroLevel()) < 2)) || ((self.ability().abilities()[i].level() == 2) && (parseInt(self.selectedHeroLevel()) < 7)) || ((self.ability().abilities()[i].level() == 3) && (parseInt(self.selectedHeroLevel()) < 11)) || ((self.ability().abilities()[i].level() == 4) && (parseInt(self.selectedHeroLevel()) < 17)) ) { self.ability().levelDownAbility(i, null, null, self); }*/ } else if (self.heroId() === 'meepo') { while ((self.ability().abilities()[i].level()-1) * 7 + 3 > parseInt(self.selectedHeroLevel())) { self.ability().levelDownAbility(i, null, null, self); } } else { while (self.ability().abilities()[i].level() * 5 + 1 > parseInt(self.selectedHeroLevel())) { self.ability().levelDownAbility(i, null, null, self); } } break; default: while (self.ability().abilities()[i].level() * 2 - 1 > parseInt(self.selectedHeroLevel())) { self.ability().levelDownAbility(i, null, null, self); } break; } } while (self.skillPointHistory().length > c) { self.ability().levelDownAbility(self.skillPointHistory()[self.skillPointHistory().length-1], null, null, self); } return c-self.skillPointHistory().length; }, this); self.getAbilityAttributeValue = function(hero, ability, attributeName, level) { if (!attributeName) return 0; ability = ability.indexOf('phantom_lancer_doppelwalk') == -1 ? ability : 'phantom_lancer_doppelwalk'; if (ability == 'item_manta') { var abilityObj = itemData[ability]; } else { var abilityObj = findWhere(heroData['npc_dota_hero_' + hero].abilities, {name: ability}); } var attribute = findWhere(abilityObj.attributes, {name: attributeName}); if (level == 0) { return parseFloat(attribute.value[0]); } else if (level > attribute.value.length) { return parseFloat(attribute.value[0]); } else { return parseFloat(attribute.value[level - 1]); } } self.illusionAbilityLevel = ko.observable(0); self.getIncomingDamageMultiplier = function(illusionType, hasScepter, attackType) { console.log('illusionType', illusionType); if (!illusionType) return 1; var sign = illusionData[illusionType].incoming_damage_sign || 1; if (illusionType == 'item_manta') { if (attackType == 'DOTA_UNIT_CAP_MELEE_ATTACK') { return (1 + sign * self.getAbilityAttributeValue(illusionData[illusionType].hero, illusionType, illusionData[illusionType].incoming_damage_melee, self.illusionAbilityLevel())/100) } else { return (1 + sign * self.getAbilityAttributeValue(illusionData[illusionType].hero, illusionType, illusionData[illusionType].incoming_damage_ranged, self.illusionAbilityLevel())/100) } } else { return (1 + sign * self.getAbilityAttributeValue(illusionData[illusionType].hero, illusionType, illusionData[illusionType].incoming_damage, self.illusionAbilityLevel())/100) } } self.getOutgoingDamageMultiplier = function(illusionType, hasScepter, attackType) { console.log('illusionType', illusionType); if (!illusionType) return 1; var sign = illusionData[illusionType].outgoing_damage_sign || 1; if (illusionType == 'item_manta') { if (attackType == 'DOTA_UNIT_CAP_MELEE_ATTACK') { return (1 + sign * self.getAbilityAttributeValue(illusionData[illusionType].hero, illusionType, illusionData[illusionType].outgoing_damage_melee, self.illusionAbilityLevel())/100); } else { return (1 + sign * self.getAbilityAttributeValue(illusionData[illusionType].hero, illusionType, illusionData[illusionType].outgoing_damage_ranged, self.illusionAbilityLevel())/100); } } else { return (1 + sign * self.getAbilityAttributeValue(illusionData[illusionType].hero, illusionType, illusionData[illusionType].outgoing_damage, self.illusionAbilityLevel())/100); } } self.primaryAttribute = ko.pureComputed(function () { var v = self.heroData().attributeprimary; if (v === 'DOTA_ATTRIBUTE_AGILITY') return 'agi'; if (v === 'DOTA_ATTRIBUTE_INTELLECT') return 'int'; if (v === 'DOTA_ATTRIBUTE_STRENGTH') return 'str'; return ''; }); self.totalExp = ko.pureComputed(function () { return totalExp[self.selectedHeroLevel() - 1]; }); self.nextLevelExp = ko.pureComputed(function () { return nextLevelExp[self.selectedHeroLevel() - 1]; }); self.startingArmor = ko.pureComputed(function () { return self.heroData().attributebaseagility * constants.armorPerAgi + self.heroData().armorphysical; }); self.respawnTime = ko.pureComputed(function () { var level = self.selectedHeroLevel(); var reduction = TalentController.getRespawnReduction(self.selectedTalents()); if (level >= 1 && level <= 5) { return (level - 1) * 2 + 8 - reduction; } else if (level >= 6 && level <= 11) { return (level - 6) * 2 + 26 - reduction; } else if (level >= 12 && level <= 17) { return (level - 12) * 2 + 46 - reduction; } else if (level >= 18 && level <= 24) { return (level - 18) * 4 + 66 - reduction; } else if (level == 25) { return 100 - reduction; } }); self.totalAttribute = function (a) { if (a === 'agi') return self.totalAgi().total; if (a === 'int') return self.totalInt().total; if (a === 'str') return self.totalStr().total; return 0; }; self.totalAgi = ko.pureComputed(function () { var s = new StatModel(self.heroData().attributebaseagility, 'Base'); s.add(self.heroData().attributeagilitygain * (self.selectedHeroLevel() - 1), 'Level') .concat(self.inventory.getAttributes('agi')) .concat(self.ability().getAgility()) .concat(TalentController.getAgility(self.selectedTalents())) .concat(self.enemy().ability().getAllStatsReduction()) .concat(self.debuffs.getAllStatsReduction()) return s; }); self.intStolen = ko.observable(0).extend({ numeric: 0 }); self.totalInt = ko.pureComputed(function () { var s = new StatModel(self.heroData().attributebaseintelligence, 'Base'); s.add(self.heroData().attributeintelligencegain * (self.selectedHeroLevel() - 1), 'Level') .concat(self.inventory.getAttributes('int')) .concat(self.ability().getIntelligence()) .concat(TalentController.getIntelligence(self.selectedTalents())) .concat(self.enemy().ability().getAllStatsReduction()) .concat(self.debuffs.getAllStatsReduction()) .add(self.intStolen(), 'Int Stolen') .add(-self.enemy().intStolen(), 'Int Stolen') return s; }); self.totalStr = ko.pureComputed(function () { var s = new StatModel(self.heroData().attributebasestrength, 'Base'); s.add(self.heroData().attributestrengthgain * (self.selectedHeroLevel() - 1), 'Level') .concat(self.inventory.getAttributes('str')) .concat(self.ability().getStrength()) .concat(TalentController.getStrength(self.selectedTalents())) .concat(self.enemy().ability().getStrengthReduction()) .concat(self.enemy().ability().getAllStatsReduction()) .concat(self.debuffs.getAllStatsReduction()) return s; }); // + % status resistance self.perkStr = ko.pureComputed(function () { return self.totalStr().total * constants.statusResPerStrength; }); // + % ms self.perkAgi = ko.pureComputed(function () { return self.totalAgi().total * constants.moveSpeedPerAgi; }); // + % magic resistance self.perkInt = ko.pureComputed(function () { return self.totalInt().total * constants.magicResPerInt; }); self.health = ko.pureComputed(function () { var s = new StatModel(self.heroData().statushealth, 'Base'); self.totalStr().components.forEach(function (component) { s.add(component.value * constants.healthPerStrength, component.label == 'Base' ? 'Base Str' : component.label); }); s.concat(self.inventory.getHealth()) .concat(self.ability().getHealth()) .concat(TalentController.getHealth(self.selectedTalents())) return s; }); // Health Regeneration = (Base + Sum of Flat Bonuses) * (1 + strength * (5/700)) self.healthregen = ko.pureComputed(function () { var healthRegenAura = [self.inventory.getHealthRegenAura, self.buffs.itemBuffs.getHealthRegenAura].reduce(function (memo, fn) { return fn(memo.sources, memo.excludeList); }, {sources: new StatModel(), excludeList: []}); var s = new StatModel(self.heroData().statushealthregen, 'Base'); if (!self.isIllusion()) { s.concat(self.inventory.getHealthRegen()) .concat(self.ability().getHealthRegen()) .concat(self.buffs.getHealthRegen()) .concat(TalentController.getHealthRegen(self.selectedTalents())) .concat(healthRegenAura.sources) } s.mult(1 + self.totalStr().total * constants.healthRegenPerStrength, 'Str Regen Amp', null, 'percent'); console.log('healthregen', s); return s; }); self.mana = ko.pureComputed(function () { var s = new StatModel(self.heroData().statusmana, 'Base'); self.totalInt().components.forEach(function (component) { s.add(component.value * constants.manaPerInt, component.label == 'Base' ? 'Base Int' : component.label); }); s.concat(self.inventory.getMana()) .concat(self.ability().getMana()) .concat(TalentController.getMana(self.selectedTalents())) return s; }); // Mana Regeneration = (Base + Sum of Flat Bonuses) * (1 + intelligence * 0.02) self.manaregen = ko.pureComputed(function () { var s = new StatModel(self.heroData().statusmanaregen, 'Base'); s.concat(self.inventory.getManaRegen()) .concat(self.inventory.getManaRegenBloodstone()) .concat(self.ability().getManaRegen()) .concat(TalentController.getManaRegen(self.selectedTalents())) if (self.heroId() == 'crystal_maiden') { s.concat(self.ability().getManaRegenSelfArcaneAura()) } else { s.concat(self.buffs.getManaRegenArcaneAura()) } s.concat(self.enemy().ability().getManaRegenReduction()) s.mult(1 + self.totalInt().total * constants.manaRegenPerInt, 'Mana Regen Amp', null, 'percent'); return s; }); self.totalArmorPhysical = ko.pureComputed(function () { var armorAura = [self.inventory.getArmorAura, self.buffs.itemBuffs.getArmorAura].reduce(function (memo, fn) { return fn(memo); }, null); var armorReduction = [self.enemy().inventory.getArmorReduction, self.debuffs.itemBuffs.getArmorReduction].reduce(function (memo, fn) { return fn(memo); }, null); var armorReductionAura = [self.enemy().inventory.getArmorReductionAura, self.debuffs.itemBuffs.getArmorReductionAura].reduce(function (memo, fn) { return fn(memo); }, null); var armorBaseReduction = self.enemy().ability().getArmorBaseReduction() * self.debuffs.getArmorBaseReduction(); var s = new StatModel(self.heroData().armorphysical, 'Base'); self.totalAgi().components.forEach(function (component) { s.add(component.value * constants.armorPerAgi, component.label == 'Base' ? 'Base Agi' : component.label); }); if (armorBaseReduction != 1) { s.mult(self.enemy().ability().getArmorBaseReduction() * self.debuffs.getArmorBaseReduction(), 'Base Armor Reduction %'); } if (!self.isIllusion()) { s.concat(self.inventory.getArmor()) .concat(self.ability().getArmor()) .concat(TalentController.getArmor(self.selectedTalents())) .concat(self.buffs.getArmor()) .concat(armorAura) .concat(armorReductionAura) } s.concat(self.enemy().ability().getArmorReduction()) .concat(self.debuffs.getArmorReduction()) .concat(armorReduction) return s; }); self.totalArmorPhysicalReduction = ko.pureComputed(function () { var totalArmor = self.totalArmorPhysical().total; return (constants.armorMult * totalArmor) / (1 + constants.armorMult * Math.abs(totalArmor)) }); self.spellAmp = ko.pureComputed(function () { var s = new StatModel(); self.totalInt().components.forEach(function (component) { s.add(component.value * constants.spellDmgPerInt, component.label == 'Base' ? 'Base Int' : component.label, null, 'percent'); }); s.concat(self.inventory.getSpellAmp()) .concat(self.ability().getSpellAmp()) .concat(TalentController.getSpellAmp(self.selectedTalents())) .concat(self.buffs.getSpellAmp()) return s; }); self.cooldownReductionFlat = ko.pureComputed(function () { return self.inventory.getCooldownReductionFlat() + self.ability().getCooldownReductionFlat() + TalentController.getCooldownReductionFlat(self.selectedTalents()) + self.buffs.getCooldownReductionFlat() - self.enemy().inventory.getCooldownIncreaseFlat() - self.enemy().ability().getCooldownIncreaseFlat() - self.debuffs.getCooldownIncreaseFlat() - self.debuffs.itemBuffs.getCooldownIncreaseFlat(); }); self.cooldownReductionProduct = ko.pureComputed(function () { return self.inventory.getCooldownReductionPercent().value * self.ability().getCooldownReductionPercent() * TalentController.getCooldownReductionPercent(self.selectedTalents()) * self.buffs.getCooldownReductionPercent() * self.enemy().inventory.getCooldownIncreasePercent() * self.enemy().ability().getCooldownIncreasePercent() * self.debuffs.getCooldownIncreasePercent() * self.debuffs.itemBuffs.getCooldownIncreasePercent(); }); self.cooldownReductionPercent = ko.pureComputed(function () { return 1 - self.cooldownReductionProduct(); }); self.totalMovementSpeed = ko.pureComputed(function () { var MIN_MOVESPEED = 100; var ms = (self.ability().setMovementSpeed() > 0 ? self.ability().setMovementSpeed() : self.buffs.setMovementSpeed()); if (ms > 0) { return ms; } else { var movementSpeedFlat = [self.inventory.getMovementSpeedFlat, self.buffs.itemBuffs.getMovementSpeedFlat].reduce(function (memo, fn) { var obj = fn(memo.excludeList); obj.value += memo.value; return obj; }, {value:0, excludeList:[]}); var movementSpeedPercent = [self.inventory.getMovementSpeedPercent, self.buffs.itemBuffs.getMovementSpeedPercent].reduce(function (memo, fn) { var obj = fn(memo.excludeList); obj.value += memo.value; return obj; }, {value:0, excludeList:[]}); var movementSpeedPercentReduction = [self.enemy().inventory.getMovementSpeedPercentReduction, self.debuffs.itemBuffs.getMovementSpeedPercentReduction].reduce(function (memo, fn) { var obj = fn(memo.excludeList); obj.value += memo.value; return obj; }, {value:0, excludeList:[]}); // If agility is a hero's primary attribute, every point in agility increases their movement speed by 0.06%. var agiMovementSpeedPercent = self.primaryAttribute() == 'agi' ? self.totalAgi().total * (0.0006) : 0; return Math.max( self.enemy().inventory.isSheeped() || self.debuffs.itemBuffs.isSheeped() ? 140 : (self.heroData().movementspeed + movementSpeedFlat.value + self.ability().getMovementSpeedFlat() + TalentController.getMovementSpeedFlat(self.selectedTalents())) * (1 //+ self.inventory.getMovementSpeedPercent() + movementSpeedPercent.value + agiMovementSpeedPercent + movementSpeedPercentReduction.value + self.ability().getMovementSpeedPercent() //+ self.enemy().inventory.getMovementSpeedPercentReduction() + self.enemy().ability().getMovementSpeedPercentReduction() + self.buffs.getMovementSpeedPercent() + self.debuffs.getMovementSpeedPercentReduction() + self.unit().ability().getMovementSpeedPercent() ) , MIN_MOVESPEED).toFixed(2); } }); self.totalTurnRate = ko.pureComputed(function () { return (self.heroData().movementturnrate * (1 + self.enemy().ability().getTurnRateReduction() + self.debuffs.getTurnRateReduction())).toFixed(2); }); self.baseDamage = ko.pureComputed(function () { var totalAttribute = self.totalAttribute(self.primaryAttribute()), abilityBaseDamage = self.ability().getBaseDamage(), minDamage = self.heroData().attackdamagemin, maxDamage = self.heroData().attackdamagemax; console.log('abilityBaseDamage.multiplier', abilityBaseDamage.multiplier); var multiplier = self.ability().getSelfBaseDamageReductionPct() * self.enemy().ability().getBaseDamageReductionPct() * self.debuffs.getBaseDamageReductionPct() * self.debuffs.itemBuffs.getBaseDamageReductionPct() * abilityBaseDamage.multiplier * (self.isIllusion() ? self.getOutgoingDamageMultiplier(self.illusionId(), false, self.heroData().attacktype) : 1); return [ Math.floor((minDamage + totalAttribute + abilityBaseDamage.total) * multiplier), Math.floor((maxDamage + totalAttribute + abilityBaseDamage.total) * multiplier) ]; }); self.baseDamageAvg = ko.pureComputed(function () { return (self.baseDamage()[0] + self.baseDamage()[1]) / 2; }); self.baseDamageMin = ko.pureComputed(function () { return self.baseDamage()[0]; }); self.baseDamageMax = ko.pureComputed(function () { return self.baseDamage()[1]; }); self.bonusDamage = ko.pureComputed(function () { return self.isIllusion() ? 0 : ((self.inventory.getBonusDamage().total + self.ability().getBonusDamage().total + TalentController.getBonusDamage(self.selectedTalents()).total + self.buffs.getBonusDamage().total + Math.floor((self.baseDamage()[0] + self.baseDamage()[1]) / 2 * (self.buffs.itemBuffs.getBonusDamagePercent(self.inventory.getBonusDamagePercent()).total + self.ability().getBonusDamagePercent().total + self.buffs.getBonusDamagePercent().total ) ) + Math.floor( (self.heroData().attacktype == 'DOTA_UNIT_CAP_RANGED_ATTACK' ? ((self.heroId() == 'drow_ranger') ? self.ability().getBonusDamagePrecisionAura().total[0] * self.totalAgi().total : self.buffs.getBonusDamagePrecisionAura().total[1]) : 0) ) + Math.floor( ((self.heroId() == 'riki') ? self.ability().getBonusDamageBackstab().total[0] * self.totalAgi().total : 0) ) ) * self.ability().getSelfBaseDamageReductionPct() * self.enemy().ability().getBaseDamageReductionPct() * self.debuffs.itemBuffs.getBaseDamageReductionPct()); }); self.bonusDamageReduction = ko.pureComputed(function () { return Math.abs(self.enemy().ability().getBonusDamageReduction() + self.debuffs.getBonusDamageReduction()); }); self.damageAvg = ko.pureComputed(function () { return (self.baseDamage()[0] + self.baseDamage()[1]) / 2 + self.bonusDamage(); }); self.damageMin = ko.pureComputed(function () { return self.baseDamage()[0] + self.bonusDamage(); }); self.damageMax = ko.pureComputed(function () { return self.baseDamage()[1] + self.bonusDamage(); }); self.damage = ko.pureComputed(function () { return [self.baseDamage()[0] + self.bonusDamage(), self.baseDamage()[1] + self.bonusDamage()]; }); self.totalStatusResistanceProduct = ko.pureComputed(function() { // If strength is a hero's primary attribute, every point in strength increases their status resistance by 0.15%. var strStatusResistance = self.primaryAttribute() == 'str' ? 1 - self.totalStr().total * (0.0015) : 1; return strStatusResistance; }); self.totalStatusResistance = ko.pureComputed(function () { return 1 - self.totalStatusResistanceProduct(); }); self.totalMagicResistanceProduct = ko.pureComputed(function () { //If intelligence is a hero's primary attribute, every point in intelligence increases their magic resistance by 0.15%. var intMagicResistance = self.primaryAttribute() == 'int' ? 1 + self.totalInt().total * (0.0015) : 1; return (1 - self.heroData().magicalresistance / 100) * (self.isIllusion() ? 1 : self.inventory.getMagicResist() * intMagicResistance * self.ability().getMagicResist() * TalentController.getMagicResist(self.selectedTalents()) * self.buffs.getMagicResist() * self.inventory.getMagicResistReductionSelf() * self.enemy().inventory.getMagicResistReduction() * self.enemy().ability().getMagicResistReduction() * self.debuffs.getMagicResistReduction() * self.debuffs.itemBuffs.getMagicResistReduction() ); }); self.totalMagicResistance = ko.pureComputed(function () { return 1 - self.totalMagicResistanceProduct(); }); self.bat = ko.pureComputed(function () { var abilityBAT = self.ability().getBAT(); if (abilityBAT > 0) { return abilityBAT; } return self.heroData().attackrate; }); self.ias = ko.pureComputed(function () { var attackSpeed = [self.inventory.getAttackSpeed].reduce(function (memo, fn) { var obj = fn(memo.excludeList); obj.value += memo.value; return obj; }, {value:0, excludeList:[]}); var attackSpeedAura = [self.inventory.getAttackSpeedAura, self.buffs.itemBuffs.getAttackSpeedAura].reduce(function (memo, fn) { var obj = fn(memo.excludeList); obj.value += memo.value; return obj; }, {value: 0, excludeList: []}); var attackSpeedReduction = [self.enemy().inventory.getAttackSpeedReduction, self.debuffs.itemBuffs.getAttackSpeedReduction].reduce(function (memo, fn) { var obj = fn(memo.excludeList); obj.value += memo.value; return obj; }, {value:0, excludeList: []}); var val = self.totalAgi().total //+ self.inventory.getAttackSpeed() + attackSpeed.value + attackSpeedAura.value + attackSpeedReduction.value //+ self.enemy().inventory.getAttackSpeedReduction() + self.ability().getAttackSpeed() + TalentController.getAttackSpeed(self.selectedTalents()) + self.enemy().ability().getAttackSpeedReduction() + self.buffs.getAttackSpeed() + self.debuffs.getAttackSpeedReduction() + self.unit().ability().getAttackSpeed(); if (val < -80) { return -80; } else if (val > 500) { return 500; } return val.toFixed(2); }); self.attackTime = ko.pureComputed(function () { return (self.bat() / (1 + self.ias() / 100)).toFixed(2); }); self.attacksPerSecond = ko.pureComputed(function () { return ((1 + self.ias() / 100) / self.bat()).toFixed(2); }); self.totalAccuracyProduct = ko.pureComputed(function () { var accuracySources = self.inventory.getAccuracySource(self.heroData().attacktype); extend(accuracySources, self.enemy().debuffs.itemBuffs.getAccuracyDebuffSource()); var accuracySourcesArray = []; for (var prop in accuracySources) { var el = accuracySources[prop]; el.name = prop accuracySourcesArray.push(el); } return accuracySourcesArray.reduce(function (memo, source) { return memo * Math.pow((1 - source.chance), source.count) }, 1); }); self.accuracy = ko.pureComputed(function () { return 1 - self.totalAccuracyProduct(); }); self.totalEvasionProduct = ko.pureComputed(function () { return self.inventory.getEvasion() * self.ability().getEvasion() * self.ability().getEvasionBacktrack() * TalentController.getEvasion(self.selectedTalents()) * self.buffs.itemBuffs.getEvasion() }); self.evasion = ko.pureComputed(function () { if (self.enemy().inventory.isSheeped() || self.debuffs.itemBuffs.isSheeped()) return 0; return 1 - self.totalEvasionProduct(); }); self.ehpPhysical = ko.pureComputed(function () { var evasion = self.enemy().inventory.isSheeped() || self.debuffs.itemBuffs.isSheeped() ? 1 : self.inventory.getEvasion() * self.ability().getEvasion() * self.buffs.itemBuffs.getEvasion(); var ehp = self.health().total / (1 - self.totalArmorPhysicalReduction()); ehp /= (1 - (1 - (evasion * self.ability().getEvasionBacktrack()))); ehp /= (1 - parseFloat(self.enemy().missChance()) / 100); ehp *= (self.inventory.activeItems().some(function (item) {return item.item == 'mask_of_madness';}) ? (1 / 1.3) : 1); ehp *= (1 / self.ability().getDamageReduction()); ehp *= (1 / self.buffs.getDamageReduction()); ehp *= (1 / self.enemy().ability().getDamageAmplification()); ehp *= (1 / self.debuffs.getDamageAmplification()); if (self.isIllusion()) ehp *= (1 / self.getIncomingDamageMultiplier(self.illusionId(), false, self.heroData().attacktype)); return ehp.toFixed(2); }); self.ehpMagical = ko.pureComputed(function () { var ehp = self.health().total / self.totalMagicResistanceProduct(); ehp *= (self.inventory.activeItems().some(function (item) {return item.item == 'mask_of_madness';}) ? (1 / 1.3) : 1); ehp *= (1 / self.ability().getDamageReduction()); ehp *= (1 / self.buffs.getDamageReduction()); ehp *= (1 / self.ability().getEvasionBacktrack()); ehp *= (1 / self.enemy().ability().getDamageAmplification()); ehp *= (1 / self.debuffs.getDamageAmplification()); if (self.isIllusion()) ehp *= (1 / self.getIncomingDamageMultiplier(self.illusionId(), false, self.heroData().attacktype)); return ehp.toFixed(2); }); self.bash = ko.pureComputed(function () { var attacktype = self.heroData().attacktype; return 1 - self.inventory.getBash(attacktype) * self.ability().getBash(); }); self.critChance = ko.pureComputed(function () { return 1 - self.inventory.getCritChance() * self.ability().getCritChance(); }); HeroDamageMixin(self, itemData); self.missChance = ko.pureComputed(function () { var blindDebuff = [self.enemy().inventory.getBlindSource, self.debuffs.itemBuffs.getBlindSource].reduce(function (memo, fn) { var obj = fn(memo.excludeList); obj.total += memo.total; return obj; }, {total:0, excludeList:[]}); var blind = 1 - Math.min(self.enemy().ability().getBlindSource().total + self.debuffs.getBlindSource().total + blindDebuff.total, 1); return 1 - self.enemy().totalEvasionProduct() * blind; }); self.hitChance = ko.pureComputed(function () { return 1 - (parseFloat(self.missChance())/100) * (1 - parseFloat(self.accuracy())/100); }); self.totalattackrange = ko.pureComputed(function () { var attacktype = self.heroData().attacktype; return self.heroData().attackrange + self.ability().getAttackRange() + TalentController.getAttackRange(self.selectedTalents()) + self.inventory.getAttackRange(attacktype).value; }); self.visionrangeday = ko.pureComputed(function () { return (self.heroData().visiondaytimerange) * (1 + self.enemy().ability().getVisionRangePctReduction() + self.debuffs.getVisionRangePctReduction()); }); self.visionrangenight = ko.pureComputed(function () { return (self.heroData().visionnighttimerange + self.inventory.getVisionRangeNight() + self.ability().getVisionRangeNight()) * (1 + self.enemy().ability().getVisionRangePctReduction() + self.debuffs.getVisionRangePctReduction()); }); self.lifesteal = ko.pureComputed(function () { var total = self.inventory.getLifesteal() + self.ability().getLifesteal() + TalentController.getLifesteal(self.selectedTalents()) + self.buffs.getLifesteal(); if (self.heroData().attacktype == 'DOTA_UNIT_CAP_MELEE_ATTACK') { var lifestealAura = [self.inventory.getLifestealAura, self.buffs.itemBuffs.getLifestealAura].reduce(function (memo, fn) { var obj = fn(memo.excludeList); obj.value += memo.value; return obj; }, {value: 0, excludeList: []}); total += lifestealAura.value; } return total/100; }); self.diffProperties = diffProperties; self.diff = {}; self.diff2 = {}; for (var i = 0; i < self.diffProperties.length; i++) { var index = i; self.diff[self.diffProperties[index]] = self.getDiffFunction(self.diffProperties[index]); self.diff2[self.diffProperties[index]] = self.getDiffFunction2(self.diffProperties[index]); } }; HeroModel.prototype.getDiffFunction = function (prop) { var self = this; return ko.pureComputed(function () { if (prop == 'baseDamage') { return [self[prop]()[0] - self.heroCompare()[prop]()[0], self[prop]()[1] - self.heroCompare()[prop]()[1]]; } else { return self[prop]() - self.heroCompare()[prop](); } }, this, { deferEvaluation: true }); } HeroModel.prototype.getDiffFunction2 = function (prop) { var self = this; return ko.pureComputed(function () { if (prop == 'baseDamage') { return [self[prop]()[0] - self.heroCompare()[prop]()[0], self[prop]()[1] - self.heroCompare()[prop]()[1]]; } else { return self[prop]().total - self.heroCompare()[prop]().total; } }, this, { deferEvaluation: true }); } HeroModel.prototype.getAbilityLevelMax = function (data) { if (data.abilitytype === 'DOTA_ABILITY_TYPE_ATTRIBUTES') { return 1; } else if (data.name === 'invoker_quas' || data.name === 'invoker_wex' || data.name === 'invoker_exort') { return 7; } else if (data.name === 'invoker_invoke') { return 1; } else if (data.name === 'earth_spirit_stone_caller' || data.name === 'ogre_magi_unrefined_fireblast' || data.name === 'monkey_king_mischief') { return 1; } else if (data.abilitytype === 'DOTA_ABILITY_TYPE_ULTIMATE' || data.name === 'keeper_of_the_light_recall' || data.name === 'keeper_of_the_light_blinding_light' || data.name === 'ember_spirit_activate_fire_remnant' || data.name === 'lone_druid_true_form_battle_cry') { return 3; } else if (data.name === 'puck_ethereal_jaunt' || data.name === 'shadow_demon_shadow_poison_release' || data.name === 'templar_assassin_trap' || data.name === 'spectre_reality') { return 0; } else if (data.name === 'invoker_cold_snap' || data.name === 'invoker_ghost_walk' || data.name === 'invoker_tornado' || data.name === 'invoker_emp' || data.name === 'invoker_alacrity' || data.name === 'invoker_chaos_meteor' || data.name === 'invoker_sun_strike' || data.name === 'invoker_forge_spirit' || data.name === 'invoker_ice_wall' || data.name === 'invoker_deafening_blast') { return 0; } else if (data.name === 'techies_minefield_sign' || data.name === 'techies_focused_detonate') { return 0; } else { return 4; } }; HeroModel.prototype.toggleTalent = function (talentTier, talentIndex) { if (this.talents[talentTier]() === talentIndex) { this.talents[talentTier](-1); } else if (this.availableSkillPoints() > 0 || this.talents[talentTier]() == 1 - talentIndex) { if (parseInt(this.selectedHeroLevel()) >= talentTier * 5 + 10) { this.talents[talentTier](talentIndex); } } } module.exports = HeroModel;import React, { Component } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' //import styles from '../../_styles/_bulma_variables.sass' import { UbuntuIcon } from '../../_components/_UbuntuIcon' import { Flip } from '../../_components/_Flip' let technologies = [ "react","node", "js-square", "docker", "linux", "git","html5","css3-alt","sass" ] class Technologies extends Component { render() { let renderTechnologies = technologies.map((tech)=>{ let spin = false if(tech==="react"){ spin=true } return ( <div className="column is-mobile has-text-centered fadeIn " key={tech} > <Flip> <FontAwesomeIcon spin={spin} size="3x" icon={['fab', tech]} color="white" /> </Flip> </div> ) }) return ( <article className="tile is-child box is-dark"> <nav className="columns is-mobile is-multiline fadeIn"> { renderTechnologies } <div className="column is-mobile has-text-centered"> <Flip> <UbuntuIcon /> </Flip> </div> </nav> </article> ); } } export { Technologies } <gh_stars>0 import {connect} from 'react-redux'; import AnnotationRegister from '../views/AnnotationRegister'; const mapStateToProps = (state, ownProps) => ({ error: state.error }); const mapDispatchToProps = dispatch => ({ // registerPoint(imageId, rateCoordinates) { // dispatch(registerPoint(imageId, rateCoordinates)); // }, // deletePoint(imageId, pointId) { // dispatch(deletePoint(imageId, pointId)); // } }); export default connect(mapStateToProps, mapDispatchToProps)(AnnotationRegister); const path = require('path') const qs = require('querystring') const { md5, removeExt, getPlatformExts } = require('@dcloudio/uni-cli-shared') const { cacheTemplate, cacheCompilerOptions, getPlatformTarget } = require('./shared') const templateExt = getPlatformExts().template module.exports = function (content) { if (process.env.UNI_USING_COMPONENTS) { return require('./template-new').call(this, content) } this.cacheable && this.cacheable() const realResourcePath = path.relative(process.env.UNI_INPUT_DIR, this.resourcePath) if (process.env.UNI_USING_COMPONENTS) { // 向 uni-template-compier 传递 emitFile const vueLoaderOptions = this.loaders.find(loader => loader.ident === 'vue-loader-options') if (vueLoaderOptions) { Object.assign(vueLoaderOptions.options.compilerOptions, { resourcePath: removeExt(realResourcePath) + templateExt, emitFile: this.emitFile }) } else { throw new Error('vue-loader-options parse error') } } else { if (!content.trim()) { content = '<view></view>' } cacheTemplate(realResourcePath, content) const query = qs.parse(this.resourceQuery.slice(1)) const { id } = query const compilerOptions = { scopeId: query.scoped ? `data-v-${id}` : null, target: getPlatformTarget(), md5: md5(content.trim() + process.env.UNI_PLATFORM), realResourcePath } cacheCompilerOptions(realResourcePath, compilerOptions) // 向 vue-loader templateLoader 传递 compilerOptions const vueLoaderOptions = this.loaders.find(loader => loader.ident === 'vue-loader-options') if (vueLoaderOptions) { Object.assign(vueLoaderOptions.options.compilerOptions, compilerOptions) } else { throw new Error('vue-loader-options parse error') } } return content } 'use strict'; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } var fs = require('fs'); var join = require('path').join; module.exports = function (cli) { cli.debug('start db', cli.args); if (fs.existsSync(cli.apiDir) && fs.existsSync(cli.feDir) || fs.existsSync('.seedsrc')) { cli.debug('We\'re in a Seeds app.'); var command = join(cli.apiDir, 'node_modules', '.bin', 'sails-migrations'); var dbCommands = new Map([['create', 'db:create'], ['drop', 'db:drop'], ['migrate', 'migrate'], ['rollback', 'rollback'], ['status', 'status'], ['generate', 'generate']]); var additionalParams = [].concat(_toConsumableArray(cli.args.slice(2))); cli.runExternalCommand(command, [dbCommands.get(cli.args[1])].concat(_toConsumableArray(additionalParams)), { cwd: cli.apiDir }); } else { cli.error('You must be in a Seeds application to run the db command.'); } };angular.module('cv') .service('firebaseService', function ($firebase, $firebaseObject, $firebaseArray) { var firebaseUrl = 'https://burrfamilyfarm.firebaseio.com/'; this.getGoats = function() { return $firebaseArray(new Firebase(firebaseUrl + 'goats')); }; this.getCart = function() { return $firebaseArray(new Firebase(firebaseUrl + 'cart')); }; })<filename>designs/02/design02.js /** contains the javascript methods that are design specific */ var lastSelectedButtonId; var lastLogoName; var themes = { "default":["#1ADFEF","#16C0CE"], "grey":["silver","grey"], "mensa":["#0099FF","#E5F4FF"], "vasttrafik":["#00AEEC","#E5F4FF"], "gbg":["#1b78cc","#E5F4FF"], "green":["#118F99","#16C0CE"], "yellow":["#E6A335","#FFEC82"] }; var sunDegrees = 0; function populateMenu(mnuRows) { populateSubMenu(mnuRows); /* $("#menu").html(""); for (var i = 0; i< mnuRows.length; i++){ var mnuRow = mnuRows[i]; var html="<div class='btnBigSun' id='"+mnuRow["id"]+"' href='#"+mnuRow["id"]+"' title='"+mnuRow["label"]+"'>"+mnuRow["label"]+"</div>\n"; $("#menu").append(html); $("#"+mnuRow["id"]).hide().fadeIn(200+100*i); $("#"+mnuRow["id"]).click(mnuRow["function"]); //setTimeout(function() {$("#"+mnuRow["id"]).fadeIn();}, 100*i); } */ } function doWindowResize() { var w = $(this).width(); var gbgH = (373/1959)*$("#goteborg").width(); if (gbgH>100) gbgH=100; $("#goteborg").height(gbgH); } function menuClose(btnId) { $("#"+lastSelectedButtonId).removeClass("selected"); if (btnId!==undefined) { $("#"+btnId).addClass("selected"); lastSelectedButtonId=btnId; } // $("#menu").fadeOut(); } function initDesign() { changeTheme("green"); $("#bottom-content").animate({bottom: "10px"}, 3000); // setTimeout(rotateSun, 100); } function changeTheme(theme) { var colors = themes[theme]; if (colors) { $("body").animate({'backgroundColor': colors[0]}, 1000); $("#bkgplate").animate({'backgroundColor': colors[1]}, 1000); $(".button").animate({'border-color': colors[0]}, 500); //$(".button.selected").animate({backgroundColor: colors[1]}, 500); $('.title').animate({'color': colors[0]}, 500); $('head').append('<style>.button {border-color:'+colors[0]+'} .button:hover {background-color: '+colors[0]+';}</style>'); } } function changeLogo(name) { if (name!==lastLogoName) { $('#logo').fadeOut(); var html="<img src='images/glenn/"+name+".png' >"; setTimeout(function() {$('#logo').html(html).fadeIn(500)}, 500); lastLogoName = name; } } function rotateSun() { sunDegrees+=.2; $("#sol1").css("transform", "rotate("+sunDegrees+"deg)"); $("#sol2").css("transform", "rotate("+(0-sunDegrees)+"deg)"); setTimeout(rotateSun, 200); }import ContainerJS from "container-js" import ContainerFactory from "../../../utils/test-container-factory" import AgentSettingBuilder from "src/viewmodel/agents/agent-setting-builder" describe("AgentSettingBuilder", () => { var target; var xhrManager; beforeEach(() => { let container = new ContainerFactory().createContainer(); let d = container.get("agentClasses"); const agentClasses = ContainerJS.utils.Deferred.unpack(d); let d2 = container.get("icons"); const icons = ContainerJS.utils.Deferred.unpack(d2); target = new AgentSettingBuilder(agentClasses, icons); xhrManager = agentClasses.agentService.xhrManager; target.initialize(); xhrManager.requests[0].resolve([ {id:1} ]); xhrManager.requests[1].resolve([ {name:"TestClassA@あ", description:"aaa"}, {name:"TestClassB@あ", description:"bbb"}, {name:"TestClassC@い", description:"ccc"} ]); xhrManager.clear(); }); it("initializeで状態を初期化できる", () => { expect(target.agentSetting).toEqual([]); expect(target.agentClasses.classes.length).toEqual(3); }); it("エージェントを追加できる", () => { target.addAgent("TestClassA@あ"); expect(target.selectedAgent).toEqual( {agentClass:"TestClassA@あ", agentName:"TestClassA@あ", properties: {}}); target.addAgent("TestClassA@あ", {a:"aa"}); expect(target.selectedAgent).toEqual( {agentClass:"TestClassA@あ", agentName:"TestClassA@あ", properties: {a:"aa"}}); target.addAgent("TestClassC@い", {b:"bb"}); expect(target.selectedAgent).toEqual( {agentClass:"TestClassC@い", agentName:"TestClassC@い", properties: {b:"bb"}}); expect(target.agentSetting).toEqual([ {agentClass:"TestClassA@あ", agentName:"TestClassA@あ", properties: {}}, {agentClass:"TestClassA@あ", agentName:"TestClassA@あ", properties: {a:"aa"}}, {agentClass:"TestClassC@い", agentName:"TestClassC@い", properties: {b:"bb"}} ]); }); it("エージェントを削除できる", () => { target.addAgent("TestClassA@あ"); target.addAgent("TestClassA@あ", {a:"aa"}); target.addAgent("TestClassC@い", {b:"bb"}); target.selectedAgent = target.agentSetting[1]; target.removeSelectedAgent(); expect(target.agentSetting).toEqual([ {agentClass:"TestClassA@あ", agentName:"TestClassA@あ", properties: {}}, {agentClass:"TestClassC@い", agentName:"TestClassC@い", properties: {b:"bb"}} ]); expect(target.selectedAgent).toEqual(null); target.selectedAgent = target.agentSetting[0]; target.removeSelectedAgent(); expect(target.agentSetting).toEqual([ {agentClass:"TestClassC@い", agentName:"TestClassC@い", properties: {b:"bb"}} ]); expect(target.selectedAgent).toEqual(null); target.selectedAgent = target.agentSetting[0]; target.removeSelectedAgent(); expect(target.selectedAgent).toEqual(null); }); it("エージェントのプロパティを更新できる", () => { target.addAgent("TestClassA@あ"); target.addAgent("TestClassA@あ", {a:"aa"}); target.addAgent("TestClassC@い", {b:"bb"}); target.selectedAgent = target.agentSetting[1]; target.updateSelectedAgent("テスト", "aaa", {c:"cc"}); target.selectedAgent = target.agentSetting[0]; target.updateSelectedAgent("", null, {a:"aa"}); expect(target.agentSetting).toEqual([ {agentClass:"TestClassA@あ", agentName: "", iconId: null, properties: {a:"aa"}}, {agentClass:"TestClassA@あ", agentName: "テスト", iconId: "aaa", properties: {c:"cc"}}, {agentClass:"TestClassC@い", agentName: "TestClassC@い", properties: {b:"bb"}} ]); }); it("getAgentClassでエージェントの定義を取得できる", () => { target.addAgent("TestClassA@あ"); target.addAgent("TestClassC@い", {b:"bb"}); target.selectedAgent = target.agentSetting[0]; expect(target.getAgentClassForSelected()).toEqual( {name:"TestClassA@あ", description:"aaa"}); target.selectedAgent = target.agentSetting[1]; expect(target.getAgentClassForSelected()).toEqual( {name:"TestClassC@い", description:"ccc"}); }); }); <reponame>emiledelmas/vkshub<filename>staticfiles/robert_bus/app.js function go(stop, direction0) { let doc; let direct; if(direction0 == "<NAME>'ERMONT-EAUBONNE (Ermont)") { doc = "back"; direct = "Enghien"; } else if (direction0 == "<NAME>'ENGHIEN-LES-BAINS (Enghien-les-Bains)") { doc = "go"; direct = "Ermont"; } let date = new Date(); let currentMinutes = date.getMinutes(); let depart = localStorage.getItem(stop + direct); if (depart == null) { return goBackOnline(stop, direction0); } let timeLeft = parseInt(depart.slice(11, 13)); if (timeLeft < currentMinutes){ timeLeft = 60 - currentMinutes + timeLeft ; } else { timeLeft = timeLeft - currentMinutes; } return document.getElementById(doc).innerHTML = "<strong>"+depart.slice(9,11)+"h"+depart.slice(11,13)+"</strong> dans <strong>"+timeLeft+"</strong> minutes !</p>"; } function save(stop) { var scheduleN = []; var scheduleT = []; let request = 'https://opendata.stif.info/service/api-stif-horaires/stop_areas/'+stop+'/lines/line%3A0%3A016096001%3A14/departures?count=200&apikey=<KEY>'; console.log(request); fetch(request) .then(response => { return response.json() }) .then(data => { let time; let i = 0; let y = 0; let direction; let depart; let date = new Date(); let currentMinutes = date.getMinutes(); while (y === 0) { direction = data['departures'][i]['display_informations']['direction']; if (direction === "GARE D'ENGHIEN-LES-BAINS (Enghien-les-Bains)") { scheduleN.push(data['departures'][i]['stop_date_time']['arrival_date_time']); } else if (direction === "GARE D'ERMONT-EAUBONNE (Ermont)") { scheduleT.push(data['departures'][i]['stop_date_time']['arrival_date_time']); } i++; if(i > 100) { y++; } } localStorage.setItem(stop+'Ermont', scheduleT); localStorage.setItem(stop+'Enghien', scheduleN); return null ; }) .catch(err => { console.log("error"); }) } function goBackOnline(stop, direction0) { let doc; if(direction0 == "GARE D'ERMONT-EAUBONNE (Ermont)") { doc = "back"; } else if (direction0 == "GARE D'ENGHIEN-LES-BAINS (Enghien-les-Bains)") { doc = "go"; } let request = 'https://opendata.stif.info/service/api-stif-horaires/stop_areas/'+stop+'/lines/line%3A0%3A016096001%3A14/departures?count=5&apikey=<KEY>'; console.log(request); fetch(request) .then(response => { return response.json() }) .then(data => { // Work with JSON data here let timeLeft; let i = 0; let y = 0; let direction; let depart; let date = new Date(); let currentMinutes = date.getMinutes(); while (y === 0) { direction = data['departures'][i]['display_informations']['direction']; if (direction === direction0) { depart = data['departures'][i]['stop_date_time']['arrival_date_time']; y++; } else { i++; } } timeLeft = parseInt(depart.slice(11, 13)); if (timeLeft < currentMinutes){ timeLeft = 60 - currentMinutes + timeLeft ; } else { timeLeft = timeLeft - currentMinutes; } return document.getElementById(doc).innerHTML = "<strong>"+depart.slice(9,11)+"h"+depart.slice(11,13)+"</strong> dans <strong>"+timeLeft+"</strong> minutes !"; }) .catch(err => { return document.getElementById(doc).innerHTML = "Aucunes infos."; }) } function accurate(stop, direction0) { let doc; let direct; if(direction0 == "<NAME> (Ermont)") { doc = "back"; direct = "A"; } if (direction0 == "<NAME> (Enghien-les-Bains)") { doc = "go"; direct = "R"; } let request = "https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=016096001%3A14&stop_point_id="+stop+"&apikey=103bd4c9f914fdd20ee0c4367c84630d52260ff00a81694c36cec7b2"; console.log(request); fetch(request) .then(response => { return response.json() }) .then(data => { let sched = []; for (let i=0; i<4; i++) { if (data[i]['sens'] === direct){ sched.push(data[i]['time']); } } return document.getElementById(doc).innerHTML = "Prochains : <strong>"+sched[0]+"</strong> et <strong>"+sched[1]+"</strong> minutes !"; }) .catch(err => { console.log(err); }) } const fs = require('fs'), path = require('path'), utils = require('../utils'); const getAccountByName = name => { const userData = fs.readFileSync(path.join(__dirname, '../accounts.json'), { encoding: 'utf-8' }); const user = JSON.parse(userData).filter(user => user.name === name)[0]; return user; }; const saveAccountData = (id, data) => { const dir = utils.getUserDataDirectory(id); fs.writeFileSync(dir, data); }; const getAccountData = id => { const dir = utils.getUserDataDirectory(id); const data = fs.readFileSync(dir, { encoding: 'utf-8' }); return JSON.parse(data); }; module.exports = { getAccountByName, saveAccountData, getAccountData }; <gh_stars>0 function preload() { // Parallax Background imageGameBackground_1 = loadImage('imagens/cenario/sky.png'); imageGameBackground_2 = loadImage('imagens/cenario/bg_decor.png'); imageGameBackground_3 = loadImage('imagens/cenario/middle_decor.png'); imageGameBackground_4 = loadImage('imagens/cenario/foreground.png'); imageGameBackground_5 = loadImage('imagens/cenario/ground.png'); // Parallax Background //imagemCenario = loadImage('imagens/cenario/floresta.png'); imagemGameOver = loadImage('imagens/assets/game-over.png'); imagemPersonagem = loadImage('imagens/personagem/correndo.png'); imagemInimigo = loadImage('imagens/inimigos/gotinha.png'); imagemInimigoVoador = loadImage('imagens/inimigos/gotinha-voadora.png'); imagemInimigoGrande = loadImage('imagens/inimigos/troll.png'); imagemTelaInicial = loadImage('imagens/cenario/telaInicial.png'); imagemVida = loadImage('imagens/assets/heart.png'); fonteTelaInicial = loadFont('imagens/assets/fonteTelaInicial.otf'); fita = loadJSON('fita/fita.json') somDoJogo = loadSound('sons/trilha_jogo.mp3'); somDoPulo = loadSound('sons/somPulo.mp3'); }define(["../../../polymer/polymer-legacy.js", "../../../polymer/lib/legacy/polymer-fn.js", "../../../polymer/lib/utils/html-tag.js"], function (_polymerLegacy, _polymerFn, _htmlTag) { "use strict"; var _templateObject_0cc34810942811ecb1937969798b231a; (0, _polymerFn.Polymer)({ _template: (0, _htmlTag.html)(_templateObject_0cc34810942811ecb1937969798b231a || (_templateObject_0cc34810942811ecb1937969798b231a = babelHelpers.taggedTemplateLiteral(["\n <style>\n :host {\n font-style: italic;\n font-size: 0.85em;\n font-weight: 200;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n color: #fff;\n }\n </style>\n <span>Route prefix: {{route.prefix}} \xB7 Route path: {{route.path}} \xB7 Query params: {{_stringifyQueryParams(route.__queryParams.*)}}</span>\n"]))), is: 'route-info', properties: { route: { type: Object } }, _stringifyQueryParams: function _stringifyQueryParams() { var params = []; if (this.route && this.route.__queryParams) { for (var key in this.route.__queryParams) { params.push(key + ' = ' + this.route.__queryParams[key]); } } return params.join(', '); } }); });import Utils from "./../../libs/utils.js"; class InfoPopupComponent extends HTMLElement { componentParams = { popupType: '', isVisible: false } constructor() { super(); } getTemplate() { const TEMPLATE_LOCKED = `<div id="info-popup" class="popup-info"> <span class="popup-info__text">Unlocked on a block-by-block basis</span> <img class="popup-info__icon" id="popup-info-lock-cancel" src="./icons/icon-cancel-info.svg" /> </div>`; const TEMPLATE_AVAIL = `<div id="info-popup" class="popup-info"> <span class="popup-info__text">Unlocked but not distributed yet</span> <img class="popup-info__icon" id="popup-info-avail-cancel" src="./icons/icon-cancel-info.svg" /> </div>`; const TEMPLATE_KEY = `<div id="info-popup" class="popup-info"> <span class="popup-info__text">The key is used as an identifier <br>on the BeamX blockchain</span> <img class="popup-info__icon" id="popup-info-key-cancel" src="./icons/icon-cancel-info.svg" /> </div>`; const TEMPLATE_WEEKLY = `<div id="info-popup" class="popup-info weekly"> <div class="info-popup-content"> <span class="popup-info__text">The longer you stake for, the higher the reward is</span> <img class="popup-info__icon" id="popup-info-weekly-cancel" src="./icons/icon-cancel-info.svg" /> </div> <div class="info-popup__separator"></div> <div class="info-popup__rewards"> <div class="info-popup__rewards__titles"> <div class="info-popup-rew-title">Period</div> <div class="info-popup-rew-title">Reward (weekly)</div> </div> <div class="info-popup__rewards__weekly"> <div class="info-popup-rew-value">1 week</div> <div class="info-popup-rew-value">1%</div> </div> <div class="info-popup__rewards__month"> <div class="info-popup-rew-value">1 month</div> <div class="info-popup-rew-value">2%</div> </div> </div> </div>`; if (this.componentParams.popupType.length > 0) { if (this.componentParams.popupType === 'avail') { return TEMPLATE_AVAIL; } else if (this.componentParams.popupType === 'locked') { return TEMPLATE_LOCKED; } else if (this.componentParams.popupType === 'key') { return TEMPLATE_KEY; } else if (this.componentParams.popupType === 'weekly') { return TEMPLATE_WEEKLY; } } else { return ''; } } render() { this.innerHTML = this.getTemplate(); $(this).show(); this.componentParams.isVisible = true; $(window).click((ev) => { if (this.componentParams.isVisible) { $(this).hide(); } ev.stopPropagation(); }); $('#popup-info-lock-cancel').click(() => { $('#locked-info-popup').hide(); this.componentParams.isVisible = false; }); $('#popup-info-avail-cancel').click(() => { $('#avail-info-popup').hide(); this.componentParams.isVisible = false; }); $('#popup-info-key-cancel').click((ev) => { ev.stopPropagation(); $('#key-info-popup').hide(); this.componentParams.isVisible = false; }); $('#popup-info-weekly-cancel').click((ev) => { $('#weekly-info-popup').hide(); this.componentParams.isVisible = false; }); $(this).click((ev) => { ev.stopPropagation(); }); }; connectedCallback() { this.render(); } attributeChangedCallback(name, oldValue, newValue) { if (name === 'type') { this.componentParams.popupType = newValue; } this.render(); } static get observedAttributes() { return ['type']; } } customElements.define('info-popup-component', InfoPopupComponent); import React, { Component} from 'react' import { connect } from 'react-redux' import { NavLink, withRouter } from 'react-router-dom' import PropTypes from 'prop-types' class QuestionIntro extends Component { toQuestion = (e, question_id) => { e.preventDefault() //this.props.history.push(`/questions/${question_id}`) //console.log(this.props.location.state) } render() { const {question} = this.props const{user} = this.props if (question === null){ return <p>This Question doesn't exist</p> } const { id, optionOne, } = question const { name, avatarURL} = user return( <div className="container" style={{maxWidth:'100%', marginTop:'50px',}}> <div className="card"> <div className="card-header has-background-info" style={{padding:'10px'}}> <h3 className="subtitle is-4 has-text-white">{name} asks :</h3> </div> <div className="card-content"> <div className="media" > <div className="media-left" style={{width:'30%', marginRight:'50px', }}> <figure className="image is-center" style={{marginTop:'0%' }}> <img src={avatarURL} alt={user.name}/> </figure> </div> <div className="media-content " style={{marginTop:'0%', height:'200px'}}> <p className="title is-3">Would you rather...</p> <p className="is-medium" style={{marginBottom:'25px',marginTop:'25px'}}>---{optionOne.text }---</p> <NavLink to={`/questions/${id}`} exact className="navbar-item" activeClassName='active'> <button className="button is-medium is-fullwidth is-info is-outlined" style={{marginBottom:'0px'}} /*onClick={(e) => this.toQuestion(e, id)}*/ >View Poll</button> </NavLink> </div> </div> </div> </div> </div> ) } } QuestionIntro.propTypes = { question: PropTypes.object.isRequired, user: PropTypes.object.isRequired, } function mapStateToProps ({questions, users}, { id }) { const question = questions[id] const user = users[question.author] return { question, user, } } export default withRouter(connect(mapStateToProps)(QuestionIntro))const express = require("express"), router = express.Router(), passport = require("passport"), Cust = require("../model/cust"), bcrypt = require("bcryptjs"); //Show login form router.get("/login",(req,res)=>{ res.render("cust/login"); }) //Login logic router.post("/login", (req,res,next)=>{ passport.authenticate("local",{ successRedirect : "/", failureRedirect : "/cust/login", failureFlash : true })(req,res,next); }) //Show register form router.get("/register",(req,res)=>{ res.render("cust/register"); }) //Register logic router.post("/register", (req,res)=>{ let errors = []; const { name , email,phone, password, <PASSWORD> } = req.body; //Check all fields are filled or not if(!name, !email, !phone, ! password, !password2){ errors.push({msg: "All fields must be filled"}) } //Check password match if(password!=<PASSWORD>){ errors.push({msg: "Password does not match"}) } //Check length if(password.lenght<6){ errors.push({msg:"Password must be atleast 6 characters long"}) } //check errors if(errors.length>0){ res.render("cust/register",{ errors, name, phone, email }) } else{ //No errors Cust.findOne({email:email}) .then(cust=>{ //User exists if(cust){ errors.push({msg:"User Already exists"}) res.render("cust/register",{ errors, name, phone, email }) }else{ //New User const newCust = new Cust({ name, email, password, phone }); //Hash password bcrypt.genSalt(10,(err,salt)=>{ bcrypt.hash(newCust.password,salt, (err,hash)=>{ if(err) throw err; //Set password to hash newCust.password = hash; newCust.save(); req.flash("success_msg","You are now registered and can log in !!"); res.redirect("/cust/login"); }) }); } }).catch(err=>res.render("cust/register",{ msg: "Something went wrong"})) } }) //logout router.get("/logout",(req,res)=>{ req.logout(); req.flash("success_msg","You have logged out"); res.redirect("/cust/login") }) //dashboard router.get("/dashboard/:id",isLoggedIn, (req,res)=>{ Cust.findById(req.params.id) .populate({path: 'cabs', options:{sort : {'created_at': 1}}}).exec((err,foundCust)=>{ if(err) throw err; res.render("cust/dashboard",{cust:foundCust}); }) }) function isLoggedIn(req,res,next){ if(req.isAuthenticated()){ return next(); } req.flash("error_msg","You must be logged in!") res.redirect("/cust/login"); } module.exports = router//var contract = artifacts.require("contract.sol"); var TCI_admin = artifacts.require("TCI_admin.sol"); var TCI_client = artifacts.require("TCI_client.sol"); module.exports = function(deployer) { deployer.deploy(TCI_admin); deployer.link(TCI_admin,TCI_client); deployer.deploy(TCI_client); }; const { Command } = require('@oclif/command'); const fs = require('fs'); const execa = require('execa'); const { HOOK_PATH, REMOTE_NAME } = require('../constants'); const getMessage = (hasRemote, hasHook) => { let message = 'This project is'; if (!hasRemote && !hasHook) { message += ' not configured'; } else { message += ' configured as'; if (hasRemote) message += ' a source'; if (hasRemote && hasHook) message += ' and'; if (hasHook) message += ' a target'; } message += '.'; return message; }; class StatusCommand extends Command { async run() { const hasRemote = await execa('git', ['remote', 'get-url', REMOTE_NAME]) .then(() => true) .catch(() => false); const hasHook = fs.existsSync(HOOK_PATH); console.log(getMessage(hasRemote, hasHook)); } } StatusCommand.description = `print the configuration status Prints whether the project has been configured as a source, a target, or both.`; module.exports = StatusCommand; import { Decimal } from 'decimal.js'; export default function calculateAmountOfRam(baseBalance, quoteBalance, RIXAmount) { const R = baseBalance; const C = quoteBalance.plus(RIXAmount); const F = 1.0; const base = RIXAmount.dividedBy(C).plus(Decimal(1.0)); const multiplier = Decimal(1.0).minus(Decimal.pow(base, F)); return Decimal(0).minus(R.times(multiplier)); } // Img.js (a gatsby-image wrapper) import React from 'react' import Image from 'gatsby-image' const Img = ({ objFit = `cover`, objPosition = `50% 50%`, ...props }) => ( <Image {...props} imgStyle={{ ...props.imgStyle, objectFit: objFit, objectPosition: objPosition, fontFamily: `"object-fit: ${objFit}; object-position: ${objPosition};"`, }} /> ) export default Img { let arr = Array.of(3,4,7,9,11); console.log('arr=', arr); let empty = Array.of(); console.log('empty=', empty); } { let p = document.querySelectorAll('p'); let pArr = Array.from(p); pArr.forEach(function(item){ console.log(item.textContent); }); console.log(Array.from([1,3,5], function(item){ return item*2 })); } { console.log('fill', [1, 'a', undefined].fill(7)); console.log('fill, pos', ['a','b','c'].fill(7,1,3)); } { for(let index of ['1','c','lv'].keys()){ console.log('keys',index); } for(let value of ['1','c','lv'].values()){ console.log('values',value); } for(let [index, value] of ['1','c','lv'].entries()){ console.log('[index, value]',index,value); } } { console.log([1,2,3,4,5].copyWithin(0,3,4)); } { // 找到第一个符合条件的元素,返回值 console.log([1,2,3,4,5,6].find(function(item){ return item>3; })) // 找到第一个符合条件的元素,返回index console.log([1,2,3,4,5,6].findIndex(function(item){ return item>3; })) } { console.log('number', [1,2,3,NaN].includes(1)); console.log('number', [1,2,3,NaN].includes(NaN)); } 'use strict'; const config = require(__dirname + '/../config/config'); const request = require('request-promise'); module.exports = function() { const verificationApiURL = 'https://www.google.com/recaptcha/api/siteverify'; return { /** * Generator that verifies solved Captcha with Google * @param {string} response The value of 'g-recaptcha-response' * @param {string} remoteip Client IP address * @return {promise} Yield a promise */ verify: function *(response, remoteip) { if ( !response ) { throw new Error('captcha_response_missing'); } if ( !remoteip ) { throw new Error('captcha_remoteip_missing'); } let postData = { secret: config.app.reCaptchaSecret, response: response, remoteip: remoteip }; return yield request.post({url: verificationApiURL, form: postData}) .catch(function () { throw new Error('captcha_server_error'); }) .then(function (body) { body = JSON.parse(body); if (body.success){ return true; } else if (body.success === false){ throw new Error('captcha_verification_invalid'); } throw new Error('captcha_verification_error'); }); } }; }; var data = { "body": "<path d=\"M18 12c0 .55.45 1 1 1h2c.55 0 1-.45 1-1s-.45-1-1-1h-2c-.55 0-1 .45-1 1zm-1.41 4.82a.966.966 0 0 0 .2 1.37c.53.39 1.09.81 1.62 1.21c.44.33 1.06.24 1.38-.2c0-.01.01-.01.01-.02a.978.978 0 0 0-.2-1.38c-.53-.4-1.09-.82-1.61-1.21a.993.993 0 0 0-1.39.21c0 .01-.01.02-.01.02zm3.22-12.01c0-.01-.01-.01-.01-.02a.98.98 0 0 0-1.38-.2c-.53.4-1.1.82-1.62 1.22c-.44.33-.52.95-.19 1.38c0 .01.01.01.01.02c.33.44.94.53 1.38.2c.53-.39 1.09-.82 1.62-1.22c.43-.32.51-.94.19-1.38zM8 9H4c-1.1 0-2 .9-2 2v2c0 1.1.9 2 2 2h1v3c0 .55.45 1 1 1s1-.45 1-1v-3h1l5 3V6L8 9zm7.5 3c0-1.33-.58-2.53-1.5-3.35v6.69c.92-.81 1.5-2.01 1.5-3.34z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; exports.__esModule = true; exports.default = data; <reponame>myrzayev89/reactlara import React, { useState, useEffect } from "react"; import axios from 'axios'; import { inject, observer } from "mobx-react"; import { useHistory } from 'react-router-dom'; import {Navbar, Container, Nav, NavDropdown} from 'react-bootstrap'; import {LinkContainer} from "react-router-bootstrap"; const Layout = (props) => { const [user, setUser] = useState({}); const [isLoggedIn, setIsLoggedIn] = useState(false); const history = useHistory(); useEffect(() => { const token = (props.AuthStore.appState != null) ? props.AuthStore.appState.user.access_token : null; axios.post(`/api/authenticate`,{},{ headers:{ Authorization: 'Bearer ' + token } }).then((res) => { if(!res.data.isLoggedIn){ history.push('/login'); } setUser(res.data.user); setIsLoggedIn(res.data.isLoggedIn); }).catch(e => { history.push('/login'); }); },[]); const logout = () => { axios.post(`/api/logout`, {}, { headers: { Authorization: 'Bearer ' + props.AuthStore.appState.user.access_token } }).then(res => console.log(res)).catch(e => console.log(e)); props.AuthStore.removeToken(); history.push('/login'); }; return ( <div> <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark"> <Container> <Navbar.Brand href="/"><NAME></Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav className="me-auto"> <LinkContainer to={'/category'}> <Nav.Link>Bölmə</Nav.Link> </LinkContainer> <LinkContainer to={'/customer'}> <Nav.Link>Müştəri & Tədarikçi</Nav.Link> </LinkContainer> <LinkContainer to={'/product'}> <Nav.Link>Mal</Nav.Link> </LinkContainer> <LinkContainer to={'/stock'}> <Nav.Link>Stok</Nav.Link> </LinkContainer> </Nav> <Nav> <NavDropdown title={user.name} id="collasible-nav-dropdown"> <NavDropdown.Item href="#action/3.1">Profilini düzənlə</NavDropdown.Item> <NavDropdown.Item href="#action/3.2">Şifrəni dəyiş</NavDropdown.Item> <NavDropdown.Divider /> <NavDropdown.Item onClick={logout}>Çıxış</NavDropdown.Item> </NavDropdown> </Nav> </Navbar.Collapse> </Container> </Navbar> <div>{props.children}</div> </div> ) }; export default inject("AuthStore")(observer(Layout)); /* * moleculer-sentry * Copyright (c) 2022 LuxChan S.A R.L.-S (https://github.com/LuxChanLu/moleculer-sentry) * MIT Licensed */ 'use strict' const Sentry = require('@sentry/node') const SentryUtils = require('@sentry/utils') module.exports = { name: 'sentry', /** * Default settings */ settings: { /** @type {Object?} Sentry configuration wrapper. */ sentry: { /** @type {String} DSN given by sentry. */ dsn: null, /** @type {String} Name of event fired by "Event" exported in tracing. */ tracingEventName: '$tracing.spans', /** @type {Object} Additional options for `Sentry.init`. */ options: {}, /** @type {String?} Name of the meta containing user infos. */ userMetaKey: null, }, /** * @deprecated * @type {String} DSN given by sentry. */ dsn: null, /** * @deprecated * @type {Object?} Additional options for `Sentry.init` */ options: {}, /** * @deprecated * @type {Object?} Options for the sentry scope */ scope: { /** * @deprecated * @type {String?} Name of the meta containing user infos */ user: null } }, /** * Events */ events: { // bind event listeners '**'(payload, sender, event) { // only listen to specifig tracing event if (event !== this.settings.sentry.tracingEventName) { return } this.onTracingEvent(payload) }, }, /** * Methods */ methods: { /** * Get service name from metric event (Imported from moleculer-jaeger) * * @param {Object} metric * @returns {String} */ getServiceName(metric) { if (!metric.service && metric.action) { const parts = metric.action.name.split('.') parts.pop() return parts.join('.') } return metric.service && metric.service.name ? metric.service.name : metric.service }, /** * Get span name from metric event. By default it returns the action name (Imported from moleculer-jaeger) * * @param {Object} metric * @returns {String} */ getSpanName(metric) { return metric.action ? metric.action.name : metric.name }, /** * Get object key under which user is stored in service meta * * @returns {String} */ getUserMetaKey() { // prefer new approach if (this.settings.sentry.userMetaKey) { return this.settings.sentry.userMetaKey } // fallback to old approach if (this.settings.scope && this.settings.scope.user) { return this.settings.scope.user } return null }, /** * We need to normalize the stack trace, since Sentry will throw an error unless it's a valid raw stack trace * * @param stack * @returns {null|*[]|*} */ getNormalizedStackTrace(stack) { // empty stack trace is not parseable by sentry, if (!stack) { return null } // if stacktrace is present as a string, wrap it into an array if (!Array.isArray(stack)) { return [stack]; } return stack; }, /** * Send error to sentry, based on the metric error * * @param {Object} metric */ sendSentryError(metric) { Sentry.withScope((scope) => { scope.setTag('id', metric.requestID) scope.setTag('service', this.getServiceName(metric)) scope.setTag('span', this.getSpanName(metric)) scope.setTag('type', metric.error.type) scope.setTag('code', metric.error.code) if (metric.error.data) { scope.setExtra('data', metric.error.data) } const userMetaKey = this.getUserMetaKey() if (userMetaKey && metric.meta && metric.meta[userMetaKey]) { scope.setUser(metric.meta[userMetaKey]) } Sentry.captureEvent({ message: metric.error.message, stacktrace: this.getNormalizedStackTrace(metric.error.stack) }) }) }, /** * Check if sentry is configured or not */ isSentryReady() { return Sentry.getCurrentHub().getClient() !== undefined }, /** * Tracing event handler * * @param metrics * @return void */ onTracingEvent(metrics) { metrics.forEach((metric) => { if (metric.error && this.isSentryReady() && (!this.shouldReport || this.shouldReport(metric) == true)) { this.sendSentryError(metric) } }) } }, started() { // ToDo: remove deprecated dsn and options from settings with next version const dsn = this.settings.dsn || this.settings.sentry.dsn const options = this.settings.options || this.settings.sentry.options if (dsn) { Sentry.init({ dsn, ...options }) } }, async stopped() { if (this.isSentryReady()) { await Sentry.flush() SentryUtils.getGlobalObject().__SENTRY__ = undefined } } } <reponame>vikasshekhawat/Cybersecurity_Assessment_Tool /* Adds in a text-sorter for any tables on a page */ /* Will skip sorts on blank <th> entries */ /* Does not work with paginated tables or multiple tables */ /* Adding class="auto-sort-none" to <TH> will skip that column */ /* Adding class="auto-sort-default" to <TH> will sort that column by default (asc) */ /* Tables must follow the following format: */ /* <table class="auto-sort"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <tr> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> </tbody> </table> //////////////////////////////////////////////////// <script src="{{ asset('/js/auto_sort.js') }}"></script> */ $(document).ready(function() { //Get all page tables tables = $(".auto-sort"); //Get all header names columnNames = [] columns = tables.find('thead tr:first th').each(function() { thisColumn = $(this).text().replace(/[\s!@#$%^&*(),.?":{}|<>]/g, ''); columnNames.push(thisColumn); //Ignore empty headers if (thisColumn != '' && !$(this).hasClass('auto-sort-none')) { $(this).append(`  <button class="btn btn-sm btn-outline-primary ` + thisColumn + `Btn" type="button" title="Not Sorted" onclick="autoSort('` + thisColumn + `', 'none');"><i class="fas fa-minus"></i></button> `); } }); //Default sort defaultSort = $('.auto-sort-default'); if (defaultSort) { autoSort(defaultSort.text().replace(/[\s!@#$%^&*(),.?":{}|<>]/g, ''), 'desc'); } }); function autoSort(column, type) { columnNumber = columnNames.indexOf(column) + 1; tables = $(".auto-sort"); tbody = tables.find('tbody'); //Desc/None -> Asc if (type == 'desc' || type == 'none') { //Sort Ascending tbody.find('tr').sort(function(a, b) { return $('td:nth-child(' + columnNumber + ')', a).text().localeCompare($('td:nth-child(' + columnNumber + ')', b).text()); }).appendTo(tbody); //Set all other buttons to inactive and '-' icon buttons = columns.children(); buttons.removeClass('active'); buttons.attr("title", "Not Sorted"); buttons.children().removeClass(); buttons.children().addClass('fas fa-minus'); //Change icon style and type button = $('.' + column + 'Btn'); button.addClass('active'); button.attr("title", "Ascending Sort"); button.attr("onclick", "autoSort('" + column + "', 'asc')"); button.children().removeClass(); button.children().addClass('fas fa-arrow-up'); } //Asc -> Desc if (type == 'asc') { //Sort Descending tbody.find('tr').sort(function(a, b) { return $('td:nth-child(' + columnNumber + ')', b).text().localeCompare($('td:nth-child(' + columnNumber + ')', a).text()); }).appendTo(tbody); //Set all other buttons to inactive and '-' icon buttons = columns.children(); buttons.removeClass('active'); buttons.attr("title", "Not Sorted"); buttons.children().removeClass(); buttons.children().addClass('fas fa-minus'); //Change icon style and type button = $('.' + column + 'Btn'); button.addClass('active'); button.attr("title", "Descending Sort"); button.attr("onclick", "autoSort('" + column + "', 'desc')"); button.children().removeClass(); button.children().addClass('fas fa-arrow-down'); } }<reponame>joeldenning/esm-bundle-test console.log('other') console.log('other') <reponame>Firexd2/control-money function shopping_list() { var block_action = 1; var name_plan = location.pathname.slice(1, -1); var elem = $('.input-shopping-list'); for (var i = 0; i < elem.length; i++) { var buffer = elem.eq(i).next(); buffer.text(elem.eq(i).val()); elem.eq(i).width(buffer.width()); } $('.delete-item').on('click', function () { var id = $('#name-list').val(); $.post('/ajax/delete_item_shopping_list/' + $(this).closest('.item-list').attr('id') + '/', function () { load('shopping_list/' + id + '/') }) }); $('form').on('click', 'input[name=checkbox]', function (e) { if (block_action) { block_action = 0; if ($(this).is(':checked')) { $(this).prev().val('1'); $(this).parent().next().css({'text-decoration': 'line-through'}) } else { $(this).prev().val('0'); $(this).parent().next().css({'text-decoration': 'none'}) } $(this).submit(); show_button_input_cost() } else { e.preventDefault() } }); $('form[name=shopping-list]').on('submit', function (e) { $(document).ajaxStart(function () { Pace.restart(); }); e.preventDefault(); var data = $(this).serializeArray(); $.ajax({ type: "POST", url: '/ajax/new_shopping_list/', data: data, success: function (data) { block_action = 1 } }); }); $('input[name=price], input[name=count], input[name=name-item]').on('blur', function (e) { if (block_action) { block_action = 0; $('form').submit() } }); $('input[name=name-list]').on('blur', function () { var data = $('form[name=shopping-list]').serializeArray(); $.ajax({ type: "POST", url: '/ajax/new_shopping_list/', data: data, success: function (data) { load('shopping_list/' + data.id + '/') } }); }); $('body').unbind().on('click', '.show-item-shop', function () { var elem = $(this).next(); if (elem.is(':hidden')) { elem.show(300) } else { elem.hide(300) } }); $('body').on('input', '.input-shopping-list', function () { var buffer = $(this).next(); buffer.text($(this).val()); $(this).width(buffer.width()); }); $('#add-item').on('click', function () { var id = $('#name-list').val(); $.ajax({ type: "POST", url: '/ajax/new_shopping_list/', data: {'new-item': '', 'id': id}, success: function (data) { load('shopping_list/' + data.id + '/') } }); }); $('select').on('change', function () { $(this).prev().val($(this).val()); $('form').submit() }); $('#input-cost').on('click', function () { var id = $('#name-list').val(); var name = $('input[name=name-list]').val(); var flags = $('input[name=flag]'); var elems_price = $('input[name=price]'); var select = $('select'); var validate = elems_price.length > 0; for (var i = 0; i < elems_price.length; i++) { if (flags.eq(i).val() === '1') { if ((!(elems_price.eq(i).val())) || (!(select.eq(i).val()))) { validate = false } } } if (validate) { $.confirm({ title: '<span style="font-weight: 100">Внесение трат по списку: </span> ' + name, content: 'url: /table_input/' + id + '/', buttons: { Ok: { text: 'Ок', btnClass: 'btn', action: function () { $(document).ajaxStart(function () { Pace.restart(); }); $.post('/ajax/input_cost_shopping_list/' + id + '/', {name: name_plan}, function () { $.alert({ title: 'Операция прошла успешно', type: 'green', content: 'Траты успешно внесены!' }) }) } }, Cancel: { text: 'Отмена', action: function () { } } } }) } else { $.alert({ type: 'red', title: 'Операция отменена', content: 'Чтобы внести список в траты, необходимо у всех отмеченных записей вписать цену и выбрать категорию.' }) } }); function show_button_input_cost() { if ($('input[type=checkbox]:checked').length) { $('#input-cost').show() } else { $('#input-cost').hide() } } show_button_input_cost(); $('#delete').on('click', function () { $.post('/ajax/delete_shopping_list/' + $('#name-list').val() + '/', function () { load('shopping_list/') }) }) } window.scriptsContent = shopping_list();<reponame>snappmarket/frontend-toolbox import * as StringHelpers from '../index'; describe('StingHelpers', () => { describe('stringReplace', () => { it('should find and replace a word in a string', () => { const payload = 'Hello World, this is World!'; const expected = 'Hello Snappmarket, this is Snappmarket!'; expect( StringHelpers.stringReplace('World', 'Snappmarket', payload), ).toEqual(expected); }); }); describe('bulkStringReplace', () => { it('should find and replace in multiple words in a string', () => { const payload = 'Hello World!'; const replacements = { Hello: 'How You', World: 'Doing', '!': '?', }; const expected = 'How You Doing?'; expect(StringHelpers.bulkStringReplace(replacements, payload)).toEqual( expected, ); }); }); describe('autoLink', () => { it('should find and replace urls with linked url in string', () => { const payload = 'hello, my website address is http://erami.name and i work in https://snapp.market'; const expected = 'hello, my website address is <a href="http://erami.name" target="_blank">http://erami.name</a> and i work in <a href="https://snapp.market" target="_blank">https://snapp.market</a>'; expect(StringHelpers.autoLink(payload)).toEqual(expected); }); }); describe('getQueryParams', () => { it('should get value of a query parameter', () => { const url = 'https://example.com/?foo=bar'; expect(StringHelpers.getQueryParams(url, 'foo')).toEqual('bar'); }); it("should get empty string, cause parameter is defined but it's value is empty", () => { const url = 'https://example.com/?foo='; expect(StringHelpers.getQueryParams(url, 'foo')).toEqual(''); }); it("should not get value of a query parameter cause it's not defined", () => { const url = 'https://example.com'; expect(StringHelpers.getQueryParams(url, 'foo')).toEqual(null); }); }); describe('camelToSnakeCase', () => { it('should convert a camel case to a snake case string', () => { expect(StringHelpers.camelToSnakeCase('camelIsTheBestBandEver')).toEqual( 'camel_is_the_best_band_ever', ); }); }); }); <reponame>kjk/programming-books.io //. values to test against event.which export const Escape = 27; export const Enter = 13; export function isEsc(ev) { return ev.which === Escape; } export function isEnter(ev) { return ev.which === Enter; } export function isUp(ev) { return (ev.key == "ArrowUp") || (ev.key == "Up"); } export function isDown(ev) { return (ev.key == "ArrowDown") || (ev.key == "Down"); } // navigation up is: Up or Ctrl-P export function isNavUp(ev) { if (isUp(ev)) { return true; } return ev.ctrlKey && (ev.keyCode === 80); } // navigation down is: Down or Ctrl-N export function isNavDown(ev) { if (isDown(ev)) { return true; } return ev.ctrlKey && (ev.keyCode === 78); } "use strict"; exports.BattleTPP = { /* ============================ Hall of Fame Mon - Undisputed TPP Mon ============================ */ // See: http://thatswhatyouget.github.io/tpp-progress/halloffame.html ////// Season 1 // Red pidgey:1, pidgeotto:1, pidgeot:1, pidgeotmega:1, lapras:1, venonat:1, venomoth:1, zapdos:1, nidoranm:1, nidorino:1, nidoking:1, omanyte:1, omastar:1, // Crystal onix:1, steelix:1, steelixmega:1, dratini:1, dragonair:1, dragonite:1, eevee:1, vaporeon:1, jolteon:1, flareon:1, espeon:1, umbreon:1, leafeon:1, glaceon:1, sylveon:1, totodile:1, croconaw:1, feraligatr:1, // Emerald makuhita:1, hariyama:1, poochyena:1, mightyena:1, oddish:1, gloom:1, vileplume:1, bellossom:1, geodude:1, graveler:1, golem:1, geodudealola:1, graveleralola:1, golemalola:1, tentacool:1, tentacruel:1, azurill:1, marill:1, azumarill:1, // FireRed swablu:1, altaria:1, altariamega:1, mew:1, surskit:1, masquerain:1, squirtle:1, wartortle:1, blastoise:1, blastoisemega:1, sandshrew:1, sandslash:1, sandshrewalola:1, sandslashalola:1, slakoth:1, vigoroth:1, slaking:1, // Platinum shinx:1, luxio:1, luxray:1, bidoof:1, bibarel:1, zubat:1, golbat:1, crobat:1, bronzor:1, bronzong:1, budew:1, roselia:1, roserade:1, // HeartGold trapinch:1, vibrava:1, flygon:1, bonsly:1, sudowoodo:1, natu:1, xatu:1, shieldon:1, bastiodon:1, cranidos:1, rampardos:1, // Black deerling:1, sawsbuck:1, joltik:1, galvantula:1, druddigon:1, blitzle:1, zebstrika:1, tympole:1, palpitoad:1, seismitoad:1, pidove:1, tranquill:1, unfezant:1, // Black 2 treecko:1, grovyle:1, sceptile:1, sceptilemega:1, sewaddle:1, swadloon:1, leavanny:1, zorua:1, zoroark:1, tepig:1, pignite:1, emboar:1, // X charmander:1, charmeleon:1, charizard:1, charizardmegax:1, charizardmegay:1, absol:1, absolmega:1, honedge:1, doublade:1, aegislash:1, aegislashblade:1, xerneas:1, hawlucha:1, // OmegaRuby zigzagoon:1, linoone:1, whismur:1, loudred:1, exploud:1, minun:1, latios:1, latiosmega:1, electrike:1, manectric:1, manectricmega:1, rayquaza:1, rayquazamega:1, plusle:1, ////// Season 2 // Anniversary Red slowpoke:1, slowbro:1, slowbromega:1, slowking:1, kabuto:1, kabutops:1, shellder:1, cloyster:1, paras:1, parasect:1, grimer:1, muk:1, grimeralola:1, mukalola:1, abra:1, kadabra:1, alakazam:1, alakazammega:1, bellsprout:1, weepinbell:1, victreebel:1, // Moemon / Touhoumon diglett:1, dugtrio:1, diglettalola:1, dugtrioalola:1, elekid:1, electabuzz:1, electivire:1, // TODO: Insert Sanae, Cirno, Momiji, Satori, Tokiko, Mima here for Touhoumon // AlphaSapphire igglybuff:1, jigglypuff:1, wigglytuff:1, frillish:1, jellicent:1, cacnea:1, cacturne:1, chinchou:1, lanturn:1, // Colosseum chikorita:1, bayleef:1, meganium:1, hoppip:1, skiploom:1, jumpluff:1, misdreavus:1, mismagius:1, wooper:1, quagsire:1, // XD mareep:1, flaaffy:1, ampharos:1, ampharosmega:1, gulpin:1, swalot:1, baltoy:1, claydol:1, carvanha:1, sharpedo:1, sharpedomega:1, spheal:1, sealeo:1, walrein:1, seedot:1, nuzleaf:1, shiftry:1, ////// Season 3 // Anniversary Crystal bulbasaur:1, ivysaur:1, venusaur:1, venusaurmega:1, aerodactyl:1, aerodactylmega:1, horsea:1, seadra:1, kingdra:1, miltank:1, hoothoot:1, noctowl:1, // Crystal Revisit rattata:1, raticate:1, // Brown psyduck:1, golduck:1, weedle:1, kakuna:1, beedrill:1, beedrillmega:1, // Randomized Platinum pachirisu:1, magnemite:1, magneton:1, magnezone:1, ponyta:1, rapidash:1, phanpy:1, donphan:1, krabby:1, kingler:1, // Prism vulpix:1, ninetales:1, vulpixalola:1, ninetalesalola:1, buneary:1, lopunny:1, lopunnymega:1, ralts:1, kirlia:1, gardevoir:1, gardevoirmega:1,gallade:1, gallademega:1, larvitar:1, pupitar:1, tyranitar:1, tyranitarmega:1, // Sun cutiefly:1, ribombee:1, cosmog:1, cosmoem:1, solgaleo:1, lunala:1, spinarak:1, ariados:1, zygarde:1, rattataalola:1, raticatealola:1, spearow:1, fearow:1, // Waning Moon starly:1, staravia:1, staraptor:1, litten:1, torracat:1, incineroar:1, ducklett:1, swanna:1, pikipek:1, trumbeak:1, toucannon:1, ////// Season 4 // Chatty Yellow chatot:1, magikarp:1, gyarados:1, gyaradosmega:1, pichu:1, pikachu:1, raichu:1, raichualola:1, pikachucosplay:1, pikachurockstar:1, pikachubelle:1, pikachupopstar:1, pikachuphd:1, pikachulibre:1, // Blazed Glazed oshawott:1, dewott:1, samurott:1, turtwig:1, grotle:1, torterra:1, venipede:1, whirlipede:1, scolipede:1, bagon:1, shelgon:1, salamence:1, salamencemega:1, swinub:1, piloswine:1, mamoswine:1, houndour:1, houndoom:1, // Randomized White 2 articuno:1, cresselia:1, buizel:1, floatzel:1, kyogre:1, // Pyrite seel:1, dewgong:1, sentret:1, furret:1, magby:1, magmar:1, magmortar:1, exeggcute:1, exeggutor:1, exeggutoralola:1, // Theta Emerald EX skiddo:1, gogoat:1, mantyke:1, mantine:1, litleo:1, pyroar:1, pancham:1, pangoro:1, inkay:1, malamar:1, // Ultra Sun popplio:1, brionne:1, primarina:1, grubbin:1, charjabug:1, vikavolt:1, rockruff:1, lycanroc:1, lycanrocmidnight:1, lycanrocdusk:1, phantump:1, trevenant:1, ////// Season 5 // Dual Red/Blue ekans:1, arbok:1, meowth:1, persian:1, meowthalola:1, persianalola:1, cleffa:1, clefairy:1, clefable:1, tauros:1, nidoranf:1, nidorina:1, nidoqueen:1, // Storm Silver shellos:1, gastrodon:1, farfetchd:1, stunky:1, skuntank:1, snorunt:1, glalie:1, froslass:1, cyndaquil:1, quilava:1, typhlosion:1, lugia:1, // Bronze growlithe:1, arcanine:1, /* =============================== Legal TPP mon by Community Vote =============================== */ ////// Season 1 TPP Relevant // Red gastly:1, haunter:1, gengar:1, gengarmega:1, tyrogue:1, hitmonlee:1, hitmonchan:1, hitmontop:1, // Crystal togepi:1, togetic:1, togekiss:1, unown:1, shuckle:1, drowzee:1, hypno:1, smoochum:1, jynx:1, goldeen:1, seaking:1, // Emerald torchic:1, combusken:1, blaziken:1, blazikenmega:1, wurmple:1, silcoon:1, beautifly:1, cascoon:1, dustox:1, wingull:1, pelipper:1, nincada:1, ninjask:1, shedinja:1, lotad:1, lombre:1, ludicolo:1, // FireRed machop:1, machoke:1, machamp:1, skitty:1, delcatty:1, // Platium chimchar:1, monferno:1, infernape:1, uxie:1, kricketot:1, kricketune:1, giratina:1, giratinaorigin:1, azelf:1, sneasel:1, weavile:1, // HeartGold lileep:1, cradily:1, groudon:1, groudonprimal:1, phione:1, // Black pansage:1, simisage:1, petilil:1, lilligant:1, tirtouga:1, carracosta:1, purrloin:1, liepard:1, lillipup:1, herdier:1, stoutland:1, vullaby:1, mandibuzz:1, // Black 2 basculin:1, basculinbluestriped:1, // X riolu:1, lucario:1, lucariomega:1, chespin:1, quilladin:1, chesnaught:1, beldum:1, metang:1, metagross:1, metagrossmega:1, // OR caterpie:1, metapod:1, butterfree:1, poliwag:1, poliwhirl:1, poliwrath:1, politoed:1, croagunk:1, toxicroak:1, // Stadium / PBR entei:1, ////// Season 2 // Anniversary Red mimejr:1, mrmime:1, cubone:1, marowak:1, marowakalola:1, scatterbug:1, spewpa:1, vivillon:1, // Viernamese Crystal (Intermission Game) suicune:1, // Randomized AlphaSapphire glameow:1, purugly:1, ferroseed:1, ferrothorn:1, corsola:1, rufflet:1, braviary:1, litwick:1, lampent:1, chandelure:1, // Colosseum remoraid:1, octillery:1, // XD teddiursa:1, ursaring:1, ////// Season 3 // Anniversary Crystal munchlax:1, snorlax:1, ledyba:1, ledian:1, // Brown porygon:1, porygon2:1, porygonz:1, // Randomized Platium chingling:1, chimecho:1, // Sun buzzwole:1, // Prism phancero:1, // Waning Moon sandile:1, krokorok:1, krookodile:1, yungoos:1, gumshoos:1, ////// Season 4 // Chatty Yellow ditto:1, // Blazed Glazed // Randomized White 2 // Pyrite // Theta Emerald EX // Ultra Sun ////// Season 5 // Dual Red/Blue // Storm Silver // Bronze ////// Because L WutFace R E arceus:1, arceusbug:1, arceusdark:1, arceusdragon:1, arceuselectric:1, arceusfairy:1, arceusfighting:1, arceusfire:1, arceusflying:1, arceusghost:1, arceusgrass:1, arceusground:1, arceusice:1, arceuspoison:1, arceuspsychic:1, arceusrock:1, arceussteel:1, arceuswater:1, genesect:1, genesectdouse:1, genesectshock:1, genesectburn:1, genesectchill:1, amaura:1, aurorus:1, tyrunt:1, tyrantrum:1, anorith:1, armaldo:1, archen:1, archeops:1, gumblegoose:1, ////// I have no idea... slugma:1, magcargo:1, shuppet:1, banette:1, banettemega:1, celebi:1, };<filename>portal/server/controllers/dashboard/facilities.test.js<gh_stars>1-10 import { bssFacilities, gefFacilities } from '.'; import mockResponse from '../../helpers/responseMock'; import { getApiData } from '../../helpers'; import api from '../../api'; jest.mock('../../helpers', () => ({ __esModule: true, getApiData: jest.fn(), getFlashSuccessMessage: jest.fn(), requestParams: jest.fn(() => ({ userToken: '<PASSWORD>' })), })); describe('controllers/facilities', () => { let req; let checkerReq; let res; beforeEach(() => { req = { body: {}, params: { page: 1 }, session: { dashboardFilters: 'mock-filters', user: { id: 'mock-user', roles: ['maker', 'checker'], }, }, }; checkerReq = { body: {}, params: { page: 1 }, session: { dashboardFilters: 'mock-filters', user: { id: 'mock-user', roles: ['checker'], }, }, }; api.transactions = jest.fn(); api.gefFacilities = jest.fn(); res = mockResponse(); }); describe('bssFacilities', () => { beforeEach(() => { getApiData.mockResolvedValue({ count: 2, transactions: [ { transaction_id: 'mockFacility1', deal_id: 'mock-deal-1', bankFacilityId: 'mock-facility', transactionType: 'bond', currency: { id: 'GBP' }, }, { transaction_id: 'mockFacility2', deal_id: 'mock-deal-1', transactionType: 'another-type', currency: { id: 'GBP' }, }, ], }); }); afterEach(() => { getApiData.mockReset(); }); it('passes the expected filter for maker', async () => { await bssFacilities(req, res); expect(api.transactions).toHaveBeenCalledWith(20, 20, [], 'mock-token'); }); it('passes the expected filter for checker', async () => { await bssFacilities(checkerReq, res); expect(api.transactions).toHaveBeenCalledWith(20, 20, [{ field: 'details.status', operator: 'eq', value: "Ready for Checker's approval" }], 'mock-token'); }); it('renders the correct template', async () => { await bssFacilities(req, res); expect(res.render).toHaveBeenCalledWith('dashboard/facilities.njk', { facilities: [ { _id: 'mockFacility1', bankId: 'mock-facility', dealId: 'mock-deal-1', facilityType: 'bond', product: 'BSS/EWCS', ukefStage: '-', value: { currency: 'GBP' }, url: '/contract/mock-deal-1/bond/mockFacility1/details', }, { _id: 'mockFacility2', bankId: 'Not entered', dealId: 'mock-deal-1', facilityType: 'another-type', product: 'BSS/EWCS', ukefStage: '-', value: { currency: 'GBP' }, url: '/contract/mock-deal-1/another-type/mockFacility2/guarantee-details', }, ], pages: { totalPages: 1, currentPage: 1, totalItems: 2, }, primaryNav: 'home', tab: 'bssFacilities', user: { id: 'mock-user', roles: ['maker', 'checker'], }, }); }); }); describe('gefFacilities', () => { beforeEach(() => { getApiData.mockResolvedValue({ count: 2, facilities: [ { _id: 'mockFacility1', name: 'mock-facility', applicationId: 'mock-deal-1', type: 'mock-type', hasBeenIssued: true, deal: { _id: 'mock-deal-1' }, }, { _id: 'mockFacility2', applicationId: 'mock-deal-1', type: 'mock-type', deal: { _id: 'mock-deal-1' }, }, ], }); }); afterEach(() => { getApiData.mockReset(); }); it('passes the expected filter for maker', async () => { await gefFacilities(req, res); expect(api.gefFacilities).toHaveBeenCalledWith(20, 20, [], 'mock-token'); }); it('passes the expected filter for checker', async () => { await gefFacilities(checkerReq, res); expect(api.gefFacilities).toHaveBeenCalledWith(20, 20, [{ field: 'deal.status', operator: 'eq', value: 'BANK_CHECK' }], 'mock-token'); }); it('renders the correct template', async () => { await gefFacilities(req, res); expect(res.render).toHaveBeenCalledWith('dashboard/facilities.njk', { facilities: [ { _id: 'mockFacility1', bankId: 'mock-facility', dealId: 'mock-deal-1', facilityType: 'mock-type', bankStage: 'Issued', product: 'GEF', ukefStage: '-', url: '/gef/application-details/mock-deal-1/facilities/mockFacility1/', value: { amount: 0, currency: '' }, }, { _id: 'mockFacility2', bankId: 'Not entered', dealId: 'mock-deal-1', facilityType: 'mock-type', bankStage: 'Unissued', product: 'GEF', ukefStage: '-', url: '/gef/application-details/mock-deal-1/facilities/mockFacility2/', value: { amount: 0, currency: '' }, }, ], pages: { totalPages: 1, currentPage: 1, totalItems: 2, }, primaryNav: 'home', tab: 'gefFacilities', user: { id: 'mock-user', roles: ['maker', 'checker'], }, }); }); }); }); /** * Statické hodnoty `CBoxLine` … jen pomocné pro napovídání * @typedef CBoxLine_static * @type {HTMLElement & { constructor: { attributes: { name: string, initial: string }[], tagName: string } }} */// @if TARGET='app' import y18n from 'y18n'; import path from 'path'; const i18n = y18n({ directory: path.join(__dirname, `locales`), updateFiles: true, locale: 'en', }); // @endif // @if TARGET='web' const i18n = { setLocale: () => {}, getLocale: () => null, __: x => x, __n: x => x, }; // @endif export default i18n; <reponame>nandini-menon/portfolio<gh_stars>1-10 import React from 'react' import { GoMarkGithub } from 'react-icons/go' class Button extends React.Component { render() { return ( <a className="button button-primary" href={this.props.link} target='_blank' rel="noopener noreferrer"> <GoMarkGithub /> Find out more </a> ) } } class CardBody extends React.Component { render() { return ( <div className="card-body"> <p className="date">March 20 2015</p> <h2>{this.props.title}</h2> <p className="body-content">{this.props.text}</p> <Button link={this.props.link} /> </div> ) } } class Card extends React.Component { render() { return ( <article className="card"> {/* <CardHeader image={this.props.image}/> */} <CardBody title={this.props.title} text={this.props.text} link={this.props.link}/> </article> ) } } export default Card<gh_stars>0 import Navigation from '../Nav/Navigation' const Contact = () => { return ( <div className="container-lg"> <Navigation/> {"TODO..."} </div> ) } export default Contact<filename>node_modules/@ant-design/icons/es/icons/BankOutlined.js<gh_stars>1-10 // GENERATE BY ./scripts/generate.ts // DON NOT EDIT IT MANUALLY import React from 'react'; import BankOutlinedSvg from "@ant-design/icons-svg/es/asn/BankOutlined"; import AntdIcon from '../components/AntdIcon'; var BankOutlined = function BankOutlined(props, ref) { return React.createElement(AntdIcon, Object.assign({}, props, { ref: ref, icon: BankOutlinedSvg })); }; BankOutlined.displayName = 'BankOutlined'; export default React.forwardRef(BankOutlined);const express = require("express") //importer les packages // const dotenv = require ("dotenv") const mongoose = require("mongoose") const cors = require('cors'); const docteur = require("./routes/docteur") const medicament = require("./routes/medicament") //import routes const certif = require("./routes/certif") const bodyParser = require("body-parser") // import const app = express() //sortie app.use(express.json()) // use json from express app.use(cors()) dotenv.config() //on doit l'utilisé en mode configuré app.use(bodyParser.urlencoded({extended:true})) // body parsing middleware //db connection// mongoose.connect(process.env.URL,err => { if(err) throw err console.log("connected to mongo DB") }) app.use("/api",docteur) //ajouté la chaîne "/api" //middlewares // app.use("/api",medicament) app.use("/api",certif) const PORT = process.env.PORT||8080 //récupérer la variable de .env app.listen(PORT,()=> { //lancer le server p(le port et une fonction callback) console.log("le server est lancé sur le port "+PORT) }) //http://localhost:8080/api/medicament/all<filename>src/api/PlayersApi.js import { createAsyncThunk } from "@reduxjs/toolkit"; // GET ALL PLAYERS const getPlayers = createAsyncThunk( "players/getPlayers", async () => { return fetch("https://free-nba.p.rapidapi.com/players?per_page=100&page=0", { "method": "GET", "headers": { "x-rapidapi-host": "free-nba.p.rapidapi.com", "x-rapidapi-key": "<KEY>" } }) .then(async response => response.json()) .catch(err => { console.error(err); }); } ); export default getPlayers<reponame>residently/huejay<filename>lib/Command/Group/CreateGroup.js 'use strict'; let Utils = require('./Utils'); const ALLOWED_ATTRIBUTES = [ 'name', 'type', 'class', 'lights', ]; /** * Create group command * * Create a group */ class CreateGroup { /** * Constructor * * @param {Group} group Group */ constructor(group) { Utils.validateGroup(group); this.group = group; } /** * Invoke command * * @param {Client} client Client * * @return {Promise} Promise for chaining */ invoke(client) { let options = { method: 'POST', url: `api/${client.username}/groups`, data: {} }; let attributes = this.group.attributes.getAll(); for (let key of ALLOWED_ATTRIBUTES) { if (key in attributes) { options.data[key] = attributes[key]; } } return client.getTransport() .sendRequest(options) .then(result => { this.group.attributes.resetChanged(); this.group.attributes.replace({ id: result.id }); return this.group; }); } } module.exports = CreateGroup; // @flow import PokemonList from "./PokemonList"; export default PokemonList; /* Copyright (c) 2003-2010, CKSource - <NAME>. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Slovenian language. */ /**#@+ @type String @example */ /** * Constains the dictionary of language entries. * @namespace */ CKEDITOR.lang['sl'] = { /** * The language reading direction. Possible values are "rtl" for * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right * languages (like English). * @default 'ltr' */ dir: 'ltr', /* * Screenreader titles. Please note that screenreaders are not always capable * of reading non-English words. So be careful while translating it. */ editorTitle: 'Rich text editor, %1, press ALT 0 for help.', // MISSING // ARIA descriptions. toolbar: 'Toolbar', // MISSING editor: 'Rich Text Editor', // MISSING // Toolbar buttons without dialogs. source: 'Izvorna koda', newPage: 'Nova stran', save: 'Shrani', preview: 'Predogled', cut: 'Izreži', copy: 'Kopiraj', paste: 'Prilepi', print: 'Natisni', underline: 'Podčrtano', bold: 'Krepko', italic: 'Ležeče', selectAll: 'Izberi vse', removeFormat: 'Odstrani oblikovanje', strike: 'Prečrtano', subscript: 'Podpisano', superscript: 'Nadpisano', horizontalrule: 'Vstavi vodoravno črto', pagebreak: 'Vstavi prelom strani', pagebreakAlt: 'Page Break', // MISSING unlink: 'Odstrani povezavo', undo: 'Razveljavi', redo: 'Ponovi', // Common messages and labels. common: { browseServer: 'Prebrskaj na strežniku', url: 'URL', protocol: 'Protokol', upload: 'Prenesi', uploadSubmit: 'Pošlji na strežnik', image: 'Slika', flash: 'Flash', form: 'Obrazec', checkbox: 'Potrditveno polje', radio: 'Izbirno polje', textField: 'Vnosno polje', textarea: 'Vnosno območje', hiddenField: 'Skrito polje', button: 'Gumb', select: 'Spustni seznam', imageButton: 'Gumb s sliko', notSet: '<ni postavljen>', id: 'Id', name: 'Ime', langDir: 'Smer jezika', langDirLtr: 'Od leve proti desni (LTR)', langDirRtl: 'Od desne proti levi (RTL)', langCode: 'Oznaka jezika', longDescr: 'Dolg opis URL-ja', cssClass: 'Razred stilne predloge', advisoryTitle: 'Predlagani naslov', cssStyle: 'Slog', ok: 'V redu', cancel: 'Prekliči', close: 'Close', // MISSING preview: 'Preview', // MISSING generalTab: 'Splošno', advancedTab: 'Napredno', validateNumberFailed: 'Ta vrednost ni število.', confirmNewPage: 'Vse neshranjene spremembe te vsebine bodo izgubljene. Ali gotovo želiš naložiti novo stran?', confirmCancel: 'Nekaj možnosti je bilo spremenjenih. Ali gotovo želiš zapreti okno?', options: 'Options', // MISSING target: 'Target', // MISSING targetNew: 'New Window (_blank)', // MISSING targetTop: 'Topmost Window (_top)', // MISSING targetSelf: 'Same Window (_self)', // MISSING targetParent: 'Parent Window (_parent)', // MISSING langDirLTR: 'Left to Right (LTR)', // MISSING langDirRTL: 'Right to Left (RTL)', // MISSING styles: 'Style', // MISSING cssClasses: 'Stylesheet Classes', // MISSING width: 'Širina', height: 'Višina', align: 'Poravnava', alignLeft: 'Levo', alignRight: 'Desno', alignCenter: 'Sredinsko', alignTop: 'Na vrh', alignMiddle: 'V sredino', alignBottom: 'Na dno', invalidHeight: 'Višina mora biti število.', invalidWidth: 'Širina mora biti število.', // Put the voice-only part of the label in the span. unavailable: '%1<span class="cke_accessibility">, nedosegljiv</span>' }, contextmenu: { options: 'Context Menu Options' // MISSING }, // Special char dialog. specialChar: { toolbar: 'Vstavi posebni znak', title: 'Izberi posebni znak', options: 'Special Character Options' // MISSING }, // Link dialog. link: { toolbar: 'Vstavi/uredi povezavo', other: '<drug>', menu: 'Uredi povezavo', title: 'Povezava', info: 'Podatki o povezavi', target: 'Cilj', upload: 'Prenesi', advanced: 'Napredno', type: 'Vrsta povezave', toUrl: 'URL', // MISSING toAnchor: 'Zaznamek na tej strani', toEmail: 'Elektronski naslov', targetFrame: '<okvir>', targetPopup: '<pojavno okno>', targetFrameName: 'Ime ciljnega okvirja', targetPopupName: 'Ime pojavnega okna', popupFeatures: 'Značilnosti pojavnega okna', popupResizable: 'Spremenljive velikosti', popupStatusBar: 'Vrstica stanja', popupLocationBar: 'Naslovna vrstica', popupToolbar: 'Orodna vrstica', popupMenuBar: 'Menijska vrstica', popupFullScreen: 'Celozaslonska slika (IE)', popupScrollBars: 'Drsniki', popupDependent: 'Podokno (Netscape)', popupLeft: 'Lega levo', popupTop: 'Lega na vrhu', id: 'Id', langDir: 'Smer jezika', langDirLTR: 'Od leve proti desni (LTR)', langDirRTL: 'Od desne proti levi (RTL)', acccessKey: 'Vstopno geslo', name: 'Ime', langCode: 'Smer jezika', tabIndex: 'Številka tabulatorja', advisoryTitle: 'Predlagani naslov', advisoryContentType: 'Predlagani tip vsebine (content-type)', cssClasses: 'Razred stilne predloge', charset: 'Kodna tabela povezanega vira', styles: 'Slog', selectAnchor: 'Izberi zaznamek', anchorName: 'Po imenu zaznamka', anchorId: 'Po ID-ju elementa', emailAddress: 'Elektronski naslov', emailSubject: 'Predmet sporočila', emailBody: 'Vsebina sporočila', noAnchors: '(V tem dokumentu ni zaznamkov)', noUrl: 'Vnesite URL povezave', noEmail: 'Vnesite elektronski naslov' }, // Anchor dialog anchor: { toolbar: 'Vstavi/uredi zaznamek', menu: 'Lastnosti zaznamka', title: '<NAME>', name: '<NAME>', errorName: 'Prosim vnesite ime zaznamka' }, // List style dialog list: { numberedTitle: 'Numbered List Properties', // MISSING bulletedTitle: 'Bulleted List Properties', // MISSING type: 'Type', // MISSING start: 'Start', // MISSING validateStartNumber: 'List start number must be a whole number.', // MISSING circle: 'Circle', // MISSING disc: 'Disc', // MISSING square: 'Square', // MISSING none: 'None', // MISSING notset: '<not set>', // MISSING armenian: 'Armenian numbering', // MISSING georgian: 'Georgian numbering (an, ban, gan, etc.)', // MISSING lowerRoman: 'Lower Roman (i, ii, iii, iv, v, etc.)', // MISSING upperRoman: 'Upper Roman (I, II, III, IV, V, etc.)', // MISSING lowerAlpha: 'Lower Alpha (a, b, c, d, e, etc.)', // MISSING upperAlpha: 'Upper Alpha (A, B, C, D, E, etc.)', // MISSING lowerGreek: 'Lower Greek (alpha, beta, gamma, etc.)', // MISSING decimal: 'Decimal (1, 2, 3, etc.)', // MISSING decimalLeadingZero: 'Decimal leading zero (01, 02, 03, etc.)' // MISSING }, // Find And Replace Dialog findAndReplace: { title: 'Najdi in zamenjaj', find: 'Najdi', replace: 'Zamenjaj', findWhat: 'Najdi:', replaceWith: 'Zamenjaj z:', notFoundMsg: 'Navedeno besedilo ni bilo najdeno.', matchCase: 'Razlikuj velike in male črke', matchWord: 'Samo cele besede', matchCyclic: 'Primerjaj znake v cirilici', replaceAll: 'Zamenjaj vse', replaceSuccessMsg: '%1 pojavitev je bilo zamenjano.' }, // Table Dialog table: { toolbar: 'Tabela', title: 'Lastnosti tabele', menu: 'Lastnosti tabele', deleteTable: 'Izbriši tabelo', rows: 'Vrstice', columns: 'Stolpci', border: 'Velikost obrobe', widthPx: 'pik', widthPc: 'procentov', widthUnit: 'width unit', // MISSING cellSpace: 'Razmik med celicami', cellPad: 'Polnilo med celicami', caption: 'Naslov', summary: 'Povzetek', headers: 'Glave', headersNone: 'Brez', headersColumn: 'Prvi stolpec', headersRow: 'Prva vrstica', headersBoth: 'Oboje', invalidRows: 'Število vrstic mora biti večje od 0.', invalidCols: 'Število stolpcev mora biti večje od 0.', invalidBorder: 'Širina obrobe mora biti število.', invalidWidth: 'Širina tabele mora biti število.', invalidHeight: 'Višina tabele mora biti število.', invalidCellSpacing: 'Razmik med celicami mora biti število.', invalidCellPadding: 'Zamik celic mora biti število', cell: { menu: 'Celica', insertBefore: 'Vstavi celico pred', insertAfter: 'Vstavi celico za', deleteCell: 'Izbriši celice', merge: 'Združi celice', mergeRight: 'Združi desno', mergeDown: 'Druži navzdol', splitHorizontal: 'Razdeli celico vodoravno', splitVertical: 'Razdeli celico navpično', title: 'Lastnosti celice', cellType: 'Vrsta celice', rowSpan: 'Razpon vrstic', colSpan: 'Razpon stolpcev', wordWrap: 'Prelom besedila', hAlign: 'Vodoravna poravnava', vAlign: 'Navpična poravnava', alignBaseline: 'Osnovnica', bgColor: 'Barva ozadja', borderColor: 'Barva obrobe', data: 'Podatki', header: 'Glava', yes: 'Da', no: 'Ne', invalidWidth: 'Širina celice mora biti število.', invalidHeight: 'Višina celice mora biti število.', invalidRowSpan: 'Razpon vrstic mora biti celo število.', invalidColSpan: 'Razpon stolpcev mora biti celo število.', chooseColor: 'Izberi' }, row: { menu: 'Vrstica', insertBefore: 'Vstavi vrstico pred', insertAfter: 'Vstavi vrstico za', deleteRow: 'Izbriši vrstice' }, column: { menu: 'Stolpec', insertBefore: 'Vstavi stolpec pred', insertAfter: 'Vstavi stolpec za', deleteColumn: 'Izbriši stolpce' } }, // Button Dialog. button: { title: 'Lastnosti gumba', text: 'Besedilo (Vrednost)', type: 'Tip', typeBtn: 'Gumb', typeSbm: 'Potrdi', typeRst: 'Ponastavi' }, // Checkbox and Radio Button Dialogs. checkboxAndRadio: { checkboxTitle: 'Lastnosti potrditvenega polja', radioTitle: 'Lastnosti izbirnega polja', value: 'Vrednost', selected: 'Izbrano' }, // Form Dialog. form: { title: 'Lastnosti obrazca', menu: 'Lastnosti obrazca', action: 'Akcija', method: 'Metoda', encoding: 'Kodiranje znakov' }, // Select Field Dialog. select: { title: 'Lastnosti spustnega seznama', selectInfo: 'Podatki', opAvail: 'Razpoložljive izbire', value: 'Vrednost', size: 'Velikost', lines: 'vrstic', chkMulti: 'Dovoli izbor večih vrstic', opText: 'Besedilo', opValue: 'Vrednost', btnAdd: 'Dodaj', btnModify: 'Spremeni', btnUp: 'Gor', btnDown: 'Dol', btnSetValue: 'Postavi kot privzeto izbiro', btnDelete: 'Izbriši' }, // Textarea Dialog. textarea: { title: 'Lastnosti vnosnega območja', cols: 'Stolpcev', rows: 'Vrstic' }, // Text Field Dialog. textfield: { title: 'Lastnosti vnosnega polja', name: 'Ime', value: 'Vrednost', charWidth: 'Dolžina', maxChars: 'Največje število znakov', type: 'Tip', typeText: 'Besedilo', typePass: 'Geslo' }, // Hidden Field Dialog. hidden: { title: 'Lastnosti skritega polja', name: 'Ime', value: 'Vrednost' }, // Image Dialog. image: { title: 'Lastnosti slike', titleButton: 'Lastnosti gumba s sliko', menu: 'Lastnosti slike', infoTab: 'Podatki o sliki', btnUpload: 'Pošlji na strežnik', upload: 'Pošlji', alt: 'Nadomestno besedilo', lockRatio: 'Zakleni razmerje', unlockRatio: 'Unlock Ratio', // MISSING resetSize: 'Ponastavi velikost', border: 'Obroba', hSpace: 'Vodoravni razmik', vSpace: 'Navpični razmik', alertUrl: 'Vnesite URL slike', linkTab: 'Povezava', button2Img: 'Želiš pretvoriti izbrani gumb s sliko v preprosto sliko?', img2Button: 'Želiš pretvoriti izbrano sliko v gumb s sliko?', urlMissing: 'Manjka vir (URL) slike.', validateBorder: 'Border must be a whole number.', // MISSING validateHSpace: 'HSpace must be a whole number.', // MISSING validateVSpace: 'VSpace must be a whole number.' // MISSING }, // Flash Dialog flash: { properties: 'Lastnosti Flash', propertiesTab: 'Lastnosti', title: 'Lastnosti Flash', chkPlay: 'Samodejno predvajaj', chkLoop: 'Ponavljanje', chkMenu: 'Omogoči Flash Meni', chkFull: 'Dovoli celozaslonski način', scale: 'Povečava', scaleAll: 'Pokaži vse', scaleNoBorder: 'Brez obrobe', scaleFit: 'Natančno prileganje', access: 'Dostop skript', accessAlways: 'Vedno', accessSameDomain: 'Samo ista domena', accessNever: 'Nikoli', alignAbsBottom: 'Popolnoma na dno', alignAbsMiddle: 'Popolnoma v sredino', alignBaseline: 'Na osnovno črto', alignTextTop: 'Besedilo na vrh', quality: 'Kakovost', qualityBest: 'Najvišja', qualityHigh: 'Visoka', qualityAutoHigh: 'Samodejno visoka', qualityMedium: 'Srednja', qualityAutoLow: 'Samodejno nizka', qualityLow: 'Nizka', windowModeWindow: 'Okno', windowModeOpaque: 'Motno', windowModeTransparent: 'Prosojno', windowMode: 'Vrsta okna', flashvars: 'Spremenljivke za Flash', bgcolor: 'Barva ozadja', hSpace: 'Vodoravni razmik', vSpace: 'Navpični razmik', validateSrc: 'Vnesite URL povezave', validateHSpace: 'Vodoravni razmik mora biti število.', validateVSpace: 'Navpični razmik mora biti število.' }, // Speller Pages Dialog spellCheck: { toolbar: 'Preveri črkovanje', title: 'Črkovalnik', notAvailable: 'Oprostite, storitev trenutno ni dosegljiva.', errorLoading: 'Napaka pri nalaganju storitve programa na naslovu %s.', notInDic: 'Ni v slovarju', changeTo: 'Spremeni v', btnIgnore: 'Prezri', btnIgnoreAll: 'Prezri vse', btnReplace: 'Zamenjaj', btnReplaceAll: 'Zamenjaj vse', btnUndo: 'Razveljavi', noSuggestions: '- Ni predlogov -', progress: 'Preverjanje črkovanja se izvaja...', noMispell: 'Črkovanje je končano: Brez napak', noChanges: 'Črkovanje je končano: Nobena beseda ni bila spremenjena', oneChange: 'Črkovanje je končano: Spremenjena je bila ena beseda', manyChanges: 'Črkovanje je končano: Spremenjenih je bilo %1 besed', ieSpellDownload: 'Črkovalnik ni nameščen. Ali ga želite prenesti sedaj?' }, smiley: { toolbar: 'Smeško', title: 'Vstavi smeška', options: 'Smiley Options' // MISSING }, elementsPath: { eleLabel: 'Elements path', // MISSING eleTitle: '%1 element' }, numberedlist: 'Oštevilčen seznam', bulletedlist: 'Označen seznam', indent: 'Povečaj zamik', outdent: 'Zmanjšaj zamik', justify: { left: 'Leva poravnava', center: 'Sredinska poravnava', right: 'Desna poravnava', block: 'Obojestranska poravnava' }, blockquote: 'Citat', clipboard: { title: 'Prilepi', cutError: 'Varnostne nastavitve brskalnika ne dopuščajo samodejnega izrezovanja. Uporabite kombinacijo tipk na tipkovnici (Ctrl/Cmd+X).', copyError: 'Varnostne nastavitve brskalnika ne dopuščajo samodejnega kopiranja. Uporabite kombinacijo tipk na tipkovnici (Ctrl/Cmd+C).', pasteMsg: 'Prosim prilepite v sleči okvir s pomočjo tipkovnice (<STRONG>Ctrl/Cmd+V</STRONG>) in pritisnite <STRONG>V redu</STRONG>.', securityMsg: 'Zaradi varnostnih nastavitev vašega brskalnika urejevalnik ne more neposredno dostopati do odložišča. Vsebino odložišča ponovno prilepite v to okno.', pasteArea: 'Paste Area' // MISSING }, pastefromword: { confirmCleanup: 'The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?', // MISSING toolbar: 'Prilepi iz Worda', title: 'Prilepi iz Worda', error: 'It was not possible to clean up the pasted data due to an internal error' // MISSING }, pasteText: { button: 'Prilepi kot golo besedilo', title: 'Prilepi kot golo besedilo' }, templates: { button: 'Predloge', title: 'Vsebinske predloge', options: 'Template Options', // MISSING insertOption: 'Zamenjaj trenutno vsebino', selectPromptMsg: 'Izberite predlogo, ki jo želite odpreti v urejevalniku<br>(trenutna vsebina bo izgubljena):', emptyListMsg: '(Ni pripravljenih predlog)' }, showBlocks: 'Prikaži ograde', stylesCombo: { label: 'Slog', panelTitle: 'Formatting Styles', // MISSING panelTitle1: 'Slogi odstavkov', panelTitle2: 'Slogi besedila', panelTitle3: 'Slogi objektov' }, format: { label: 'Oblika', panelTitle: 'Oblika', tag_p: 'Navaden', tag_pre: 'Oblikovan', tag_address: 'Napis', tag_h1: 'Naslov 1', tag_h2: 'Naslov 2', tag_h3: 'Naslov 3', tag_h4: 'Naslov 4', tag_h5: 'Naslov 5', tag_h6: 'Naslov 6', tag_div: 'Navaden (DIV)' }, div: { title: 'Create Div Container', // MISSING toolbar: 'Create Div Container', // MISSING cssClassInputLabel: 'Stylesheet Classes', // MISSING styleSelectLabel: 'Style', // MISSING IdInputLabel: 'Id', // MISSING languageCodeInputLabel: ' Language Code', // MISSING inlineStyleInputLabel: 'Inline Style', // MISSING advisoryTitleInputLabel: 'Advisory Title', // MISSING langDirLabel: 'Language Direction', // MISSING langDirLTRLabel: 'Left to Right (LTR)', // MISSING langDirRTLLabel: 'Right to Left (RTL)', // MISSING edit: 'Edit Div', // MISSING remove: 'Remove Div' // MISSING }, iframe: { title: 'iFrame Properties', // MISSING toolbar: 'iFrame', // MISSING noUrl: 'Please type the iFrame URL', // MISSING scrolling: 'Enable scrollbars', // MISSING border: 'Show frame border' // MISSING }, font: { label: 'Pisava', voiceLabel: 'Pisava', panelTitle: 'Pisava' }, fontSize: { label: 'Velikost', voiceLabel: 'Velikost', panelTitle: 'Velikost' }, colorButton: { textColorTitle: 'Barva besedila', bgColorTitle: 'Barva ozadja', panelTitle: 'Colors', // MISSING auto: 'Samodejno', more: 'Več barv...' }, colors: { '000': 'Black', // MISSING '800000': 'Maroon', // MISSING '8B4513': 'Saddle Brown', // MISSING '2F4F4F': 'Dark Slate Gray', // MISSING '008080': 'Teal', // MISSING '000080': 'Navy', // MISSING '4B0082': 'Indigo', // MISSING '696969': 'Dark Gray', // MISSING 'B22222': 'Fire Brick', // MISSING 'A52A2A': 'Brown', // MISSING 'DAA520': 'Golden Rod', // MISSING '006400': 'Dark Green', // MISSING '40E0D0': 'Turquoise', // MISSING '0000CD': 'Medium Blue', // MISSING '800080': 'Purple', // MISSING '808080': 'Gray', // MISSING 'F00': 'Red', // MISSING 'FF8C00': 'Dark Orange', // MISSING 'FFD700': 'Gold', // MISSING '008000': 'Green', // MISSING '0FF': 'Cyan', // MISSING '00F': 'Blue', // MISSING 'EE82EE': 'Violet', // MISSING 'A9A9A9': 'Dim Gray', // MISSING 'FFA07A': 'Light Salmon', // MISSING 'FFA500': 'Orange', // MISSING 'FFFF00': 'Yellow', // MISSING '00FF00': 'Lime', // MISSING 'AFEEEE': 'Pale Turquoise', // MISSING 'ADD8E6': 'Light Blue', // MISSING 'DDA0DD': 'Plum', // MISSING 'D3D3D3': 'Light Grey', // MISSING 'FFF0F5': 'Lavender Blush', // MISSING 'FAEBD7': 'Antique White', // MISSING 'FFFFE0': 'Light Yellow', // MISSING 'F0FFF0': 'Honeydew', // MISSING 'F0FFFF': 'Azure', // MISSING 'F0F8FF': 'Alice Blue', // MISSING 'E6E6FA': 'Lavender', // MISSING 'FFF': 'White' // MISSING }, scayt: { title: 'Črkovanje med tipkanjem', opera_title: 'Not supported by Opera', // MISSING enable: 'Omogoči SCAYT', disable: 'Onemogoči SCAYT', about: 'O storitvi SCAYT', toggle: 'Preklopi SCAYT', options: 'Možnosti', langs: 'Jeziki', moreSuggestions: 'Več predlogov', ignore: 'Prezri', ignoreAll: 'Prezri vse', addWord: 'Dodaj besedo', emptyDic: 'Ime slovarja ne more biti prazno.', optionsTab: 'Možnosti', allCaps: 'Ignore All-Caps Words', // MISSING ignoreDomainNames: 'Ignore Domain Names', // MISSING mixedCase: 'Ignore Words with Mixed Case', // MISSING mixedWithDigits: 'Ignore Words with Numbers', // MISSING languagesTab: 'Jeziki', dictionariesTab: 'Slovarji', dic_field_name: 'Dictionary name', // MISSING dic_create: 'Create', // MISSING dic_restore: 'Restore', // MISSING dic_delete: 'Delete', // MISSING dic_rename: 'Rename', // MISSING dic_info: 'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.', // MISSING aboutTab: 'O storitvi' }, about: { title: 'O programu CKEditor', dlgTitle: 'O programu CKEditor', moreInfo: 'Za informacijo o licenci prostim obiščite našo spletno stran:', copy: 'Copyright © $1. Vse pravice pridržane.' }, maximize: 'Maksimiraj', minimize: 'Minimiraj', fakeobjects: { anchor: 'Sidro', flash: 'Flash animacija', iframe: 'iFrame', // MISSING hiddenfield: 'Hidden Field', // MISSING unknown: 'Neznan objekt' }, resize: 'Potegni za spremembo velikosti', colordialog: { title: 'Izberi barvo', options: 'Color Options', // MISSING highlight: 'Poudarjeno', selected: 'Izbrano', clear: 'Počisti' }, toolbarCollapse: 'Collapse Toolbar', // MISSING toolbarExpand: 'Expand Toolbar', // MISSING bidi: { ltr: 'Text direction from left to right', // MISSING rtl: 'Text direction from right to left' // MISSING } }; window.onload = async function() { $('#view').css("color", "blue"); };const FormulaError = require('../error'); const {FormulaHelpers, Types, Factorials, Criteria} = require('../helpers'); const {Infix} = require('../operators'); const H = FormulaHelpers; // Max number in excel is 2^1024-1, same as javascript, thus I will not check if number is valid in some functions. // factorials const f = [], fd = []; function factorial(n) { if (n <= 100) return Factorials[n]; if (f[n] > 0) return f[n]; return f[n] = factorial(n - 1) * n; } function factorialDouble(n) { if (n === 1 || n === 0) return 1; if (n === 2) return 2; if (fd[n] > 0) return fd[n]; return fd[n] = factorialDouble(n - 2) * n; } // https://support.office.com/en-us/article/excel-functions-by-category-5f91f4e9-7b42-46d2-9bd1-63f26a86c0eb const MathFunctions = { ABS: number => { number = H.accept(number, Types.NUMBER); return Math.abs(number); }, AGGREGATE: (functionNum, options, ref1, ...refs) => { // functionNum = H.accept(functionNum, Types.NUMBER); // throw FormulaError.NOT_IMPLEMENTED('AGGREGATE'); }, ARABIC: text => { text = H.accept(text, Types.STRING).toUpperCase(); // Credits: <NAME> if (!/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/.test(text)) { throw new FormulaError('#VALUE!', 'Invalid roman numeral in ARABIC evaluation.'); } let r = 0; text.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, function (i) { r += { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 }[i]; }); return r; }, BASE: (number, radix, minLength) => { number = H.accept(number, Types.NUMBER); if (number < 0 || number >= 2 ** 53) throw FormulaError.NUM; radix = H.accept(radix, Types.NUMBER); if (radix < 2 || radix > 36) throw FormulaError.NUM; minLength = H.accept(minLength, Types.NUMBER, 0); if (minLength < 0) { throw FormulaError.NUM; } const result = number.toString(radix).toUpperCase(); return new Array(Math.max(minLength + 1 - result.length, 0)).join('0') + result; }, CEILING: (number, significance) => { number = H.accept(number, Types.NUMBER); significance = H.accept(significance, Types.NUMBER); if (significance === 0) return 0; if (number / significance % 1 === 0) return number; const absSignificance = Math.abs(significance); const times = Math.floor(Math.abs(number) / absSignificance); if (number < 0) { // round down, away from zero const roundDown = significance < 0; return roundDown ? -absSignificance * (times + 1) : -absSignificance * (times); } else { return (times + 1) * absSignificance; } }, 'CEILING.MATH': (number, significance, mode) => { number = H.accept(number, Types.NUMBER); significance = H.accept(significance, Types.NUMBER, number > 0 ? 1 : -1); // mode can be any number mode = H.accept(mode, Types.NUMBER, 0); // The Mode argument does not affect positive numbers. if (number >= 0) { return MathFunctions.CEILING(number, significance); } // if round down, away from zero, then significance const offset = mode ? significance : 0; return MathFunctions.CEILING(number, significance) - offset; }, 'CEILING.PRECISE': (number, significance) => { number = H.accept(number, Types.NUMBER); significance = H.accept(significance, Types.NUMBER, 1); // always round up return MathFunctions.CEILING(number, Math.abs(significance)); }, COMBIN: (number, numberChosen) => { number = H.accept(number, Types.NUMBER); numberChosen = H.accept(numberChosen, Types.NUMBER); if (number < 0 || numberChosen < 0 || number < numberChosen) throw FormulaError.NUM; const nFactorial = MathFunctions.FACT(number), kFactorial = MathFunctions.FACT(numberChosen); return nFactorial / kFactorial / MathFunctions.FACT(number - numberChosen); }, COMBINA: (number, numberChosen) => { number = H.accept(number, Types.NUMBER); numberChosen = H.accept(numberChosen, Types.NUMBER); // special case if ((number === 0 || number === 1) && numberChosen === 0) return 1; if (number < 0 || numberChosen < 0) throw FormulaError.NUM; return MathFunctions.COMBIN(number + numberChosen - 1, number - 1); }, DECIMAL: (text, radix) => { text = H.accept(text, Types.STRING); radix = H.accept(radix, Types.NUMBER); radix = Math.trunc(radix); if (radix < 2 || radix > 36) throw FormulaError.NUM; const res = parseInt(text, radix); if (isNaN(res)) throw FormulaError.NUM; return res; }, DEGREES: (radians) => { radians = H.accept(radians, Types.NUMBER); return radians * (180 / Math.PI); }, EVEN: (number) => { return MathFunctions.CEILING(number, -2); }, EXP: (number) => { number = H.accept(number, Types.NUMBER); return Math.exp(number) }, FACT: (number) => { number = H.accept(number, Types.NUMBER); number = Math.trunc(number); // max number = 170 if (number > 170 || number < 0) throw FormulaError.NUM; if (number <= 100) return Factorials[number]; return factorial(number); }, FACTDOUBLE: (number) => { number = H.accept(number, Types.NUMBER); number = Math.trunc(number); // max number = 170 if (number < -1) throw FormulaError.NUM; if (number === -1) return 1; return factorialDouble(number); }, FLOOR: (number, significance) => { number = H.accept(number, Types.NUMBER); significance = H.accept(significance, Types.NUMBER); if (significance === 0) return 0; if (number > 0 && significance < 0) throw FormulaError.NUM; if (number / significance % 1 === 0) return number; const absSignificance = Math.abs(significance); const times = Math.floor(Math.abs(number) / absSignificance); if (number < 0) { // round down, away from zero const roundDown = significance < 0; return roundDown ? -absSignificance * times : -absSignificance * (times + 1); } else { // toward zero return times * absSignificance; } }, 'FLOOR.MATH': (number, significance, mode) => { number = H.accept(number, Types.NUMBER); significance = H.accept(significance, Types.NUMBER, number > 0 ? 1 : -1); // mode can be 0 or any other number, 0 means away from zero // the official documentation seems wrong mode = H.accept(mode, Types.NUMBER, 0); // The Mode argument does not affect positive numbers. if (mode === 0 || number >= 0) { // away from zero return MathFunctions.FLOOR(number, Math.abs(significance)); } // towards zero, add a significance return MathFunctions.FLOOR(number, significance) + significance; }, 'FLOOR.PRECISE': (number, significance) => { number = H.accept(number, Types.NUMBER); significance = H.accept(significance, Types.NUMBER, 1); // always round up return MathFunctions.FLOOR(number, Math.abs(significance)); }, GCD: (...params) => { const arr = []; H.flattenParams(params, null, false, (param) => { // allow array, range ref param = typeof param === 'boolean' ? NaN : Number(param); if (!isNaN(param)) { if (param < 0 || param > 9007199254740990) // 2^53 throw FormulaError.NUM; arr.push(Math.trunc(param)) } else throw FormulaError.VALUE; }, 0); // http://rosettacode.org/wiki/Greatest_common_divisor#JavaScript let i, y, n = params.length, x = Math.abs(arr[0]); for (i = 1; i < n; i++) { y = Math.abs(arr[i]); while (x && y) { (x > y) ? x %= y : y %= x; } x += y; } return x; }, INT: (number) => { number = H.accept(number, Types.NUMBER); return Math.floor(number); }, 'ISO.CEILING': (...params) => { return MathFunctions['CEILING.PRECISE'](...params); }, LCM: (...params) => { const arr = []; // always parse string to number if possible H.flattenParams(params, null, false, param => { param = typeof param === 'boolean' ? NaN : Number(param); if (!isNaN(param)) { if (param < 0 || param > 9007199254740990) // 2^53 throw FormulaError.NUM; arr.push(Math.trunc(param)) } // throw value error if can't parse to string else throw FormulaError.VALUE; }, 1); // http://rosettacode.org/wiki/Least_common_multiple#JavaScript let n = arr.length, a = Math.abs(arr[0]); for (let i = 1; i < n; i++) { let b = Math.abs(arr[i]), c = a; while (a && b) { a > b ? a %= b : b %= a; } a = Math.abs(c * arr[i]) / (a + b); } return a; }, LN: number => { number = H.accept(number, Types.NUMBER); return Math.log(number); }, LOG: (number, base) => { number = H.accept(number, Types.NUMBER); base = H.accept(base, Types.NUMBER, 10); return Math.log(number) / Math.log(base); }, LOG10: number => { number = H.accept(number, Types.NUMBER); return Math.log10(number); }, MDETERM: (array) => { array = H.accept(array, Types.ARRAY, undefined, false, true); if (array[0].length !== array.length) throw FormulaError.VALUE; // adopted from https://github.com/numbers/numbers.js/blob/master/lib/numbers/matrix.js#L261 const numRow = array.length, numCol = array[0].length; let det = 0, diagLeft, diagRight; if (numRow === 1) { return array[0][0]; } else if (numRow === 2) { return array[0][0] * array[1][1] - array[0][1] * array[1][0]; } for (let col = 0; col < numCol; col++) { diagLeft = array[0][col]; diagRight = array[0][col]; for (let row = 1; row < numRow; row++) { diagRight *= array[row][(((col + row) % numCol) + numCol) % numCol]; diagLeft *= array[row][(((col - row) % numCol) + numCol) % numCol]; } det += diagRight - diagLeft; } return det; }, MINVERSE: (array) => { // TODO // array = H.accept(array, Types.ARRAY, null, false); // if (array[0].length !== array.length) // throw FormulaError.VALUE; // throw FormulaError.NOT_IMPLEMENTED('MINVERSE'); }, MMULT: (array1, array2) => { array1 = H.accept(array1, Types.ARRAY, undefined, false, true); array2 = H.accept(array2, Types.ARRAY, undefined, false, true); const aNumRows = array1.length, aNumCols = array1[0].length, bNumRows = array2.length, bNumCols = array2[0].length, m = new Array(aNumRows); // initialize array of rows if (aNumCols !== bNumRows) throw FormulaError.VALUE; for (let r = 0; r < aNumRows; r++) { m[r] = new Array(bNumCols); // initialize the current row for (let c = 0; c < bNumCols; c++) { m[r][c] = 0; // initialize the current cell for (let i = 0; i < aNumCols; i++) { const v1 = array1[r][i], v2 = array2[i][c]; if (typeof v1 !== "number" || typeof v2 !== "number") throw FormulaError.VALUE; m[r][c] += array1[r][i] * array2[i][c]; } } } return m; }, MOD: (number, divisor) => { number = H.accept(number, Types.NUMBER); divisor = H.accept(divisor, Types.NUMBER); if (divisor === 0) throw FormulaError.DIV0; return number - divisor * MathFunctions.INT(number / divisor); }, MROUND: (number, multiple) => { number = H.accept(number, Types.NUMBER); multiple = H.accept(multiple, Types.NUMBER); if (multiple === 0) return 0; if (number > 0 && multiple < 0 || number < 0 && multiple > 0) throw FormulaError.NUM; if (number / multiple % 1 === 0) return number; return Math.round(number / multiple) * multiple; }, MULTINOMIAL: (...numbers) => { let numerator = 0, denominator = 1; H.flattenParams(numbers, Types.NUMBER, false, number => { if (number < 0) throw FormulaError.NUM; numerator += number; denominator *= factorial(number); }); return factorial(numerator) / denominator; }, MUNIT: (dimension) => { dimension = H.accept(dimension, Types.NUMBER); const matrix = []; for (let row = 0; row < dimension; row++) { const rowArr = []; for (let col = 0; col < dimension; col++) { if (row === col) rowArr.push(1); else rowArr.push(0); } matrix.push(rowArr); } return matrix; }, ODD: (number) => { number = H.accept(number, Types.NUMBER); if (number === 0) return 1; let temp = Math.ceil(Math.abs(number)); temp = (temp & 1) ? temp : temp + 1; return (number > 0) ? temp : -temp; }, PI: () => { return Math.PI; }, POWER: (number, power) => { number = H.accept(number, Types.NUMBER); power = H.accept(power, Types.NUMBER); return number ** power; }, PRODUCT: (...numbers) => { let product = 1; H.flattenParams(numbers, null, true, (number, info) => { const parsedNumber = Number(number); if (info.isLiteral && !isNaN(parsedNumber)) { product *= parsedNumber; } else { if (typeof number === "number") product *= number; } }, 1); return product; }, QUOTIENT: (numerator, denominator) => { numerator = H.accept(numerator, Types.NUMBER); denominator = H.accept(denominator, Types.NUMBER); return Math.trunc(numerator / denominator); }, RADIANS: (degrees) => { degrees = H.accept(degrees, Types.NUMBER); return degrees / 180 * Math.PI; }, RAND: () => { return Math.random(); }, RANDBETWEEN: (bottom, top) => { bottom = H.accept(bottom, Types.NUMBER); top = H.accept(top, Types.NUMBER); return Math.floor(Math.random() * (top - bottom + 1) + bottom); }, ROMAN: (number, form) => { number = H.accept(number, Types.NUMBER); form = H.accept(form, Types.NUMBER, 0); if (form !== 0) throw Error('ROMAN: only allows form=0 (classic form).'); // The MIT License // Copyright (c) 2008 <NAME> const digits = String(number).split(''); const key = ['', '<KEY> 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; let roman = '', i = 3; while (i--) { roman = (key[+digits.pop() + (i * 10)] || '') + roman; } return new Array(+digits.join('') + 1).join('M') + roman; }, ROUND: (number, digits) => { number = H.accept(number, Types.NUMBER); digits = H.accept(digits, Types.NUMBER); const multiplier = Math.pow(10, Math.abs(digits)); const sign = number > 0 ? 1 : -1; if (digits > 0) { return sign * Math.round(Math.abs(number) * multiplier) / multiplier; } else if (digits === 0) { return sign * Math.round(Math.abs(number)); } else { return sign * Math.round(Math.abs(number) / multiplier) * multiplier; } }, ROUNDDOWN: (number, digits) => { number = H.accept(number, Types.NUMBER); digits = H.accept(digits, Types.NUMBER); const multiplier = Math.pow(10, Math.abs(digits)); const sign = number > 0 ? 1 : -1; if (digits > 0) { const offset = 1 / multiplier * 0.5; return sign * Math.round((Math.abs(number) - offset) * multiplier) / multiplier; } else if (digits === 0) { const offset = 0.5; return sign * Math.round((Math.abs(number) - offset)); } else { const offset = multiplier * 0.5; return sign * Math.round((Math.abs(number) - offset) / multiplier) * multiplier; } }, ROUNDUP: (number, digits) => { number = H.accept(number, Types.NUMBER); digits = H.accept(digits, Types.NUMBER); const multiplier = Math.pow(10, Math.abs(digits)); const sign = number > 0 ? 1 : -1; if (digits > 0) { const offset = 1 / multiplier * 0.5; return sign * Math.round((Math.abs(number) + offset) * multiplier) / multiplier; } else if (digits === 0) { const offset = 0.5; return sign * Math.round((Math.abs(number) + offset)); } else { const offset = multiplier * 0.5; return sign * Math.round((Math.abs(number) + offset) / multiplier) * multiplier; } }, SERIESSUM: (x, n, m, coefficients) => { x = H.accept(x, Types.NUMBER); n = H.accept(n, Types.NUMBER); m = H.accept(m, Types.NUMBER); let i = 0, result; H.flattenParams([coefficients], Types.NUMBER, false, (coefficient) => { if (typeof coefficient !== "number") { throw FormulaError.VALUE; } if (i === 0) { result = coefficient * Math.pow(x, n); } else { result += coefficient * Math.pow(x, n + i * m); } i++; }); return result; }, SIGN: number => { number = H.accept(number, Types.NUMBER); return number > 0 ? 1 : number === 0 ? 0 : -1; }, SQRT: number => { number = H.accept(number, Types.NUMBER); if (number < 0) throw FormulaError.NUM; return Math.sqrt(number); }, SQRTPI: number => { number = H.accept(number, Types.NUMBER); if (number < 0) throw FormulaError.NUM; return Math.sqrt(number * Math.PI); }, SUBTOTAL: () => { // TODO: Finish this after statistical functions are implemented. }, SUM: (...params) => { // parse string to number only when it is a literal. (not a reference) let result = 0; H.flattenParams(params, Types.NUMBER, true, (item, info) => { // literal will be parsed to given type (Type.NUMBER) if (info.isLiteral) { result += item; } else { if (typeof item === "number") result += item; } }); return result }, /** * This functions requires instance of {@link FormulaParser}. */ SUMIF: (context, range, criteria, sumRange) => { const ranges = H.retrieveRanges(context, range, sumRange); range = ranges[0]; sumRange = ranges[1]; criteria = H.retrieveArg(context, criteria); const isCriteriaArray = criteria.isArray; // parse criteria criteria = Criteria.parse(H.accept(criteria)); let sum = 0; range.forEach((row, rowNum) => { row.forEach((value, colNum) => { const valueToAdd = sumRange[rowNum][colNum]; if (typeof valueToAdd !== "number") return; // wildcard if (criteria.op === 'wc') { if (criteria.match === criteria.value.test(value)) { sum += valueToAdd; } } else if (Infix.compareOp(value, criteria.op, criteria.value, Array.isArray(value), isCriteriaArray)) { sum += valueToAdd; } }) }); return sum; }, SUMIFS: () => { }, SUMPRODUCT: (array1, ...arrays) => { array1 = H.accept(array1, Types.ARRAY, undefined, false, true); arrays.forEach(array => { array = H.accept(array, Types.ARRAY, undefined, false, true); if (array1[0].length !== array[0].length || array1.length !== array.length) throw FormulaError.VALUE; for (let i = 0; i < array1.length; i++) { for (let j = 0; j < array1[0].length; j++) { if (typeof array1[i][j] !== "number") array1[i][j] = 0; if (typeof array[i][j] !== "number") array[i][j] = 0; array1[i][j] *= array[i][j]; } } }); let result = 0; array1.forEach(row => { row.forEach(value => { result += value; }) }); return result; }, SUMSQ: (...params) => { // parse string to number only when it is a literal. (not a reference) let result = 0; H.flattenParams(params, Types.NUMBER, true, (item, info) => { // literal will be parsed to given type (Type.NUMBER) if (info.isLiteral) { result += item ** 2; } else { if (typeof item === "number") result += item ** 2; } }); return result }, SUMX2MY2: (arrayX, arrayY) => { const x = [], y = []; let sum = 0; H.flattenParams([arrayX], null, false, (item, info) => { x.push(item); }); H.flattenParams([arrayY], null, false, (item, info) => { y.push(item); }); if (x.length !== y.length) throw FormulaError.NA; for (let i = 0; i < x.length; i++) { if (typeof x[i] === "number" && typeof y[i] === "number") sum += x[i] ** 2 - y[i] ** 2 } return sum; }, SUMX2PY2: (arrayX, arrayY) => { const x = [], y = []; let sum = 0; H.flattenParams([arrayX], null, false, (item, info) => { x.push(item); }); H.flattenParams([arrayY], null, false, (item, info) => { y.push(item); }); if (x.length !== y.length) throw FormulaError.NA; for (let i = 0; i < x.length; i++) { if (typeof x[i] === "number" && typeof y[i] === "number") sum += x[i] ** 2 + y[i] ** 2 } return sum; }, SUMXMY2: (arrayX, arrayY) => { const x = [], y = []; let sum = 0; H.flattenParams([arrayX], null, false, (item, info) => { x.push(item); }); H.flattenParams([arrayY], null, false, (item, info) => { y.push(item); }); if (x.length !== y.length) throw FormulaError.NA; for (let i = 0; i < x.length; i++) { if (typeof x[i] === "number" && typeof y[i] === "number") sum += (x[i] - y[i]) ** 2; } return sum; }, TRUNC: (number) => { number = H.accept(number, Types.NUMBER); return Math.trunc(number); }, }; module.exports = MathFunctions; export default class InvalidRequestError { violations = {}; constructor(violations) { this.violations = violations; } } <filename>src/main.js import Vue from 'vue' import './utils'; import App from './App.vue' import VueRouter from "vue-router" import 'vuetify/dist/vuetify.min.css' import store from "./store" import MakeModelRun from "@/components/MakeModelRun"; import AppHome from "@/components/AppHome"; import ListModelRuns from "@/components/ListModelRuns"; import InputDataViewer from "@/components/InputDataViewer"; import Settings from "@/components/Settings"; import About from "@/components/About"; import Help from "@/components/Help"; const ModelRun = () => import(/* webpackPrefetch: true */ "@/components/ModelRun"); // we load this this way so that it can lazy load it on demand import 'material-design-icons-iconfont/dist/material-design-icons.css' // need this for material design icons import 'leaflet/dist/leaflet.css'; import vuetify from '@/plugins/vuetify' // path to vuetify export import '@/sentry'; // initialize a11y features // Now init the application itself Vue.use(VueRouter) Vue.config.productionTip = false const routes = [ { path: '/', name:'home', component: AppHome, meta: {title: "Home"} }, { path: '/make-model-run', name:'make-model-run', component: MakeModelRun, meta: {title: "Make New Model Run"} }, { path: '/model-runs', name:'list-model-runs', component: ListModelRuns, meta: {title: "My Model Runs"}}, { path: '/model-run/:id', name:'model-run', component: ModelRun, meta: {title: "View Model Run"} }, { path: '/input-data-viewer/', name:'input-data-viewer', component: InputDataViewer, meta: {title: "View Input Data"} }, { path: '/help/', name:'help', component: Help, meta: {title: "Help and Tutorials"} }, { path: '/settings/', name:'settings', component: Settings, meta: {title: "Settings"} }, { path: '/pages/about/', name:'about', component: About, meta: {title: "About OpenAg"} }, ] const router = new VueRouter({ routes, // short for `routes: routes` scrollBehavior (to) { if (to.hash) { return { selector: to.hash // , offset: { x: 0, y: 10 } } } } }); const stormchaser = new Vue({ store, router, vuetify, render: h => h(App), }).$mount('#app') let default_title_getter = function(){return stormchaser.$store.getters.current_model_area.name}; function set_window_title(title){ document.title = `${default_title_getter()}: ${title}` || default_title_getter(); } router.afterEach((to ) => { // Use next tick to handle router history correctly // see: https://github.com/vuejs/vue-router/issues/914#issuecomment-384477609 Vue.nextTick(() => { set_window_title(to.meta.title) }); }); /* We have an autologin system for washington that bypasses the need to create or manage user accounts - a bit of a distinction without a difference in some ways because it's actually that we'll have a single user account and log them in automatically. This next function will set up the check that runs when the application first loads to see if it's an auto-login deployment of the application. It hits an API endpoint that either tells us that it's not an auto-login version or that it is and provides the credentials to use and the auto login user info. We have a flag here at the top to set whether or not to try it just to prevent an unnecessary request from happening in deployments that don't need it. We'll build it special when we send deployments that need auto-login. */ let try_auto_login = false; if(try_auto_login === true){ // when the DOM is loaded, then check if we're running an auto-login setup document.addEventListener("DOMContentLoaded", function() { fetch("/auto-login/", {method: 'GET', credentials: 'omit'}).then((response) => { response.json().then( function(response_data){ if("auto_login_allowed" in response_data && response_data.auto_login_allowed === true) { store.dispatch("check_and_set_token", {token: response_data.auto_login_token, user_info: response_data.user_info}) } } ) }) }); } window.stormchaser = stormchaser; // log it to the window so we can debug with it. 'use strict'; module.exports = (sequelize, DataTypes) => { const Sensors = sequelize.define('Sensors', { location: { type: DataTypes.STRING, set: function(val) { this.setDataValue('location', val.toUpperCase()); } }, type: { type: DataTypes.STRING, set: function(val) { this.setDataValue('type', val.toUpperCase()); } }, state: DataTypes.STRING, value: DataTypes.STRING }, {}); Sensors.associate = function(models) { // associations can be defined here }; return Sensors; };<reponame>92cit22/IST const puppeteer = require('puppeteer'); countVacancies(); async function countVacancies() { const browser = await puppeteer.launch({ args: ['--start-maximized'], headless: false, slowMo: 100, }); let page = await browser.pages().then(x => x[0]); await page.goto('https://careers.veeam.ru/vacancies'); let opts = await page.$$("button#sl"); await opts[0].click().then(x => { return clickElem("#root > div > div.container-main.container-fluid > div > div.row.block-spacer-top > div.col-12.col-lg-4 > div > div:nth-child(2) > div > div > div > a:nth-child(6)") }) await opts[1].click().then(x => { return clickElem("#root > div > div.container-main.container-fluid > div > div.row.block-spacer-top > div.col-12.col-lg-4 > div > div:nth-child(3) > div > div > div > div:nth-child(1)") }) page.$$("#root > div > div.container-main.container-fluid > div > div.row.block-spacer-top > div.col-12.col-lg-8 > div > a") .then(x => { if (x.length == 6) console.info(true) else console.error(false) browser.close() }) async function clickElem(selector) { return page.waitForSelector(selector, { visible: true, hidden: false }).then(x => x.click()) } }<filename>build.js // node.js based build script // run `node build -h` for usage information var _helpers = require('./_build/helpers'); var _config = require('./_build/config'); var _cli = require('commander'); var _path = require('path'); _cli .option('-s, --silent', 'suppress log messages.'); _cli .command('doc') .description('build documentation.') .action( cmd(buildDocs) ); _cli .command('pkg') .description('update packages and specs') .action( cmd(updatePackages) ); _cli .command('add <moduleName> [templateName]') .description('add a new module.') .action( cmd(addModule) ); _cli .command('mv <moduleName> <newName>') .description('rename module.') .action( cmd(renameModule) ); _cli .command('cjs <destinationPath>') .description('convert mout into a node.js compatible package.') .action( cmd(convert) ); _cli .command('release <version>') .description('bump version number, run tests, git tag, publish') .action( cmd(release) ); _cli .command('testling') .description('prepare files for ci.testling.com') .action( cmd(generateTestBundle) ); _cli .command('prune') .description('remove cjs files created during "release"') .action( cmd(prune) ); _cli.parse(process.argv); // show help by default if (!_cli.args.length) { _cli.outputHelp(); process.exit(0); } // just a helper to run multiple commands in sequence and process global // options before executing them. function cmd(){ var fns = Array.prototype.slice.call(arguments); return function(){ if (_cli.silent) { _helpers.isSilent = true; } var args = Array.prototype.slice.call(arguments); fns.forEach(function(fn){ fn.apply(null, args); }); }; } // -- function buildDocs(){ var mdoc = require('mdoc'); mdoc.run({ inputDir : 'doc', outputDir : 'doc_html', baseTitle : 'mout', indexContentPath : 'README.md', templatePath : '_build/doc_template' }); } function updatePackages(){ var pkg = require('./_build/package'); pkg.updateAllPackages(); } function addModule(moduleName, templateName){ var add = require('./_build/add'); add.createSource(moduleName, templateName); add.createSpec(moduleName); } function renameModule(moduleName, newName){ var rename = require('./_build/rename'); rename.renameModule(moduleName, newName); } function convert(destinationPath){ var glob = _path.join(_config.SRC_FOLDER, '/**/**.js'); _helpers.echo('Converting modules to node.js:'); require('nodefy').batchConvert(glob, destinationPath, function(err, results){ if (err) { console.error( err.toString() ); process.exit(1); } function checkKeys(mod, name){ try { var keys = Object.keys(mod); } catch (err) { throw new Error('"'+ name +'" is not an object'); } if (! keys.length ) { throw new Error('"'+ name +'" does\'t contain any enumerable properties'); } } try { // we load the index file and check if all the properties contain // keys to make sure module conversion worked properly this will // avoid npm publish mistakes like mout/mout#127 var index = require( _path.join(__dirname, destinationPath, 'index') ); checkKeys(index, 'mout'); for (var key in index) { if (key !== 'VERSION') checkKeys(index[key], 'mout.'+ key); } } catch (err) { console.error( 'node.js module conversion went wrong:' ); console.error( err.toString() ); process.exit(1); } results = results.map(function(r){ return r.outputPath; }); _helpers.echoList(results); _helpers.echo('Finished node.js conversion'); }); } function release(version){ if (! version) throw new Error('version is a required argument'); version = String(version).replace(/[^\d\.]/g, ''); var remote = require('./package.json').repository.url; updateJsonVersion('./package.json', version); updateJsonVersion('./bower.json', version); updateChangelog('./CHANGELOG.md', version); _helpers.shellSeries([ // make sure we checkout master so git will warn about uncommited // changes and it will also avoid publishing wrong branch 'git checkout master', // scripts.pretest already generates the packages 'npm test --coverage', 'git add -A', 'git commit --verbose', 'git tag v'+ version, 'git push '+ remote, 'git push --tags', // we do not rely on npm.scripts.prepublish because of // https://github.com/isaacs/npm/issues/3856 'node build cjs .', 'npm publish', 'node build prune' ], function(err){ if (err) { console.error(err.toString()); process.exit(1); } }); } function updateJsonVersion(path, version) { var target = require(path); var fs = require('fs'); target.version = version; fs.writeFileSync(path, JSON.stringify(target, null, ' '), _config.ENCODING); } function updateChangelog(path, version) { var fs = require('fs'); var content = fs.readFileSync(path).toString(); var release = 'v'+ version +' ('+ today() +')'; var dashedLine = (new Array(release.length + 1)).join('-'); // add version number and release date to changelog if first h2 doesn't // start with "v" content = content.replace(/^(?!v)[^\n]+\n\-+/m, release +'\n'+ dashedLine); fs.writeFileSync(path, content, _config.ENCODING); } function today(){ // YYYY/MM/DD var date = new Date(); var dateString = ''; dateString += date.getFullYear(); dateString += '/'+ pad(date.getMonth() + 1); dateString += '/'+ pad(date.getDate()); return dateString; } function pad(val){ val = String(val); if (val.length < 2) { val = '0'+ val; } return val; } // ci.testling.com can't load relative resources so we need to bundle all the // source files and tests into few files to make it work properly. // we can't use rawgithub.com to load the files dynamically since it can // timeout and was causing more issues (see #10). function generateTestBundle(){ var rjs = require('requirejs'); _helpers.echo('generateTestBundle: generating AMD bundles...'); // yes, it's ugly but works for now. rjs.optimize({ logLevel : 3, baseUrl : '.', optimize: 'none', name : 'mout/index', paths : { 'mout' : 'src' }, out : 'tests/testling/src.js' }, function(){ rjs.optimize({ logLevel : 3, baseUrl : '.', optimize: 'none', name : 'spec/spec-index', paths : { 'mout' : 'empty:', 'spec' : 'tests/spec' }, out : 'tests/testling/specs.js' }, function(){ _helpers.echo('generateTestBundle: done.'); }); }); } function prune(){ var ls = _helpers.getFolderStructure('./src'); var rimraf = require('rimraf'); var rm = line => rimraf.sync( _path.basename(line) ); ls.folders.map( rm ); ls.files.map( rm ); } <filename>app.js /** * @file 服务端入口文件 * @name server.js * @author <NAME> <<EMAIL>> * @copyright DXC 2017 * @version 1.0.0 */ // Koa:nodejs的web开发框架 const app = new (require("koa"))(); let connLimit = 30000; // 并发数 // 全局错误处理,并发量控制 app.use(async (ctx, next) => { if (connLimit) { connLimit--; // console.log('req num:', 30000 - connLimit) // 项目中不要使用ctx.throw抛出异常,使用ctx.body就地返回 // 不要使用 console.error输出异常 // 不要catch不能处理的异常 await next(); connLimit++; } else { ctx.status = 413; ctx.body = { status: 2, data: { msg: "We are too popular to busy!" } }; } }); // 单用户访问限制 if (process.env.REDIS) { let limit = false; const redis = new (require("ioredis"))({ autoResubscribe: false, autoResendUnfulfilledCommands: false, enableOfflineQueue: false, retryStrategy: () => 60000 // 1分钟 }); redis.on("error", () => { limit = false; }); redis.on("connect", () => { limit = true; }); // 每ip每分钟100(每个ip并发连接数)连接 app.use( require("koa-ratelimit")({ db: redis, duration: 60000, errorMessage: "Sometimes You Just Have to Slow Down.", id: ctx => (limit ? ctx.ip : false), max: 100 }) ); } // 启用gzip压缩,提高数据传输效率 app.use( require("koa-compress")({ threshold: 1024 * 1024 }) ); // cors app.use(require("kcors")()); // 缓存协商,根据etag判断待传输的数据有没有更新,没有更新返回304 Not Modified,不传输数据 app.use(require("koa-conditional-get")()); // 给传输的数据添加标识 app.use(require("koa-etag")()); // 解析请求body,100M大小限制 app.use( require("koa-bodyparser")({ formLimit: 1024 * 1024 * 100, jsonLimit: 1024 * 1024 * 100, textLimit: 1024 * 1024 * 100 }) ); // Koa 日志输出 if (process.env.NODE_LOG) app.use(require("koa-logger")()); // 引入自定义路由模块 app.use(require("./router/api").routes()); module.exports = app; // 在指定端口启动服务 app.listen(process.env.PORT || 3000); console.log( `Server running on port ${process.env.PORT || 3000}!\nnode version:${ process.version }` ); // 字符串模板 /* * Copyright (c) 2020 The Web eID Project * * 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. */ var config = Object.freeze({ VERSION: "0.9.0", EXTENSION_HANDSHAKE_TIMEOUT: 1000, NATIVE_APP_HANDSHAKE_TIMEOUT: 5 * 1000, DEFAULT_USER_INTERACTION_TIMEOUT: 2 * 60 * 1000, DEFAULT_SERVER_REQUEST_TIMEOUT: 20 * 1000, }); var ErrorCode; (function (ErrorCode) { // Timeout errors ErrorCode["ERR_WEBEID_ACTION_TIMEOUT"] = "ERR_WEBEID_ACTION_TIMEOUT"; ErrorCode["ERR_WEBEID_USER_TIMEOUT"] = "ERR_WEBEID_USER_TIMEOUT"; ErrorCode["ERR_WEBEID_SERVER_TIMEOUT"] = "ERR_WEBEID_SERVER_TIMEOUT"; // Health errors ErrorCode["ERR_WEBEID_VERSION_MISMATCH"] = "ERR_WEBEID_VERSION_MISMATCH"; ErrorCode["ERR_WEBEID_VERSION_INVALID"] = "ERR_WEBEID_VERSION_INVALID"; ErrorCode["ERR_WEBEID_EXTENSION_UNAVAILABLE"] = "ERR_WEBEID_EXTENSION_UNAVAILABLE"; ErrorCode["ERR_WEBEID_NATIVE_UNAVAILABLE"] = "ERR_WEBEID_NATIVE_UNAVAILABLE"; ErrorCode["ERR_WEBEID_UNKNOWN_ERROR"] = "ERR_WEBEID_UNKNOWN_ERROR"; // Security errors ErrorCode["ERR_WEBEID_CONTEXT_INSECURE"] = "ERR_WEBEID_CONTEXT_INSECURE"; ErrorCode["ERR_WEBEID_PROTOCOL_INSECURE"] = "ERR_WEBEID_PROTOCOL_INSECURE"; ErrorCode["ERR_WEBEID_TLS_CONNECTION_BROKEN"] = "ERR_WEBEID_TLS_CONNECTION_BROKEN"; ErrorCode["ERR_WEBEID_TLS_CONNECTION_INSECURE"] = "ERR_WEBEID_TLS_CONNECTION_INSECURE"; ErrorCode["ERR_WEBEID_TLS_CONNECTION_WEAK"] = "ERR_WEBEID_TLS_CONNECTION_WEAK"; ErrorCode["ERR_WEBEID_CERTIFICATE_CHANGED"] = "ERR_WEBEID_CERTIFICATE_CHANGED"; ErrorCode["ERR_WEBEID_ORIGIN_MISMATCH"] = "ERR_WEBEID_ORIGIN_MISMATCH"; // Third party errors ErrorCode["ERR_WEBEID_SERVER_REJECTED"] = "ERR_WEBEID_SERVER_REJECTED"; ErrorCode["ERR_WEBEID_USER_CANCELLED"] = "ERR_WEBEID_USER_CANCELLED"; ErrorCode["ERR_WEBEID_NATIVE_FATAL"] = "ERR_WEBEID_NATIVE_FATAL"; // Developer mistakes ErrorCode["ERR_WEBEID_ACTION_PENDING"] = "ERR_WEBEID_ACTION_PENDING"; ErrorCode["ERR_WEBEID_MISSING_PARAMETER"] = "ERR_WEBEID_MISSING_PARAMETER"; })(ErrorCode || (ErrorCode = {})); var ErrorCode$1 = ErrorCode; var Action; (function (Action) { Action["STATUS"] = "web-eid:status"; Action["STATUS_ACK"] = "web-eid:status-ack"; Action["STATUS_SUCCESS"] = "web-eid:status-success"; Action["STATUS_FAILURE"] = "web-eid:status-failure"; Action["AUTHENTICATE"] = "web-eid:authenticate"; Action["AUTHENTICATE_ACK"] = "web-eid:authenticate-ack"; Action["AUTHENTICATE_SUCCESS"] = "web-eid:authenticate-success"; Action["AUTHENTICATE_FAILURE"] = "web-eid:authenticate-failure"; Action["SIGN"] = "web-eid:sign"; Action["SIGN_ACK"] = "web-eid:sign-ack"; Action["SIGN_SUCCESS"] = "web-eid:sign-success"; Action["SIGN_FAILURE"] = "web-eid:sign-failure"; })(Action || (Action = {})); var Action$1 = Action; class CertificateChangedError extends Error { constructor(message = "server certificate changed between requests") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_CERTIFICATE_CHANGED; } } class OriginMismatchError extends Error { constructor(message = "URLs for a single operation require the same origin") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_ORIGIN_MISMATCH; } } const SECURE_CONTEXTS_INFO_URL = "https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"; class ContextInsecureError extends Error { constructor(message = "Secure context required, see " + SECURE_CONTEXTS_INFO_URL) { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_CONTEXT_INSECURE; } } class ExtensionUnavailableError extends Error { constructor(message = "Web-eID extension is not available") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_EXTENSION_UNAVAILABLE; } } class ActionPendingError extends Error { constructor(message = "same action for Web-eID browser extension is already pending") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_ACTION_PENDING; } } class NativeFatalError extends Error { constructor(message = "native application terminated with a fatal error") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_NATIVE_FATAL; } } class NativeUnavailableError extends Error { constructor(message = "Web-eID native application is not available") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_NATIVE_UNAVAILABLE; } } class ServerRejectedError extends Error { constructor(message = "server rejected the request") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_SERVER_REJECTED; } } class UserTimeoutError extends Error { constructor(message = "user failed to respond in time") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_USER_TIMEOUT; } } class UserCancelledError extends Error { constructor(message = "request was cancelled by the user") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_USER_CANCELLED; } } function tmpl(strings, requiresUpdate) { return `Update required for Web-eID ${requiresUpdate}`; } class VersionMismatchError extends Error { constructor(message, versions, requiresUpdate) { if (!message) { if (!requiresUpdate) { message = "requiresUpdate not provided"; } else if (requiresUpdate.extension && requiresUpdate.nativeApp) { message = tmpl `${"extension and native app"}`; } else if (requiresUpdate.extension) { message = tmpl `${"extension"}`; } else if (requiresUpdate.nativeApp) { message = tmpl `${"native app"}`; } } super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_VERSION_MISMATCH; this.requiresUpdate = requiresUpdate; if (versions) { const { library, extension, nativeApp } = versions; Object.assign(this, { library, extension, nativeApp }); } } } class TlsConnectionBrokenError extends Error { constructor(message = "TLS connection was broken") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_TLS_CONNECTION_BROKEN; } } class TlsConnectionInsecureError extends Error { constructor(message = "TLS connection was insecure") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_TLS_CONNECTION_INSECURE; } } class TlsConnectionWeakError extends Error { constructor(message = "TLS connection was weak") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_TLS_CONNECTION_WEAK; } } class ProtocolInsecureError extends Error { constructor(message = "HTTPS required") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_PROTOCOL_INSECURE; } } class ActionTimeoutError extends Error { constructor(message = "extension message timeout") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_ACTION_TIMEOUT; } } class VersionInvalidError extends Error { constructor(message = "invalid version string") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_VERSION_INVALID; } } class ServerTimeoutError extends Error { constructor(message = "server failed to respond in time") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_SERVER_TIMEOUT; } } class UnknownError extends Error { constructor(message = "an unknown error occurred") { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_UNKNOWN_ERROR; } } const errorCodeToErrorClass = { [ErrorCode$1.ERR_WEBEID_ACTION_PENDING]: ActionPendingError, [ErrorCode$1.ERR_WEBEID_ACTION_TIMEOUT]: ActionTimeoutError, [ErrorCode$1.ERR_WEBEID_CERTIFICATE_CHANGED]: CertificateChangedError, [ErrorCode$1.ERR_WEBEID_ORIGIN_MISMATCH]: OriginMismatchError, [ErrorCode$1.ERR_WEBEID_CONTEXT_INSECURE]: ContextInsecureError, [ErrorCode$1.ERR_WEBEID_EXTENSION_UNAVAILABLE]: ExtensionUnavailableError, [ErrorCode$1.ERR_WEBEID_NATIVE_FATAL]: NativeFatalError, [ErrorCode$1.ERR_WEBEID_NATIVE_UNAVAILABLE]: NativeUnavailableError, [ErrorCode$1.ERR_WEBEID_PROTOCOL_INSECURE]: ProtocolInsecureError, [ErrorCode$1.ERR_WEBEID_SERVER_REJECTED]: ServerRejectedError, [ErrorCode$1.ERR_WEBEID_SERVER_TIMEOUT]: ServerTimeoutError, [ErrorCode$1.ERR_WEBEID_TLS_CONNECTION_BROKEN]: TlsConnectionBrokenError, [ErrorCode$1.ERR_WEBEID_TLS_CONNECTION_INSECURE]: TlsConnectionInsecureError, [ErrorCode$1.ERR_WEBEID_TLS_CONNECTION_WEAK]: TlsConnectionWeakError, [ErrorCode$1.ERR_WEBEID_USER_CANCELLED]: UserCancelledError, [ErrorCode$1.ERR_WEBEID_USER_TIMEOUT]: UserTimeoutError, [ErrorCode$1.ERR_WEBEID_VERSION_INVALID]: VersionInvalidError, [ErrorCode$1.ERR_WEBEID_VERSION_MISMATCH]: VersionMismatchError, }; function deserializeError(errorObject) { let error; if (typeof errorObject.code == "string" && errorObject.code in errorCodeToErrorClass) { const CustomError = errorCodeToErrorClass[errorObject.code]; error = new CustomError(); } else { error = new UnknownError(); } for (const [key, value] of Object.entries(errorObject)) { error[key] = value; } return error; } class WebExtensionService { constructor() { this.queue = []; window.addEventListener("message", (event) => this.receive(event)); } receive(event) { var _a, _b, _c, _d; const message = event.data; const suffix = (_b = (_a = message.action) === null || _a === void 0 ? void 0 : _a.match(/success$|failure$|ack$/)) === null || _b === void 0 ? void 0 : _b[0]; const initialAction = this.getInitialAction(message.action); const pending = this.getPendingMessage(initialAction); if (suffix === "ack") { console.log("ack message", message); console.log("ack pending", pending === null || pending === void 0 ? void 0 : pending.message.action); console.log("ack queue", JSON.stringify(this.queue)); } if (pending) { switch (suffix) { case "ack": { clearTimeout(pending.ackTimer); break; } case "success": { (_c = pending.resolve) === null || _c === void 0 ? void 0 : _c.call(pending, message); this.removeFromQueue(initialAction); break; } case "failure": { (_d = pending.reject) === null || _d === void 0 ? void 0 : _d.call(pending, message.error ? deserializeError(message.error) : message); this.removeFromQueue(initialAction); break; } } } } send(message, timeout) { if (this.getPendingMessage(message.action)) { return Promise.reject(new ActionPendingError()); } else if (!window.isSecureContext) { return Promise.reject(new ContextInsecureError()); } else { const pending = { message }; this.queue.push(pending); pending.promise = new Promise((resolve, reject) => { pending.resolve = resolve; pending.reject = reject; }); pending.ackTimer = setTimeout(() => this.onAckTimeout(pending), config.EXTENSION_HANDSHAKE_TIMEOUT); pending.replyTimer = setTimeout(() => this.onReplyTimeout(pending), timeout); window.postMessage(message, "*"); return pending.promise; } } onReplyTimeout(pending) { var _a; console.log("onReplyTimeout", pending.message.action); (_a = pending.reject) === null || _a === void 0 ? void 0 : _a.call(pending, new ActionTimeoutError()); this.removeFromQueue(pending.message.action); } onAckTimeout(pending) { var _a; console.log("onAckTimeout", pending.message.action); (_a = pending.reject) === null || _a === void 0 ? void 0 : _a.call(pending, new ExtensionUnavailableError()); clearTimeout(pending.replyTimer); } getPendingMessage(action) { return this.queue.find((pm) => { return pm.message.action === action; }); } getSuccessAction(action) { return `${action}-success`; } getFailureAction(action) { return `${action}-failure`; } getInitialAction(action) { return action.replace(/-success$|-failure$|-ack$/, ""); } removeFromQueue(action) { const pending = this.getPendingMessage(action); clearTimeout(pending === null || pending === void 0 ? void 0 : pending.replyTimer); this.queue = this.queue.filter((pending) => (pending.message.action !== action)); } } const semverPattern = new RegExp("^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)" + "(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"); var IdentifierDiff; (function (IdentifierDiff) { IdentifierDiff[IdentifierDiff["NEWER"] = 1] = "NEWER"; IdentifierDiff[IdentifierDiff["SAME"] = 0] = "SAME"; IdentifierDiff[IdentifierDiff["OLDER"] = -1] = "OLDER"; })(IdentifierDiff || (IdentifierDiff = {})); function parseSemver(string = "") { const result = string.match(semverPattern); const [, majorStr, minorStr, patchStr, rc, build] = result ? result : []; const major = parseInt(majorStr, 10); const minor = parseInt(minorStr, 10); const patch = parseInt(patchStr, 10); for (const indentifier of [major, minor, patch]) { if (Number.isNaN(indentifier)) { throw new VersionInvalidError(`Invalid SemVer string '${string}'`); } } return { major, minor, patch, rc, build, string }; } /** * Compares two Semver objects. * * @param {Semver} a First SemVer object * @param {Semver} b Second Semver object * * @returns {SemverDiff} Diff for major, minor and patch. */ function compareSemver(a, b) { return { major: Math.sign(a.major - b.major), minor: Math.sign(a.minor - b.minor), patch: Math.sign(a.patch - b.patch), }; } /** * Checks if update is required. * * @param version Object containing SemVer version strings for library, extension and native app. * * @returns Object which specifies if the extension or native app should be updated. */ function checkCompatibility(version) { const library = parseSemver(version.library); const extension = parseSemver(version.extension); const nativeApp = parseSemver(version.nativeApp); const extensionDiff = compareSemver(extension, library); const nativeAppDiff = compareSemver(nativeApp, library); return { extension: extensionDiff.major === IdentifierDiff.OLDER, nativeApp: nativeAppDiff.major === IdentifierDiff.OLDER, }; } /** * Checks an object if 'library', 'extension' or 'nativeApp' properties are present. * Values are not checked for SemVer validity. * * @param object Object which will be checked for version properties. * * @returns Were any of the version properties found in the provided object. */ function hasVersionProperties(object) { if (typeof object === "object") { for (const prop of ["library", "extension", "nativeApp"]) { if (Object.hasOwnProperty.call(object, prop)) return true; } } return false; } class MissingParameterError extends Error { constructor(message) { super(message); this.name = this.constructor.name; this.code = ErrorCode$1.ERR_WEBEID_MISSING_PARAMETER; } } function defer() { return new Promise((resolve) => setTimeout(resolve)); } const webExtensionService = new WebExtensionService(); async function status() { await defer(); // Give chrome a moment to load the extension content script let statusResponse; const library = config.VERSION; const timeout = config.EXTENSION_HANDSHAKE_TIMEOUT + config.NATIVE_APP_HANDSHAKE_TIMEOUT; const message = { action: Action$1.STATUS }; try { statusResponse = await webExtensionService.send(message, timeout); } catch (error) { error.library = library; throw error; } const versions = { library, ...statusResponse }; const requiresUpdate = checkCompatibility(versions); if (requiresUpdate.extension || requiresUpdate.nativeApp) { throw new VersionMismatchError(undefined, versions, requiresUpdate); } return versions; } async function authenticate(options) { await defer(); // Give chrome a moment to load the extension content script if (typeof options != "object") { throw new MissingParameterError("authenticate function requires an options object as parameter"); } if (!options.getAuthChallengeUrl) { throw new MissingParameterError("getAuthChallengeUrl missing from authenticate options"); } if (!options.postAuthTokenUrl) { throw new MissingParameterError("postAuthTokenUrl missing from authenticate options"); } const timeout = (config.EXTENSION_HANDSHAKE_TIMEOUT + config.NATIVE_APP_HANDSHAKE_TIMEOUT + (options.serverRequestTimeout || config.DEFAULT_SERVER_REQUEST_TIMEOUT) * 2 + (options.userInteractionTimeout || config.DEFAULT_USER_INTERACTION_TIMEOUT)); const message = { ...options, action: Action$1.AUTHENTICATE }; const result = await webExtensionService.send(message, timeout); return result.response; } async function sign(options) { await defer(); // Give chrome a moment to load the extension content script if (typeof options != "object") { throw new MissingParameterError("sign function requires an options object as parameter"); } if (!options.postPrepareSigningUrl) { throw new MissingParameterError("postPrepareSigningUrl missing from sign options"); } if (!options.postFinalizeSigningUrl) { throw new MissingParameterError("postFinalizeSigningUrl missing from sign options"); } const timeout = (config.EXTENSION_HANDSHAKE_TIMEOUT + config.NATIVE_APP_HANDSHAKE_TIMEOUT + (options.serverRequestTimeout || config.DEFAULT_SERVER_REQUEST_TIMEOUT) * 2 + (options.userInteractionTimeout || config.DEFAULT_USER_INTERACTION_TIMEOUT) * 2); const message = { ...options, action: Action$1.SIGN }; const result = await webExtensionService.send(message, timeout); return result.response; } export { Action$1 as Action, ErrorCode$1 as ErrorCode, authenticate, config, hasVersionProperties, sign, status }; <reponame>ap--/annotorious import EventEmitter from 'tiny-emitter'; import RubberbandRectTool from './rectangle/RubberbandRectTool'; import RubberbandPolygonTool from './polygon/RubberbandPolygonTool'; import { SVG_NAMESPACE } from '../util/SVG'; /** The drawing tool 'registry' **/ class DrawingToolRegistry extends EventEmitter { constructor(g, config, env) { super(); // SVG annotation layer group this._g = g; // Annotorious user config this._config = config; // Environment settings this._env = env; // Registered tool implementations this._registered = {}; // Current drawing tool this._current = null; this.setDefaults(); } setDefaults() { this.registerTool('rect', RubberbandRectTool); this.registerTool('polygon', RubberbandPolygonTool); this.setCurrent('rect'); } registerTool = (id, impl) => { this._registered[id] = impl; } /** * Sets a drawing tool by providing an implementation, or the ID * of a built-in toll. */ setCurrent = toolOrId => { if (typeof toolOrId === 'string' || toolOrId instanceof String) { const Tool = this._registered[toolOrId]; if (Tool) { this._current = new Tool(this._g, this._config, this._env); this._current.on('complete', evt => this.emit('complete', evt)); this._current.on('cancel', evt => this.emit('cancel', evt)); } } else { this._current = toolOrId; } } /** TODO inefficient - maybe organize this in a different way **/ forShape = svgShape => { const inner = svgShape.querySelector('.a9s-inner'); const Tool = this._registered[inner.nodeName]; return Tool ? new Tool(this._g, this._config, this._env) : null; } get current() { return this._current; } } export default DrawingToolRegistry; /** * Common code for drawing resize handles */ export const drawHandle = (x, y) => { const containerGroup = document.createElementNS(SVG_NAMESPACE, 'g'); containerGroup.setAttribute('class', 'a9s-handle'); containerGroup.setAttribute('transform-origin', `${x}px ${y}px`); const group = document.createElementNS(SVG_NAMESPACE, 'g'); group.setAttribute('transform-origin', `${x}px ${y}px`); const drawCircle = r => { const c = document.createElementNS(SVG_NAMESPACE, 'circle'); c.setAttribute('cx', x); c.setAttribute('cy', y); c.setAttribute('r', r); return c; } const inner = drawCircle(6); inner.setAttribute('class', 'a9s-handle-inner') const outer = drawCircle(7); outer.setAttribute('class', 'a9s-handle-outer') group.appendChild(outer); group.appendChild(inner); containerGroup.appendChild(group); return containerGroup; } /** * Common code for setting handle position */ export const setHandleXY = (handle, x, y) => { handle.setAttribute('transform-origin', `${x}px ${y}px`); handle.firstChild.setAttribute('transform-origin', `${x}px ${y}px`); const inner = handle.querySelector('.a9s-handle-inner'); inner.setAttribute('cx', x); inner.setAttribute('cy', y); const outer = handle.querySelector('.a9s-handle-outer'); outer.setAttribute('cx', x); outer.setAttribute('cy', y); } import { Factory, faker, } from '@bigtest/mirage'; import { associatedJobProfiles } from '../../mocks'; import { fieldsConfig } from '../../../../src/utils/fields-config'; import { INCOMING_RECORD_TYPES, FOLIO_RECORD_TYPES, } from '../../../../src/components/ListTemplate'; import { COMPARISON_PARTS, CRITERION_TYPES, VALUE_TYPES, } from '../../../../src/utils/constants'; export default Factory.extend({ id: () => faker.random.uuid(), name: i => `Name ${i}`, description: i => `Description ${i}`, tags: { tagList: [faker.random.arrayElement(['tag1', 'tag2', 'tag3'])] }, entityType: 'INVENTORY_ITEM', incomingRecordType: () => faker.random.arrayElement(Object.keys(INCOMING_RECORD_TYPES)), existingRecordType: () => faker.random.arrayElement(Object.keys(FOLIO_RECORD_TYPES)), matchDetails: [ { incomingRecordType: () => faker.random.arrayElement(Object.keys(INCOMING_RECORD_TYPES)), existingRecordType: () => faker.random.arrayElement(Object.keys(FOLIO_RECORD_TYPES)), matchCriterion: () => faker.random.arrayElement(CRITERION_TYPES.map(type => type.value)), existingMatchExpression: { dataValueType: () => faker.random.arrayElement(VALUE_TYPES.map(type => type.value)), fields: [{ label: 'field', value: () => faker.random.arrayElement(fieldsConfig.map(field => field.value)), }], qualifier: { comparisonPart: () => faker.random.arrayElement(COMPARISON_PARTS.map(type => type.value)) }, }, incomingMatchExpression: { dataValueType: () => faker.random.arrayElement(VALUE_TYPES.map(type => type.value)), fields: [{ label: 'field', value: '001', }, { label: 'indicator1', value: '', }, { label: 'indicator2', value: '', }, { label: 'recordSubfield', value: 'a', }], qualifier: { comparisonPart: () => faker.random.arrayElement(COMPARISON_PARTS.map(type => type.value)) }, }, }, ], deleted: 'false', parentProfiles: associatedJobProfiles, childProfiles: [], metadata: { updatedDate: faker.date.past(0.1, faker.date.past(0.1)).toString() }, userInfo: { firstName: faker.name.firstName(), lastName: faker.name.lastName(), userName: faker.name.lastName(), }, }); return ['$scope', '$stateParams', '$state', 'webservice', 'songService', 'uploadFileService', 'globals', function ($scope, $stateParams, $state, webservice, songService, uploadFileService, globals) { var song_id = $stateParams.song_id || ''; var back = $stateParams.back || ''; if (!!back) { $scope.song = songService.get(); } else { $scope.song = {}; } var language = 'chinese'; $scope.hasChangeFile = false; $scope.hasUploadFile = false; $scope.hasChangePic = false; $scope.hasUploadPic = false; if (!$scope.song.song_id) { $scope.loading = true; $scope.failing = false; $scope.empty = false; webservice.getSongRow(language, song_id).then(function (res) { $scope.loading = false; var status = res.status; if (globals.STATUS_OK === status) { $scope.song = res.data; var items = []; items.push($scope.song.song); $scope.items = items; } else if (globals.SPECIFIC_ERROR === status) { $scope.empty = true; } else { $scope.failing = true; } }, function (res) { $scope.loading = false; $scope.failing = true; var res = res; }); } $scope.getFile = function (file) { $scope.myFile = file; uploadFileService.readAsDataUrl($scope.myFile, $scope).then(function (res) { $scope.song.filename = $scope.myFile.name; $scope.song.song = res; var items = []; items.push($scope.song.song); $scope.items = items; $scope.hasChangeFile = true; }, function (res) { var tip = '儿歌歌曲预览失败,请重新选择'; $scope.$emit('TOAST', {msg: tip}); var res = res; }); }; $scope.uploadFile = function () { if (!$scope.myFile) { var tip = '请选择需要上传的儿歌歌曲'; $scope.$emit('TOAST', {msg: tip}); return; } $scope.$emit('BUSY'); webservice.uploadFile($scope.myFile, globals.SONG).then(function (res) { $scope.$emit('NOTBUSY'); var status = res.status; var tip = res.message; if (globals.STATUS_OK === status) { $scope.song.filename = res.data && res.data.name; $scope.song.song = res.data && res.data.url; var items = []; items.push($scope.song.song); $scope.items = items; $scope.hasUploadFile = true; } $scope.$emit('TOAST', {msg: tip}); }, function (res) { $scope.$emit('NOTBUSY'); $scope.$emit('TOAST', {msg: globals.NO_NETWORK_TEXT}); var res = res; }); }; $scope.getPic = function (pic) { $scope.myPic = pic; uploadFileService.readAsDataUrl($scope.myPic, $scope).then(function (res) { $scope.song.picname = $scope.myPic.name; $scope.song.pic = res; $scope.hasChangePic = true; }, function (res) { var tip = '儿歌图片预览失败,请重新选择'; $scope.$emit('TOAST', {msg: tip}); var res = res; }); }; $scope.uploadPic = function () { if (!$scope.myPic) { var tip = '请选择需要上传的儿歌图片'; $scope.$emit('TOAST', {msg: tip}); return; } $scope.$emit('BUSY'); webservice.uploadPic($scope.myPic, globals.SONG).then(function (res) { $scope.$emit('NOTBUSY'); var status = res.status; var tip = res.message; if (globals.STATUS_OK === status) { $scope.song.picname = res.data && res.data.name; $scope.song.pic = res.data && res.data.url; $scope.hasUploadPic = true; } $scope.$emit('TOAST', {msg: tip}); }, function (res) { $scope.$emit('NOTBUSY'); $scope.$emit('TOAST', {msg: globals.NO_NETWORK_TEXT}); var res = res; }); }; $scope.editSongPreview = function () { var songName = $scope.song.name; var songContent = $scope.song.content; var songSong = $scope.song.song; var songPic = $scope.song.pic; if (!songName) { var tip = '儿歌名称不能为空'; $scope.$emit('TOAST', {msg: tip}); return; } else if (songName.length > 50) { var tip = '儿歌名称长度不能超过50个字符'; $scope.$emit('TOAST', {msg: tip}); return; } if (!songContent) { var tip = '儿歌歌词不能为空'; $scope.$emit('TOAST', {msg: tip}); return; } else if (songContent.length > 4000) { var tip = '儿歌歌词长度不能超过4000个字符'; $scope.$emit('TOAST', {msg: tip}); return; } if (!songSong) { var tip = '请选择需要上传的儿歌歌曲'; $scope.$emit('TOAST', {msg: tip}); return; } if ($scope.hasChangeFile) { if (!$scope.hasUploadFile) { var tip = '请上传选择的儿歌歌曲'; $scope.$emit('TOAST', {msg: tip}); return; } } if (!songPic) { var tip = '请选择需要上传的儿歌图片'; $scope.$emit('TOAST', {msg: tip}); return; } if ($scope.hasChangePic) { if (!$scope.hasUploadPic) { var tip = '请上传选择的儿歌图片'; $scope.$emit('TOAST', {msg: tip}); return; } } songService.set($scope.song); $state.go('main.song.chinese.preview', { song_id: song_id }); }; if (!$scope.$$phase) { $scope.$apply(); } }]; <filename>src/components/Bar/Bar.js import React from 'react'; const { Link } = require('react-router'); const { pushPath } = require('redux-simple-router'); const { connect } = require('react-redux'); import BarList from '../../containers/bar-list'; import BarCounts from '../../containers/bar-counts'; const Bar = React.createClass({ render: function() { return ( <div className="container"> <h1>Bar</h1> <BarList /> <BarCounts /> </div> ); } }); export default connect( null, { pushPath } )(Bar); 'use strict'; // Write a function to convert between currencies // EUR, PLN and USD as reported by NBP API // as of 2018-01-02 // // Example values: // value = 10 // from = 'USD' // to = 'PLN' // // Return a promise that will resolve to the result of conversion. const currency = (value, from, to) => { // ... }; module.exports = { currency, }; var opter = require('opter'), version = require('./package.json').version, express = require('express'); /******************************* PARSING OPTIONS *******************************/ var options = { authToken: { argument: 'token', description: 'The token for the user to log in as.' }, userId: { argument: 'id', description: 'The user id of the user to log in as.' }, roomId: { argument: 'id', description: 'The id of the room to join.' }, dbHost: { argument: 'host', defaultValue: 'localhost', description: 'The Mongo DB host to connect to' }, dbPort: { argument: 'number', defaultValue: '27017', description: 'The Mongo DB port' }, dbName: { argument: 'name', defaultValue: 'ttfm', description: 'The Mongo DB to connect to' }, dbUser: { argument: 'user', description: 'The Mongo DB user' }, dbPassword: { argument: 'password', description: 'The Mongo DB password' }, lastFmApiKey: { argument: 'key', defaultValue: '', description: 'The last.fm API key' }, lastFmSecret: { argument: 'secret', defaultValue: '', description: 'The last.fm secret' } }, config = opter(options, version); /******************************* Status route (to keep heroku happy) *******************************/ var app = express(express.logger()); app.get('/', function(request, response) { response.send('Bot is running!'); }); var port = process.env.PORT || 5000; app.listen(port, function() { console.log('Listening on ' + port); }); /******************************* Bot Logic *******************************/ var ExtendedBot = require('./lib/ExtendedBot.js'), BopperAddOn = require('./lib/BopperAddOn.js'), TwssAddOn = require('./lib/TwssAddOn.js'), GreeterAddOn = require('./lib/GreeterAddOn.js'), SongTrackerAddOn = require('./lib/SongTrackerAddOn.js'), UserTrackerAddOn = require('./lib/UserTrackerAddOn.js'), AchievementsTrackerAddOn = require('./lib/AchievementsTrackerAddOn.js'), DjAddOn = require('./lib/DjAddOn.js'), EscortMeAddOn = require('./lib/EscortMeAddOn.js'), AfkAddOn = require('./lib/AfkTrackerAddOn.js'), DjQueueAddOn = require('./lib/DjQueueAddOn.js'), LastFmAddOn = require('./lib/LastFmAddOn.js'), VotingAddOn = require('./lib/VotingAddOn.js'), bot = new ExtendedBot(config.authToken, config.userId, config.roomId), dbConnectionString = 'mongodb://'; if (config.dbUser && config.dbUser.length && config.dbPassword && config.dbPassword.length) { dbConnectionString += config.dbUser + ':' + config.dbPassword + '@'; } dbConnectionString += config.dbHost + ':' + config.dbPort + '/' + config.dbName; // register greeter addon bot.registerAddOn(GreeterAddOn); // register bopper addon bot.registerAddOn(BopperAddOn); // register escort me addon bot.registerAddOn(EscortMeAddOn); // register twss addon bot.registerAddOn(TwssAddOn); // register dj addon bot.registerAddOn(DjAddOn); // register dj queue addon bot.registerAddOn(DjQueueAddOn, { djSongLimit: 2 }); // register lastfm addon bot.registerAddOn(LastFmAddOn, { lastFmApiKey: config.lastFmApiKey, lastFmSecret: config.lastFmSecret }); // register voting addon bot.registerAddOn(VotingAddOn); // register afk addon bot.registerAddOn(AfkAddOn, { afkThreshold: 60 * 15 }); // afk threshold of 15 minutes // register song tracker addon bot.registerAddOn(SongTrackerAddOn, { dbConnectionString: dbConnectionString }); // register user tracker addon bot.registerAddOn(UserTrackerAddOn, { dbConnectionString: dbConnectionString }); // register achievements tracker addon bot.registerAddOn(AchievementsTrackerAddOn, { dbConnectionString: dbConnectionString }); function BuildMaze() { if (Charactercheck == null) { Charactercheck = 0 cellsizesetter = Charactercheck localStorage.setItem("mySize", cellsizesetter) cellsize = myCellsizeSet[cellsizesetter] document.getElementById('myh102').innerHTML = "Difficulty " + mydiff } else { cellsize = myCellsizeSet[Charactercheck] document.getElementById('myh102').innerHTML = "Difficulty " + mydiff } Charactercheck = parseInt(localStorage.getItem("mySize")) pointCheck = localStorage.getItem("myPoints") if (pointCheck == null) { //cellsize = myCellsizeSet[0] cellsizestter = Charactercheck cellsize = myCellsizeSet[cellsizesetter] points = [] MakeNewMaze() MakeMazeStorage() } else { cellsizestter = Charactercheck cellsize = myCellsizeSet[cellsizesetter] pointCheck = eval('[' + pointCheck + ']') useMazeStorage() MakeCurrentMaze() } } function MakeMazeStorage() { myTempMapArray = []; start = 0; end = start + 4; for (let i = 0; i < points.length / 4; i++) { myTempMapArray.push(points.slice(start, end)) start = start + 4; end = start + 4; } return myTempMapArray } function useMazeStorage() { myTempMapArray = []; start = 0; end = start + 4; for (let i = 0; i < pointCheck.length / 4; i++) { myTempMapArray.push(pointCheck.slice(start, end)) start = start + 4; end = start + 4; } return myTempMapArray } function MakeCurrentMaze() { for (let i = 0; i in myTempMapArray; i++) { line(myTempMapArray[i][0], myTempMapArray[i][1], myTempMapArray[i][2], myTempMapArray[i][3]); draw('black') } return myTempMapArray } function MakeNewMaze() { points = [] for (let y = 0; y <= canvas.height; y += cellsize) { for (let x = 0; x <= canvas.width; x += cellsize) { switch (Math.round(Math.random())) { case 0: switch (Math.round(Math.random())) { case 0: line(x, y, x + cellsize, y); points.push([x, y, x + cellsize, y]); break; case 1: line(x, y, x + cellsize, y); points.push([x, y, x + cellsize, y]); break; } break; case 1: switch (Math.round(Math.random())) { case 0: line(x, y, x, y + cellsize); points.push([x, y, x, y + cellsize]); break; case 1: line(x, y, x, y - cellsize); points.push([x, y, x, y - cellsize]); break; } break; } draw('black') line(pl.x, pl.y, pl.s, pl.s) draw('white') } //////////////////////////////////console.log(points) localStorage.setItem("myPoints", points) } }'use strict'; const os = require('os'); const path = require('path'); const fs = require('fs'); const test = require('supertape'); const tryToCatch = require('try-to-catch'); const tryCatch = require('try-catch'); const writejson = require('..'); const {readFile, unlink} = fs.promises; const tmp = os.tmpdir(); const NAME = path.join(tmp, String(Math.random())); const json = { hello: 'world', bye: 'sword', }; test('writejson: should write json data to file', async (t) => { await writejson(NAME, json); const data = await readFile(NAME, 'utf8'); await unlink(NAME); t.deepEqual(json, JSON.parse(data), 'data should be equal'); t.end(); }); test('writejson: should write json data to file with options', async (t) => { const result = { hello: 'world', }; const options = { replacer: ['hello'], space: 2, eof: false, }; const resultStr = JSON.stringify(json, options.replacer, options.space); await writejson(NAME, json, options); const data = await readFile(NAME, 'utf8'); await unlink(NAME); t.equal(resultStr, data, 'data should be equal'); t.deepEqual(JSON.parse(data), result, 'objects should be equal'); t.end(); }); test('writejson: should write json data to file with default options', async (t) => { const resultStr = JSON.stringify(json, null, 4) + '\n'; await writejson(NAME, json); const data = await readFile(NAME, 'utf8'); await unlink(NAME); t.equal(resultStr, data, 'data should be equal'); t.deepEqual(JSON.parse(data), json, 'objects should be equal'); t.end(); }); test('writejson: write error', async (t) => { const [error] = await tryToCatch(writejson, '/hello.json', json); t.ok(error, 'should return error: ' + error.message); t.end(); }); test('writejson: write options', async (t) => { const json = { hello: 'world', }; const options = { mode: 0o600, }; await tryToCatch(writejson, NAME, json, options); const {mode} = fs.statSync(NAME); const expected = Number(mode).toString(8).slice(3); fs.unlinkSync(NAME); t.equal(expected, '600', 'should equal'); t.end(); }); test('writejson.sync.try: write error', (t) => { const error = writejson.sync.try('/hello.json', json); t.ok(error, 'should return error: ' + error.message); t.end(); }); test('writejson: no args', async (t) => { const [e] = await tryToCatch(writejson); t.equal(e.message, 'name should be string!'); t.end(); }); test('writejson: no json', async (t) => { const [e] = await tryToCatch(writejson, 'hello'); t.equal(e.message, 'json should be object!'); t.end(); }); test('writejson: options not object', async (t) => { const [error] = await tryToCatch(writejson, 'hello', {}, 'options'); t.equal(error.message, 'options should be object!'); t.end(); }); test('writejson.sync: should write json data to file synchonously', (t) => { writejson.sync(NAME, json); const data = fs.readFileSync(NAME, 'utf8'); fs.unlinkSync(NAME); t.ok(data, 'data should be read'); t.deepEqual(json, JSON.parse(data), 'data should be equal'); t.end(); }); test('writejson.sync: no args', (t) => { t.throws(writejson.sync, /name should be string!/, 'NAME check'); t.end(); }); test('writejson.sync: no json', (t) => { const fn = () => writejson.sync('hello'); t.throws(fn, /json should be object!/, 'json check'); t.end(); }); test('writejson.sync.try: no args', (t) => { t.throws(writejson.sync.try, /name should be string!/, 'NAME check'); t.end(); }); test('writejson.sync.try: no json', (t) => { const [error] = tryCatch(writejson.sync.try, 'hello'); t.ok(error, error.message); t.end(); }); <gh_stars>0 /* eslint-disable react-native/no-inline-styles */ import React from 'react'; import { SafeAreaView, View, Text, StyleSheet, Image, Platform, } from 'react-native'; // REDUX import {useDispatch} from 'react-redux'; import {setUser, setLogin} from '../../reducer/userSlice'; import {colors, images, width, height} from '../../config/globalStyles'; import {SocialButton} from '../../components/SocialButton'; import {signInKakaoTalk} from './loginKakao'; import {signInApple} from './loginApple'; import Logo from '../../assets/svg/dreamingLogo'; function LoginScreen({navigation}) { const dispatch = useDispatch(); const setUserInfo = params => { dispatch(setUser(params)); }; const setLoggedIn = token => { dispatch(setLogin(token)); }; return ( <SafeAreaView style={[styles.container]}> <View style={styles.LogoSection}> <Logo width={150} height={400} /> </View> <View style={{flex: 1}}> <Text style={styles.headerSection}> 운동을 올바르게{' '} <Text style={{ color: '#20C1A1', fontWeight: 'bold', fontSize: 18, }}> right </Text> </Text> <Text style={styles.headerSection}> 똑똑하게 기록하기{' '} <Text style={{fontWeight: 'bold', color: '#20C1A1', fontSize: 18}}> write </Text> </Text> </View> <View style={styles.divederSection}> <View style={{flex: 1, height: 1, backgroundColor: '#F8FAFF'}} /> <View> <Text style={styles.dividerText}>⚡️ 3초만에 빠른 회원가입 </Text> </View> <View style={{flex: 1, height: 1, backgroundColor: '#F8FAFF'}} /> </View> <View style={styles.snsSection}> <SocialButton style={{backgroundColor: colors.kakaoTalk}} onPress={() => { signInKakaoTalk(setUserInfo, setLoggedIn); }}> <Image style={{width: 15, height: 15}} source={images.kakao} /> <Text style={{...styles.socialText, color: '#421919'}}> 카카오톡으로 로그인하기 </Text> </SocialButton> {Platform.OS === 'ios' && ( <View> <SocialButton style={{backgroundColor: colors.apple}} onPress={() => { signInApple(setUserInfo, setLoggedIn); }}> <Image style={{width: 14, height: 17}} source={images.apple} /> <Text style={{...styles.socialText, color: colors.white}}> Apple로 로그인하기 </Text> </SocialButton> </View> )} </View> </SafeAreaView> ); } const styles = StyleSheet.create({ LogoSection: { flex: height < 0.85 ? 2.5 : 1.8, marginRight: width * 10, }, container: { flex: 1, padding: 20, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', backgroundColor: colors.white, }, headerSection: { // width: width * 200, textAlign: 'center', color: '#424141', fontWeight: '300', fontSize: 14, }, divederSection: { flexDirection: 'row', alignItems: 'center', marginTop: 10, flex: 0.5, }, dividerText: { width: width * 200, textAlign: 'center', color: colors.lightGrey, fontWeight: 'bold', }, socialText: { color: colors.textGrey, fontSize: 16, fontWeight: 'bold', marginLeft: 6, }, snsSection: { flex: 1.5, alignItems: 'center', }, }); export default LoginScreen; <gh_stars>1-10 const { documentInclusionArray } = require('./../../documentParser/config.js') const { documentInclusionLogic } = require('./../../documentParser/inclusionLogic.js') const mockInclusionLogic = `async function documentInclusionLogic({ data }, btwArray) { /* istanbul ignore next */cov_2p7fblcvls.f[4]++; const numArrayResponse = /* istanbul ignore next */(cov_2p7fblcvls.s[7]++, await mapSections(data, btwArray)); /* istanbul ignore next */cov_2p7fblcvls.s[8]++; return subStringSections(data, numArrayResponse); }` /* const mockInclusionLogic = `async function documentInclusionLogic({ data }, btwArray) { const numArrayResponse = await mapSections(data, btwArray); return subStringSections(data, numArrayResponse); }` */ // const mockInclusionLogic = '[Function documentInclusionLogic]' const mockInclusionArray = [{"after": "class=\"d-none js-permalink-shortcut\" ", "before": "class=\"d-none js-permalink-shortcut\" data-hotkey=\"y\">Permalink</a>", "postIns": "", "preIns": "<html><body><h1>TEST</h1></body></html>"}, {"after": "class=\"d-none js-permalink-shortcut\" data-hotkey=\"y\">Permalink</a>", "before": "class=\"d-none js-permalink-shortcut\" data-hotkey=\"y\">Permalink</a>", "postIns": "", "preIns": ""}] // const mockInclusionArray = "[object Object],[object Object]" it('test 1, InclusionArray', () => { expect(documentInclusionArray).toEqual(documentInclusionArray); }); it('test 1, InclusionLogic', () => { expect(documentInclusionLogic).toEqual(documentInclusionLogic); }); it('test 2, InclusionArray', () => { expect(documentInclusionArray).toEqual(mockInclusionArray); }); it('test 2, InclusionLogic', () => { expect(`${documentInclusionLogic}`).toEqual(mockInclusionLogic); }); <filename>src/views/register/component/index.js /** * Created by cjy on 16/11/23. */ import React, {Component} from 'react'; import {Redirect, Link} from 'react-router-dom'; import routes from 'constants/routes'; import './style.scss'; export default class Register extends Component { state = { password: '', password1: '', account: '', } render() { const {isLogin, login, toast} = this.props; const {password, password1, account} = this.state; if (isLogin === true) { return <Redirect to={'/'}/> } return ( <div className="v-register-root"> <div> <i className="logo icon icon-snowflake-o"/> </div> <div className="info-box"> <input type="text" value={account} maxLength={16} onChange={e => this.setState({account: e.target.value})} placeholder="请输入账号"/> <input type="password" value={password} maxLength={16} onChange={e => this.setState({password: e.target.value})} placeholder="请输入密码"/> <input type="password" value={password1} maxLength={16} onChange={e => this.setState({password1: e.target.value})} placeholder="请确认密码"/> <Link to={routes.login} className="primary to-login">已有账号?去登陆</Link> </div> <div className="button-box"> <div onClick={::this.register} className="btn">注册并登陆 </div> </div> </div> ) } register() { const {toast, register, history} = this.props; const {password, password1, account} = this.state; if (!account) { return toast({text: '请输入账号', toastType: 'error'}); } if (!password || password !== <PASSWORD>) { return toast({text: '两次密码不一致', toastType: 'error'}); } register({username: account, password, <PASSWORD>}, res => { if(res.code == 0){ return history.push('/') } toast({text: res.message, toastType: 'error'}); }) } }<filename>test/cypress/integration/02-collective.transactions.test.js describe('collective.transactions', () => { it('Should have no-index meta for user profiles', () => { cy.visit('/xdamman/transactions'); cy.getByDataCy('transactions-page-content'); // Wait for page to be loaded cy.get('meta[name="robots"]').should('have.attr', 'content', 'none'); }); it('Should NOT have no-index meta for collectives', () => { cy.visit('/apex/transactions'); cy.getByDataCy('transactions-page-content'); // Wait for page to be loaded cy.get('meta[name="robots"]').should('not.exist'); }); it("shows the 'Download CSV' button", () => { cy.visit('/apex/transactions'); cy.get('[data-cy=download-csv]').contains('Download CSV'); }); it('shows a message when the result is empty for the given date range', () => { cy.visit('/apex/transactions'); cy.get('[data-cy=download-csv]').click(); // Date range that won't ever contain any results cy.get('[data-cy=download-csv-start-date] input').click().type('1970-01-01').blur(); cy.wait(300); // Second input doesn't get right value unless we wait cy.get('[data-cy=download-csv-end-date] input').click().type('1970-02-01').blur(); // There should be an error message when download is clicked cy.wait(300); cy.get('[data-cy=download-csv-download]').click(); // Then it should show an error message cy.get('[data-cy=download-csv-error]').contains('There are no transactions in this date range.'); }); }); import { HOME_COUNTER_PLUS_ONE, } from './constants'; export function counterPlusOne() { return { type: HOME_COUNTER_PLUS_ONE, }; } export function reducer(state, action) { switch (action.type) { case HOME_COUNTER_PLUS_ONE: return { ...state, count: state.count + 1, }; default: return state; } } <filename>client/src/config/api-urls.js export const TASK_API = '/tasks'; export const FB_LOGIN = '/login/fb'; export const GOOGLE_LOGIN = '/login/google'; export const NORMAL_LOGIN = '/login/normal'; export const FB_SIGNUP = '/signup/fb'; export const GOOGLE_SIGNUP = '/signup/google'; export const NORMAL_SIGNUP = '/signup/normal';<gh_stars>0 'use strict'; const React = require('react'); const rB = require('react-bootstrap'); const AppActions = require('../actions/AppActions'); const TableApps = require('./TableApps'); const TableCAs = require('./TableCAs'); const AppStatus = require('./AppStatus'); const NewError = require('./NewError'); const ManagementPanel = require('./ManagementPanel'); const Transfer = require('./Transfer'); const Accept = require('./Accept'); const Query = require('./Query'); const AppInfo = require('./AppInfo'); const AppUsage = require('./AppUsage'); const Buy = require('./Buy'); const Confirmation = require('./Confirmation'); const cE = React.createElement; class MyApp extends React.Component { constructor(props) { super(props); this.state = this.props.ctx.store.getState(); } componentDidMount() { if (!this.unsubscribe) { this.unsubscribe = this.props.ctx.store .subscribe(this._onChange.bind(this)); this._onChange(); } } componentWillUnmount() { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; } } _onChange() { if (this.unsubscribe) { this.setState(this.props.ctx.store.getState()); } } render() { const pendingAccepts = this.state.userInfo.accepts && (Object.keys(this.state.userInfo.accepts).length > 0); return cE("div", {className: "container-fluid"}, cE(AppInfo, { ctx: this.props.ctx, appInfo: this.state.appInfo }), cE(AppUsage, { ctx: this.props.ctx, appUsage: this.state.appUsage }), cE(Transfer, { ctx: this.props.ctx, transferMode: this.state.transferMode, transferUsername: this.state.transferUsername, transferUnits: this.state.transferUnits, transfers: this.state.userInfo.offers || {} }), cE(Accept, { ctx: this.props.ctx, acceptMode: this.state.acceptMode, accepts: this.state.userInfo.accepts || {} }), cE(Query, { ctx: this.props.ctx, queryMode: this.state.queryMode, queryUsername: this.state.queryUsername, myStats: this.state.userInfo.reputation, stats: this.state.stats }), cE(Buy, { ctx: this.props.ctx, buyMode: this.state.buyMode, buyUnits: this.state.buyUnits, price: this.state.price, clientId: this.state.clientId, pendingOrders: this.state.pendingOrders, orders: this.state.orders }), cE(Confirmation, { ctx: this.props.ctx, capturedOrder: this.state.capturedOrder, confirmation: this.state.confirmation }), cE(NewError, { ctx: this.props.ctx, error: this.state.error }), cE(rB.Panel, null, cE(rB.Panel.Heading, null, cE(rB.Panel.Title, null, cE(rB.Grid, {fluid: true}, cE(rB.Row, null, cE(rB.Col, {sm:1, xs:1}, cE(AppStatus, { isClosed: this.state.isClosed }) ), cE(rB.Col, { sm: 5, xs:10, className: 'text-right' }, 'People' + (this.state.bankBalance ? ' $' + this.state.bankBalance : '')), cE(rB.Col, { sm: 5, xs:11, className: 'text-right' }, this.state.fullName) ) ) ) ), cE(rB.Panel.Body, null, cE(rB.Panel, null, cE(rB.Panel.Heading, null, cE(rB.Panel.Title, null, "User") ), cE(rB.Panel.Body, null, cE(ManagementPanel, { ctx: this.props.ctx, units: this.state.userInfo.user || 0, username: this.state.username, allUsers: this.state.allUsers, privileged: this.state.privileged, pendingId: this.state.pendingId, deltaUnits: this.state.deltaUnits, changeUnitsId: this.state.changeUnitsId, pendingAccepts: pendingAccepts, cost: this.state.cost, appNameCost: this.state.appNameCost }) ) ), cE(rB.Panel, null, cE(rB.Panel.Heading, null, cE(rB.Panel.Title, null, "Applications") ), cE(rB.Panel.Body, null, cE(TableApps, { ctx: this.props.ctx, apps: this.state.userInfo.apps }) ) ), cE(rB.Panel, null, cE(rB.Panel.Heading, null, cE(rB.Panel.Title, null, "CAs") ), cE(rB.Panel.Body, null, cE(TableCAs, {cas: this.state.userInfo.cas}) ) ) ) ) ); } }; module.exports = MyApp; BN.addDecl('bold').blockTemplate(function(ctx){ ctx.tag('b'); });var Hapi = require('hapi') var server = new Hapi.Server() server.connection({ host: 'localhost', port: Number(process.argv[2] || 8080) }) function handler (request, reply) { reply('Hello ' + request.params.name) } server.route({ method: 'GET', path: '/{name}', handler: handler }) server.start() //// [exportDefaultTypeClassAndValue.ts] const foo = 1 export default foo export default class Foo {} type Bar = {} export default Bar //// [exportDefaultTypeClassAndValue.js] "use strict"; exports.__esModule = true; var foo = 1; exports["default"] = foo; var Foo = /** @class */ (function () { function Foo() { } return Foo; }()); exports["default"] = Foo; <reponame>drom/reqack<gh_stars>10-100 {assign:[ ['i.req', ['&', 't0.req', 't1.req', '...']], ['t0.ack', ['&', 'i.ack', ['&', '1', 't1.req', '...']]], ['t1.ack', ['&', 'i.ack', ['&', 't0.req', '1', '...']]], ]} <reponame>onosfw/apis<filename>onos/apis/classorg_1_1onosproject_1_1net_1_1intent_1_1impl_1_1phase_1_1FinalIntentProcessPhase.js var classorg_1_1onosproject_1_1net_1_1intent_1_1impl_1_1phase_1_1FinalIntentProcessPhase = [ [ "data", "classorg_1_1onosproject_1_1net_1_1intent_1_1impl_1_1phase_1_1FinalIntentProcessPhase.html#a96a53eec76b9f5feeb48c4e5e6b82439", null ], [ "execute", "classorg_1_1onosproject_1_1net_1_1intent_1_1impl_1_1phase_1_1FinalIntentProcessPhase.html#a1fcbbdb9d950c71cf25dc0d5b8d3f00a", null ], [ "preExecute", "classorg_1_1onosproject_1_1net_1_1intent_1_1impl_1_1phase_1_1FinalIntentProcessPhase.html#a49537a1f71e607060705580bf7701877", null ] ];const { existsSync, readFileSync } = require('fs') const exec = require('../utils/exec.js') const log = require('../utils/logger.js') const getWd = require('../utils/get-wd.js') const postPullHandlers = { js: () => { log('installing all npm dependencies...', 'info') exec('npm i') log('successfully installed all dependencies!', 'success') const { scripts } = JSON.parse(readFileSync('package.json', 'utf8')) if (scripts.build) { log('this project seems to contain a build script, executing it...', 'info') exec('npm run build') log('build script successfully executed!', 'success') } } } module.exports = (repoData) => { process.chdir(getWd(repoData, { lvl: 'branch' })) log('checking repository type...', 'info') const repoType = checkRepoType() if (!postPullHandlers[repoType]) { log('this repository type does not have any associated post-pull operations to perform', 'info') } else { log(`repository seems to be of type ${repoType}...`, 'info') postPullHandlers[repoType]() } } function checkRepoType () { if (existsSync('package.json')) { return 'js' } return null } <reponame>cityofasheville/PSQL-JOBS<filename>gis-jobs.js var yaml = require('yamljs'); var pg = require('pg'); var program = require('commander'); pg.defaults.poolsize = 10; //args program .version('0.0.1') .usage('[options] ') .option('-d, --databaseconn <file>', 'PostGres database connection file <file> default is config/db.yml', String, 'config/db.yml') .option('-m, --maintenance <file>', 'maintenance configuration file <file>', String) .option('-t, --datatest <file>', 'data test configuration file <file>', String) .parse(process.argv); /** Load yaml file for database connection using YAML.load do not change the name of database connection file db.yml or it will be pushed to gitHub :-( **/ var dataBaseConnectionObject = yaml.load(program.databaseconn); //sleep function //short rest to allow for sql insert to complete //found that this actuall increases the speed of inserts var sleep = function (milliSeconds) { 'use strict'; var startTime = new Date().getTime(); // get the current time //Loop till time change in millisecons matches what was passed in while (new Date().getTime() < startTime + milliSeconds) { } }; //gets duration based on start and end time milliseconds var msToTime = function (duration) { 'use strict'; var milliseconds = duration, seconds = parseInt((duration / 1000) % 60), minutes = parseInt((duration / (1000 * 60)) % 60), hours = parseInt((duration / (1000 * 60 * 60)) % 24); hours = (hours < 10) ? "0" + hours : hours; minutes = (minutes < 10) ? "0" + minutes : minutes; seconds = (seconds < 10) ? "0" + seconds : seconds; return hours + ":" + minutes + ":" + seconds + "." + milliseconds; }; var on_queryMessages = function (current, rowcount, arr, secarr) { 'use strict'; //first pass starting if (rowcount === 0) { console.log(' '); console.log(' Starting: ' + arr[rowcount]); } //called when completed; console.log(' Completed: ' + current.name); if (typeof secarr !== "undefined") { console.log(' ' + secarr[rowcount]); } console.log(' '); rowcount = rowcount + 1; var percentComplete = ((rowcount / arr.length ) * 100).toFixed(2); console.log(' Percent Completed: %' + percentComplete); //if not last call add starting of next one if (rowcount > 0 && rowcount < arr.length) { console.log(' Starting: ' + arr[rowcount]); } return rowcount; }; /** _____ _ _______ _ | __ \ | | |__ __| | | | | | | __ _| |_ __ _ | | ___ ___| |_ ___ | | | |/ _` | __/ _` | | |/ _ \/ __| __/ __| | |__| | (_| | || (_| | | | __/\__ \ |_\__ \ |_____/ \__,_|\__\__,_| |_|\___||___/\__|___/ data tests passed as argument? if so run the data testests the argiument must be a yaml file **/ if (program.datatest) { var startTime = new Date().getTime(); var endTime; //objects var dataTests_YAML = yaml.load(program.datatest); var dataTests_Obj = dataTests_YAML.tests; //clients for data data tests var dataTests_client; var dataTestsSuccess_client; //date tests varriables var dataTests_queryConfig; var dataTests_check = true; var dataTests_checkRun = false; var dataTests_array = []; var dataTests_resultsArray = []; var dataTests_rowcount = 0; //varrables for dataTestsSuccess var dataTestsSuccess_queryConfig; var dataTestsSucesss_array = []; var dataTestsSuccess_rowcount = 0; //generic error callback for client,queries var dataTests_connectionError = function (err) { 'use strict'; if (err) { console.error("Connection Error: %s", err); dataTests_resultsArray.push('FAILED'); dataTests_check = false; } return err; }; //data test drain callback when all maintenace queries finish var dataTests_clientDrain = function () { 'use strict'; dataTests_client.end(); }; //generic error callback for client,queries var dataTests_clientError = function (err) { 'use strict'; if (err) { console.error("Client Error: %s", err); dataTests_resultsArray.push('FAILED'); dataTests_check = false; } return err; }; //when client ends var dataTests_clientEnd = function (result) { 'use strict'; console.log('Tests Complete.'); //all tests completed and one of them failed if (!dataTests_check) { //something failed console.log('FAILED test(s) for: ' + dataTests_YAML.testname + '.'); console.log('Failed a test! Please see the log for details'); //time endTime = new Date().getTime(); var aTime = endTime - startTime; var timeMessage = msToTime(aTime); console.log('completed in ' + timeMessage); console.log(' '); } //all tests completed and succesfull if (dataTests_check && !dataTests_checkRun) { console.log('PASSED all tests for: ' + dataTests_YAML.testname + '.'); dataTestsSuccess(); } return result; }; //generic error callback for client,queries var dataTests_queryError = function (err) { 'use strict'; if (err) { console.error("Query Error: %s", err); dataTests_resultsArray.push('FAILED'); dataTests_check = false; } else { } return err; }; /** query on row method. for data tests when a row exists named check we use that to determine a pass or fail. when we encounter any fail we change the Tests state to fail with dataTests_check. **/ var dataTests_queryRow = function (row, result) { 'use strict'; if (row.hasOwnProperty('check')) { if (row.check) { dataTests_resultsArray.push('PASSED'); } else { dataTests_resultsArray.push('FAILED'); dataTests_check = false; } } else { dataTests_resultsArray.push('FAILED'); dataTests_check = false; } }; //when query ends var dataTests_queryEnd = function (result) { 'use strict'; if (result.rowCount === 0) { dataTests_resultsArray.push('FAILED'); dataTests_check = false; } dataTests_rowcount = on_queryMessages(this, dataTests_rowcount, dataTests_array, dataTests_resultsArray); }; //data tests functionå var dataTests = function () { 'use strict'; var id; //open client and connection for Buidling Buffers dataTests_client = new pg.Client(dataBaseConnectionObject) .on('drain', dataTests_clientDrain) .on('error', dataTests_clientError) .on('end', dataTests_clientEnd); //connect dataTests_client.connect(dataTests_connectionError); console.log(' '); console.log('Running Test(s) for ' + dataTests_YAML.testname); for (id in dataTests_Obj) { if (dataTests_Obj.hasOwnProperty(id)) { dataTests_queryConfig = dataTests_Obj[id]; dataTests_array.push(dataTests_queryConfig.name); dataTests_client.query(dataTests_queryConfig) .on('error', dataTests_queryError) .on('row', dataTests_queryRow) .on('end', dataTests_queryEnd); } } }; //data test sucessfull drain callback when all maintenace queries finish var dataTestsSuccess_clientDrain = function () { 'use strict'; dataTestsSuccess_client.end(); }; //generic error callback for client,queries var dataTestsSuccess_clientError = function (err) { 'use strict'; if (err) { console.error("Client Error: %s", err); } return err; }; //generic error callback for client,queries var dataTestsSuccess_connectionError = function (err) { 'use strict'; if (err) { console.error("Connection Error: %s", err); } return err; }; //when client ends var dataTestsSuccess_clientEnd = function (result) { 'use strict'; endTime = new Date().getTime(); var aTime = endTime - startTime; var timeMessage = msToTime(aTime); console.log('completed Data Test in ' + timeMessage); console.log(' '); return result; }; //data tests successful query row callback var dataTestsSuccess_queryRow = function (row, result) { 'use strict'; return row; }; //generic error callback for client,queries var dataTestsSuccess_queryError = function (err) { 'use strict'; if (err) { console.error("Query Error: %s", err); } return err; }; //when query ends var dataTestsSuccess_queryEnd = function (result) { 'use strict'; dataTestsSuccess_rowcount = on_queryMessages(this, dataTestsSuccess_rowcount, dataTestsSucesss_array); }; //data tests success full run these queries var dataTestsSuccess = function () { 'use strict'; var id; var dataTests_successCommands = dataTests_YAML.onsuccess; console.log(''); console.log('Running Data Push for ' + dataTests_YAML.testname); //open client and connection for Buidling Buffers dataTestsSuccess_client = new pg.Client(dataBaseConnectionObject) .on('drain', dataTestsSuccess_clientDrain) .on('error', dataTestsSuccess_clientError) .on('end', dataTestsSuccess_clientEnd); //connect dataTestsSuccess_client.connect(dataTestsSuccess_connectionError); for (id in dataTests_successCommands) { if (dataTests_successCommands.hasOwnProperty(id)) { dataTests_checkRun = true; dataTestsSuccess_queryConfig = dataTests_successCommands[id]; dataTestsSucesss_array.push(dataTestsSuccess_queryConfig.name); dataTestsSuccess_client.query(dataTestsSuccess_queryConfig) .on('error', dataTestsSuccess_queryError) .on('row', dataTestsSuccess_queryRow) .on('end', dataTestsSuccess_queryEnd); } } }; //run data tests dataTests(); } //maintenance passed as argument? /* __ __ _ _ | \/ | (_) | | | \ / | __ _ _ _ __ | |_ ___ _ __ __ _ _ __ ___ ___ | |\/| |/ _` | | '_ \| __/ _ \ '_ \ / _` | '_ \ / __/ _ \ | | | | (_| | | | | | || __/ | | | (_| | | | | (_| __/ |_| |_|\__,_|_|_| |_|\__\___|_| |_|\__,_|_| |_|\___\___| */ if (program.maintenance) { var startTime = new Date().getTime(); var endTime; //load maintenance yaml var maintenance_YAML = yaml.load(program.maintenance); //clients for data maintenace var maintenance_client; //objects var maintenance_Obj = maintenance_YAML.sql; var maintenance_queryConfig; //varrables for maintenance_queryEnd var maintenance_rowcount = 0; var maintenance_array = []; //maintence error callback var maintenance_connectionError = function (err) { 'use strict'; if (err) { console.error("Connection Error: %s", err); } return err; }; //maintence drain callback when all maintenace queries finish var maintenance_clientDrain = function () { 'use strict'; maintenance_client.end(); }; //maintence error callback var maintenance_clientError = function (err) { 'use strict'; if (err) { console.error("Client Error: %s", err); } return err; }; //when client ends var maintenance_clientEnd = function (result) { 'use strict'; endTime = new Date().getTime(); var aTime = endTime - startTime; var timeMessage = msToTime(aTime); console.log('Completed Maintenance in ' + timeMessage + '.'); console.log(' '); return result; }; //maintence error callback var maintenance_queryError = function (err) { 'use strict'; if (err) { console.error("Query Error: %s", err); } return err; }; //maintenance query row callback var maintenance_queryRow = function (row, result) { 'use strict'; return row; }; /** query end callback for maintenance provides feedback about progress and status of build **/ var maintenance_queryEnd = function (result) { 'use strict'; maintenance_rowcount = on_queryMessages(this, maintenance_rowcount, maintenance_array); }; /* main function for runnong sql based maintenace */ var maintenance = function () { 'use strict'; var id; console.log(' '); console.log('Starting the Running of Maintenance job.'); //open client and connection for Buidling Buffers maintenance_client = new pg.Client(dataBaseConnectionObject) .on('drain', maintenance_clientDrain) .on('error', maintenance_clientError) .on('end', maintenance_clientEnd); //connect maintenance_client.connect(maintenance_connectionError); for (id in maintenance_Obj) { if (maintenance_Obj.hasOwnProperty(id)) { maintenance_queryConfig = maintenance_Obj[id]; maintenance_array.push(maintenance_queryConfig.name); maintenance_client.query(maintenance_queryConfig) .on('error', maintenance_queryError) .on('row', maintenance_queryRow) .on('end', maintenance_queryEnd); } } }; //run maintenance(); maintenance(); } pg.end(); // Book class class Book { constructor(title, author, isbn) { this.title = title; this.author = author; this.isbn = isbn; } } // UI elements class UI { addToBookList(newBook) { const tbody = document.getElementById("book-list"); const tr = document.createElement("tr"); tr.innerHTML = `<td>${newBook.title}</td> <td>${newBook.author}</td> <td>${newBook.isbn}</td> <td><a href="#" class='delete'>X</a></td>`; tbody.appendChild(tr); } // clears are inputs clearFields() { document.getElementById("author").value = ""; document.getElementById("title").value = ""; document.getElementById("isbn").value = ""; } // alert messages alert(message, type) { let div = document.createElement("div"); div.className = `alert ${type}`; div.appendChild(document.createTextNode(message)); const container = document.querySelector(".container"); const form = document.getElementById("book-form"); container.insertBefore(div, form); setTimeout(function() { document.querySelector(".alert").remove(); }, 3000); } // Delete book from list deleteBook(target) { if (target.className === "delete") { target.parentElement.parentElement.remove(); } } } class Store { static getBooks() { let books; if (localStorage.getItem("books") === null) { books = []; } else { books = JSON.parse(localStorage.getItem("books")); } return books; } static displayBooks() { const books = Store.getBooks(); books.forEach(function(book) { console.log(book); const ui = new UI(); ui.addToBookList(book); }); } static addBook(book) { const books = Store.getBooks(); books.push(book); localStorage.setItem("books", JSON.stringify(books)); } static removeBook(isbn) { const books = Store.getBooks(); books.forEach(function(book, index){ if(book.isbn === isbn) { books.splice(index, 1); } }); localStorage.setItem('books', JSON.stringify(books)); } } // Display books document.addEventListener('DOMContentLoaded', Store.displayBooks); // Event Listener for add book document.getElementById("book-form").addEventListener("submit", function(e) { const title = document.getElementById("title").value; const author = document.getElementById("author").value; const isbn = document.getElementById("isbn").value; const newBook = new Book(title, author, isbn); const ui = new UI(); // Validate inputs al of them are required if (title == "" || author == "" || isbn == "") { ui.alert("Please fill in all fields", "error"); } else { ui.addToBookList(newBook); Store.addBook(newBook); ui.alert("Added successfully", "success"); ui.clearFields(); } e.preventDefault(); }); // Event listener for deleting book document.getElementById("book-list").addEventListener("click", function(e) { const ui = new UI(); ui.deleteBook(e.target); Store.removeBook(e.target.parentElement.previousElementSibling.textContent); ui.alert("Deleted successfully", "success"); e.preventDefault(); }); // if (document.readyState === 'loading') { // document.addEventListener("DOMContentLoaded", Store.displayBooks); // } else { // console.log("document is already ready, just execute code here"); // Store.displayBooks; // }<filename>shared/routes/elements/infrastructure/components/top-pages/TopPages.js import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import s from './TopPages.scss'; export default class TopPages extends PureComponent { static propTypes = { children: PropTypes.node, heading: PropTypes.string, } render() { const { children, heading } = this.props; return ( <div className={s.top}> <div className={s.top__container}> <h2 className={s.top__heading}>{heading}</h2> <div className={s.top__grid}> {children} </div> </div> </div> ); } } $( document ).ready(function() { var src = "https://docs.google.com/forms/d/e/1FAIpQLScv02GWUgovQC8r7fVk9MIfxfhf1f_R8E_d3Nl3tTT2hVDl1w/viewform?usp=pp_url&entry.1328749061="; src += userID ; document.getElementById('iframeEvaluation').src = src; $('#button_evaluation').click(function (event) { addInteraction('button_evaluation', 'click', 'click'); window.location.href = base + '/thanks'; }); }); var count = 0; function load() { count++; if(count===2){ $('#button_evaluation').css('display', 'flex') } }<reponame>commercetools/merchant-center-graphql-explorer const fs = require('fs'); const path = require('path'); const headersStaticFiles = { 'cache-control': 's-maxage=31536000,immutable' }; // This transformer will generate a `vercel.json` config file, based on the application // environment config and custom headers. module.exports = ({ headers }) => { const config = { version: 2, public: true, builds: [ { src: 'public/**', use: '@vercel/static' }, { src: 'vercel-deployment/routes/fallback.js', use: '@vercel/node' }, ], routes: [ { src: '/(.*).(js.map|js|css|txt|html|png)', dest: '/public/$1.$2', headers: headersStaticFiles, }, { src: '/(login|logout)', dest: '/vercel-deployment/routes/fallback.js' }, { src: '/(.*)', // eslint-disable-next-line headers: Object.assign({ 'Cache-Control': 'no-cache' }, headers), dest: '/public/index.html', }, ], }; fs.writeFileSync( path.join(__dirname, `../vercel.json`), JSON.stringify(config, null, 2), { encoding: 'utf8' } ); }; <reponame>elanalynn/portfolio_2020<filename>src/templates/artTemplate.js import React from "react" import { graphql } from "gatsby" import { Layout } from "../components/Layout/Layout" import "./artTemplate.scss" export default function ArtTemplate({ data, path }) { const { markdownRemark } = data const { frontmatter: { date, description, image, medium, tags, title }, } = markdownRemark return ( <Layout pageTitle={title} path={path}> <div className="art-detail"> <div className="art-data"> <h1>{title}</h1> <p>{date.substring(date.length - 4)}</p> <em>{medium}</em> <p>{description}</p> {tags.map(tag => ( <label key={tag} className={tag}> {tag} </label> ))} </div> <div className="art-content"> <img src={`https://elanalynn-assets.s3-us-west-1.amazonaws.com/${image}.jpg`} alt={description} /> </div> </div> </Layout> ) } export const pageQuery = graphql` query($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { html frontmatter { date(formatString: "MMMM DD, YYYY") description image medium path title tags } } } ` // Copyright (c) 2019, <NAME> and contributors // For license information, please see license.txt frappe.ui.form.on('Meeting', { refresh: function(frm) { frm.add_custom_button(__('View Minutes'), function () { frappe.route_options = {"meeting": frm.doc.name} frappe.set_route("List", "Meeting Minute", "List"); }); frm.add_custom_button(__('View Minutes in Form'), function () { console.log("MEETING", frm.doc.name) frappe.call({ method: "meeting.api.get_minutes_for_meeting", args: { meeting_name: frm.doc.name } }).done((r) => { console.log(r); var template = '<ul>' + '{% for(var i=0; i<=minutes.length; i++) { %}' + '<li>{{ minutes[i] }}</li>' + '{% } %}' + '</ul>'; var html = frappe.render_template(template, {"minutes": r.message}); frm.set_value("minutes_html", html); }); }); }, }); <filename>node_modules/sprotty/lib/utils/logging.js "use strict"; /******************************************************************************** * Copyright (c) 2017-2018 TypeFox and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the Eclipse * Public License v. 2.0 are satisfied: GNU General Public License, version 2 * with the GNU Classpath Exception which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 ********************************************************************************/ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __spreadArrays = (this && this.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; Object.defineProperty(exports, "__esModule", { value: true }); var inversify_1 = require("inversify"); var types_1 = require("../base/types"); var LogLevel; (function (LogLevel) { LogLevel[LogLevel["none"] = 0] = "none"; LogLevel[LogLevel["error"] = 1] = "error"; LogLevel[LogLevel["warn"] = 2] = "warn"; LogLevel[LogLevel["info"] = 3] = "info"; LogLevel[LogLevel["log"] = 4] = "log"; })(LogLevel = exports.LogLevel || (exports.LogLevel = {})); var NullLogger = /** @class */ (function () { function NullLogger() { this.logLevel = LogLevel.none; } NullLogger.prototype.error = function (thisArg, message) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } }; NullLogger.prototype.warn = function (thisArg, message) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } }; NullLogger.prototype.info = function (thisArg, message) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } }; NullLogger.prototype.log = function (thisArg, message) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } }; NullLogger = __decorate([ inversify_1.injectable() ], NullLogger); return NullLogger; }()); exports.NullLogger = NullLogger; var ConsoleLogger = /** @class */ (function () { function ConsoleLogger() { this.logLevel = LogLevel.log; this.viewOptions = { baseDiv: '' }; } ConsoleLogger.prototype.error = function (thisArg, message) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } if (this.logLevel >= LogLevel.error) try { console.error.apply(thisArg, this.consoleArguments(thisArg, message, params)); } catch (error) { } }; ConsoleLogger.prototype.warn = function (thisArg, message) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } if (this.logLevel >= LogLevel.warn) try { console.warn.apply(thisArg, this.consoleArguments(thisArg, message, params)); } catch (error) { } }; ConsoleLogger.prototype.info = function (thisArg, message) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } if (this.logLevel >= LogLevel.info) try { console.info.apply(thisArg, this.consoleArguments(thisArg, message, params)); } catch (error) { } }; ConsoleLogger.prototype.log = function (thisArg, message) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } if (this.logLevel >= LogLevel.log) try { console.log.apply(thisArg, this.consoleArguments(thisArg, message, params)); } catch (error) { } }; ConsoleLogger.prototype.consoleArguments = function (thisArg, message, params) { var caller; if (typeof thisArg === 'object') caller = thisArg.constructor.name; else caller = thisArg; var date = new Date(); return __spreadArrays([date.toLocaleTimeString() + ' ' + this.viewOptions.baseDiv + ' ' + caller + ': ' + message], params); }; __decorate([ inversify_1.inject(types_1.TYPES.LogLevel), __metadata("design:type", Number) ], ConsoleLogger.prototype, "logLevel", void 0); __decorate([ inversify_1.inject(types_1.TYPES.ViewerOptions), __metadata("design:type", Object) ], ConsoleLogger.prototype, "viewOptions", void 0); ConsoleLogger = __decorate([ inversify_1.injectable() ], ConsoleLogger); return ConsoleLogger; }()); exports.ConsoleLogger = ConsoleLogger; //# sourceMappingURL=logging.js.mapimport React from 'react'; import { shallow } from 'enzyme'; import MainSidebar from '../../components/MainSidebar'; test('should correctly render MainSidebar', () => { const wrapper = shallow(<MainSidebar />); expect(wrapper).toMatchSnapshot(); });import './sortEditor.scss' import React, { useState, useEffect } from 'react' import { connect } from 'react-redux' import * as Expression from '@core/expressionParser/expression' import * as DataSort from '@common/surveyRdb/dataSort' import Popup from '@webapp/commonComponents/popup' import * as ExpressionVariables from '@webapp/commonComponents/expression/expressionVariables' import { useI18n, usePrevious } from '@webapp/commonComponents/hooks' import * as Survey from '@core/survey/survey' import * as SurveyState from '@webapp/survey/surveyState' import SortRow from './sortRow' const SortExpressionComponent = props => { const { lang } = useI18n() const { onClose } = props const [sortCriteria, setSortCriteria] = useState(props.sort) // Keep reference of old sortCriteria const sortCriteriaStrPrev = usePrevious(DataSort.toString(props.sort), '') const [unchosenVariables, setUnchosenVariables] = useState([]) const [updated, setUpdated] = useState(false) useEffect(() => { refreshUnchosenVariables() }, [sortCriteria]) const onSelectVariable = (pos, variable) => { setSortCriteria(DataSort.updateVariable(pos, variable)(sortCriteria)) } const onSelectOrder = (pos, order) => { setSortCriteria(DataSort.updateOrder(pos, order)(sortCriteria)) setUpdated(true) } const refreshUnchosenVariables = () => { const availableVariables = getAvailableVariables(props, lang) setUnchosenVariables(DataSort.getUnchosenVariables(availableVariables)(sortCriteria)) } const addCriteria = ({ value: variable, label }) => { setSortCriteria(DataSort.addCriteria(variable, label, DataSort.keys.order.asc)(sortCriteria)) setUpdated(true) } const deleteCriteria = pos => { setSortCriteria(DataSort.deleteCriteria(pos)(sortCriteria)) setUpdated(true) } const applyAndClose = sortCriteria => { const { onChange, onClose } = props if (DataSort.toString(sortCriteria) !== sortCriteriaStrPrev) { if (onChange) onChange(sortCriteria) } onClose() } const applyChange = () => { applyAndClose(sortCriteria) } const reset = () => { applyAndClose([]) } const getAvailableVariables = () => { const { survey, nodeDefUuidCols, nodeDefContext, mode } = props const variables = ExpressionVariables.getVariables(survey, nodeDefContext, null, mode, lang) return variables.filter(v => nodeDefUuidCols.includes(v.uuid)) } const availableVariables = getAvailableVariables() return ( <Popup className="sort-editor-popup" onClose={onClose} padding={20}> <React.Fragment> <div className="sort-editor__criteria"> {sortCriteria.map((criteria, pos) => ( <SortRow key={criteria.variable} variables={unchosenVariables} selectedVariable={DataSort.findVariableByValue(criteria.variable)(availableVariables)} onSelectVariable={item => onSelectVariable(pos, item)} selectedOrder={criteria.order} onSelectOrder={order => onSelectOrder(pos, order)} onDelete={() => deleteCriteria(pos)} isFirst={!pos} /> ))} {Boolean(unchosenVariables.length > 0) && ( <SortRow variables={unchosenVariables} onSelectVariable={item => addCriteria(item)} isPlaceholder={true} isFirst={!sortCriteria.length} /> )} </div> <div className="sort-editor__footer"> <button className="btn btn-xs" onClick={() => reset()} aria-disabled={!sortCriteria.length}> <span className="icon icon-undo2 icon-16px" /> Reset </button> <button className="btn btn-xs" onClick={() => applyChange()} aria-disabled={!updated}> <span className="icon icon-checkmark icon-16px" /> Apply </button> </div> </React.Fragment> </Popup> ) } const mapStateToProps = (state, props) => { const survey = SurveyState.getSurvey(state) const { nodeDefUuidContext, nodeDefUuidCols } = props const nodeDefContext = Survey.getNodeDefByUuid(nodeDefUuidContext)(survey) const mode = Expression.modes.sql return { survey, nodeDefUuidCols, nodeDefContext, mode, } } export default connect(mapStateToProps)(SortExpressionComponent) export default [ { id: '5706647302', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 88125890, name: '879479119/chrome-extension-shanbay', url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay', }, payload: { push_id: 1685849109, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '231ff54708e89fe18e9e896c03b3cda72720595e', before: 'dd1b7b0bf4c1351a6f96b90564654541c88249ab', commits: [ { sha: '231ff54708e89fe18e9e896c03b3cda72720595e', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'permission checked', distinct: true, url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay/commits/231ff54708e89fe18e9e896c03b3cda72720595e', }, ], }, public: true, created_at: '2017-04-18T11:55:19Z', }, { id: '5705655711', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 88125890, name: '879479119/chrome-extension-shanbay', url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay', }, payload: { push_id: 1685521876, size: 4, distinct_size: 4, ref: 'refs/heads/master', head: 'dd1b7b0bf4c1351a6f96b90564654541c88249ab', before: 'bb4bb305e92db79e16a7ef618c3dfbdf8a641163', commits: [ { sha: 'b45aec013d326ca1851d632bb359489c2d71419b', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':lollipop: reconstruct', distinct: true, url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay/commits/b45aec013d326ca1851d632bb359489c2d71419b', }, { sha: '503c9177f2c03027f3ab5fd8c9a94c30f490cf4e', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':lollipop: three level filter', distinct: true, url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay/commits/503c9177f2c03027f3ab5fd8c9a94c30f490cf4e', }, { sha: 'cbee9325aef8be05f4383b48f1d059b55c0ff717', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'release version', distinct: true, url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay/commits/cbee9325aef8be05f4383b48f1d059b55c0ff717', }, { sha: 'dd1b7b0bf4c1351a6f96b90564654541c88249ab', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: '添加一些注释', distinct: true, url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay/commits/dd1b7b0bf4c1351a6f96b90564654541c88249ab', }, ], }, public: true, created_at: '2017-04-18T09:07:20Z', }, { id: '5694845165', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1681673612, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '672af53627cd7c2d8ee6847dcf025c5bf331a56e', before: 'f6c528ac73351e20d658efa3f2c1334c0563dad0', commits: [ { sha: '672af53627cd7c2d8ee6847dcf025c5bf331a56e', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'commits table completed ~', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/672af53627cd7c2d8ee6847dcf025c5bf331a56e', }, ], }, public: true, created_at: '2017-04-15T17:00:19Z', }, { id: '5694014505', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1681329833, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: 'f6c528ac73351e20d658efa3f2c1334c0563dad0', before: 'd8c63efa2e569cf14584e21a94a5758c4e7be4b0', commits: [ { sha: 'f6c528ac73351e20d658efa3f2c1334c0563dad0', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'all Commits stored and provided', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/f6c528ac73351e20d658efa3f2c1334c0563dad0', }, ], }, public: true, created_at: '2017-04-15T08:29:54Z', }, { id: '5691219082', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1680424085, size: 2, distinct_size: 2, ref: 'refs/heads/master', head: 'd8c63efa2e569cf14584e21a94a5758c4e7be4b0', before: '3ceabc92be7d9532bf8fba04e0fa28098be8561c', commits: [ { sha: '32cc39f8cf0706213d083c8b1e2344f19fd2dc32', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'single commit part finished ... stash it', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/32cc39f8cf0706213d083c8b1e2344f19fd2dc32', }, { sha: 'd8c63efa2e569cf14584e21a94a5758c4e7be4b0', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'successfully get data !!!!!!!!!!! :cry:', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/d8c63efa2e569cf14584e21a94a5758c4e7be4b0', }, ], }, public: true, created_at: '2017-04-14T16:29:56Z', }, { id: '5689270656', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1679772167, size: 5, distinct_size: 5, ref: 'refs/heads/master', head: '3ceabc92be7d9532bf8fba04e0fa28098be8561c', before: 'd64adc560874b90cf3aaec4510a023213e03f758', commits: [ { sha: '07b5e55449491fc046759809c1a341a8a9d03dff', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':lollipop:users, repos, messages', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/07b5e55449491fc046759809c1a341a8a9d03dff', }, { sha: '36e793c64bf1bbbba1116f7a6ec5d3957448301f', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'mysql Error', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/36e793c64bf1bbbba1116f7a6ec5d3957448301f', }, { sha: '68c2c0aa7b55d85806116643a88391b9c387d43c', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'replace the connection with pool ~ :rocket:', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/68c2c0aa7b55d85806116643a88391b9c387d43c', }, { sha: 'bbf9f86b7ebcb2cf9cf97b5<PASSWORD>', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'get language details from all repo :rocket:', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/bbf9f86b7ebcb2cf9cf97b57ca015de7546b92ac', }, { sha: '3ceabc92be7d9532bf8fba04e0fa28098be8561c', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'standard response for all :fire:', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/3ceabc92be7d9532bf8fba04e0fa28098be8561c', }, ], }, public: true, created_at: '2017-04-14T08:40:45Z', }, { id: '5684061159', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 88125890, name: '879479119/chrome-extension-shanbay', url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay', }, payload: { push_id: 1678161277, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: 'bb4bb305e92db79e16a7ef618c3dfbdf8a641163', before: '603f4e7414f9de65ee35c837d389f3ee8fa4a2f3', commits: [ { sha: 'bb4bb305e92db79e16a7ef618c3dfbdf8a641163', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':lollipop: nearly completed in a simple way', distinct: true, url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay/commits/bb4bb305e92db79e16a7ef618c3dfbdf8a641163', }, ], }, public: true, created_at: '2017-04-13T14:12:49Z', }, { id: '5681639978', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 13992627, name: 'Sneezry/chrome_extensions_and_apps_programming', url: 'https://api.github.com/repos/Sneezry/chrome_extensions_and_apps_programming', }, payload: { action: 'started', }, public: true, created_at: '2017-04-13T07:15:44Z', }, { id: '5681117157', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 88125890, name: '879479119/chrome-extension-shanbay', url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay', }, payload: { ref: 'master', ref_type: 'branch', master_branch: 'master', description: 'chrome extention in building', pusher_type: 'user', }, public: true, created_at: '2017-04-13T04:45:51Z', }, { id: '5681117105', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 88125890, name: '879479119/chrome-extension-shanbay', url: 'https://api.github.com/repos/879479119/chrome-extension-shanbay', }, payload: { ref: null, ref_type: 'repository', master_branch: 'master', description: 'chrome extention in building', pusher_type: 'user', }, public: true, created_at: '2017-04-13T04:45:50Z', }, { id: '5675128136', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 7846848, name: 'yeoman/generator-chrome-extension', url: 'https://api.github.com/repos/yeoman/generator-chrome-extension', }, payload: { action: 'started', }, public: true, created_at: '2017-04-12T11:30:04Z', org: { id: 1714870, login: 'yeoman', gravatar_id: '', url: 'https://api.github.com/orgs/yeoman', avatar_url: 'https://avatars.githubusercontent.com/u/1714870?', }, }, { id: '5665290079', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { action: 'started', }, public: true, created_at: '2017-04-11T06:35:39Z', }, { id: '5665283532', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1672188690, size: 3, distinct_size: 3, ref: 'refs/heads/master', head: 'd64adc560874b90cf3aaec4510a023213e03f758', before: '8fd88091f4c17ceee6363384671b4cda98ebedfa', commits: [ { sha: '86f40d43da5a28a27514328631629ef323493<PASSWORD>', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Work with CDN and configure :shit:', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/86f40d43da5a28a27514328631629ef32349397f', }, { sha: '95c44079b531f352e68da53ea0d08a7652e96040', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'homepage building', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/95c44079b531f352e68da53ea0d08a7652e96040', }, { sha: 'd64adc560874b90cf3aaec4510a023213e03f758', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Animation ~~~', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/d64adc560874b90cf3aaec4510a023213e03f758', }, ], }, public: true, created_at: '2017-04-11T06:34:13Z', }, { id: '5656705414', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85866753, name: 'Microsoft/reactxp', url: 'https://api.github.com/repos/Microsoft/reactxp', }, payload: { action: 'started', }, public: true, created_at: '2017-04-10T03:10:46Z', org: { id: 6154722, login: 'Microsoft', gravatar_id: '', url: 'https://api.github.com/orgs/Microsoft', avatar_url: 'https://avatars.githubusercontent.com/u/6154722?', }, }, { id: '5651716925', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1667337145, size: 3, distinct_size: 3, ref: 'refs/heads/master', head: '8fd88091f4c17ceee6363384671b4cda98ebedfa', before: '0ab83b287b206628d2e61c33f58c696191b2178d', commits: [ { sha: '72000ab5299c9d2b4933edce3a417983edf4f219', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'loading effects added', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/72000ab5299c9d2b4933edce3a417983edf4f219', }, { sha: 'ee54d26b237344820e5f6ceda6222e9dd3ff5a01', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'server proxy added', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/ee54d26b237344820e5f6ceda6222e9dd3ff5a01', }, { sha: '8fd88091f4c17ceee6363384671b4cda98ebedfa', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':eyes: working well with redux-saga', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/8fd88091f4c17ceee6363384671b4cda98ebedfa', }, ], }, public: true, created_at: '2017-04-08T07:28:08Z', }, { id: '5644299170', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 83986178, name: 'asd0102433/blog', url: 'https://api.github.com/repos/asd0102433/blog', }, payload: { action: 'started', }, public: true, created_at: '2017-04-07T04:40:04Z', }, { id: '5644255811', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 63507825, name: 'jonathan-potter/webgl-shaders', url: 'https://api.github.com/repos/jonathan-potter/webgl-shaders', }, payload: { action: 'started', }, public: true, created_at: '2017-04-07T04:24:27Z', }, { id: '5644205054', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { push_id: 1664830394, size: 2, distinct_size: 2, ref: 'refs/heads/master', head: '7052e1f321f1d9558518dc160837228705a96470', before: '3166c476c947084188211f4da4cee2dc23b4fe73', commits: [ { sha: 'e498becc36b5a71fe021fa1a68857d97ae9020d4', author: { email: '<EMAIL>', name: '<NAME>', }, message: 'fix corners of shadow on ios', distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/e498becc36b5a71fe021fa1a68857d97ae9020d4', }, { sha: '<PASSWORD>', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Merge pull request #8 from futuun/feature/focal_point_ios\n\nfix corners of shadow on iOS', distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/7052e1f321f1d9558518dc160837228705a96470', }, ], }, public: true, created_at: '2017-04-07T04:06:11Z', }, { id: '5644205042', type: 'PullRequestEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'closed', number: 8, pull_request: { url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/8', id: 114575290, html_url: 'https://github.com/879479119/react-native-shadow/pull/8', diff_url: 'https://github.com/879479119/react-native-shadow/pull/8.diff', patch_url: 'https://github.com/879479119/react-native-shadow/pull/8.patch', issue_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/8', number: 8, state: 'closed', locked: false, title: 'fix corners of shadow on iOS', user: { login: 'futuun', id: 15254260, avatar_url: 'https://avatars2.githubusercontent.com/u/15254260?v=3', gravatar_id: '', url: 'https://api.github.com/users/futuun', html_url: 'https://github.com/futuun', followers_url: 'https://api.github.com/users/futuun/followers', following_url: 'https://api.github.com/users/futuun/following{/other_user}', gists_url: 'https://api.github.com/users/futuun/gists{/gist_id}', starred_url: 'https://api.github.com/users/futuun/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/futuun/subscriptions', organizations_url: 'https://api.github.com/users/futuun/orgs', repos_url: 'https://api.github.com/users/futuun/repos', events_url: 'https://api.github.com/users/futuun/events{/privacy}', received_events_url: 'https://api.github.com/users/futuun/received_events', type: 'User', site_admin: false, }, body: 'Hello,\r\n\r\ni found an issue with iOS, which looks like this:\r\n<img width="374" alt="glass_and_iphone_6_ _ios_10_3__14e269_" src="https://cloud.githubusercontent.com/assets/15254260/24751340/7eddb0b2-1ac9-11e7-8c7d-aa75c642ceca.png">\r\nThis pull request will fix that by changing focal point of gradient.', created_at: '2017-04-06T11:04:47Z', updated_at: '2017-04-07T04:06:11Z', closed_at: '2017-04-07T04:06:11Z', merged_at: '2017-04-07T04:06:11Z', merge_commit_sha: '7052e1f321f1d9558518dc160837228705a96470', assignee: null, assignees: [], milestone: null, commits_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/8/commits', review_comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/8/comments', review_comment_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/comments{/number}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/8/comments', statuses_url: 'https://api.github.com/repos/879479119/react-native-shadow/statuses/e498becc36b5a71fe021fa1a68857d97ae9020d4', head: { label: 'futuun:feature/focal_point_ios', ref: 'feature/focal_point_ios', sha: 'e498becc36b5a71fe021fa1a68857d97ae9020d4', user: { login: 'futuun', id: 15254260, avatar_url: 'https://avatars2.githubusercontent.com/u/15254260?v=3', gravatar_id: '', url: 'https://api.github.com/users/futuun', html_url: 'https://github.com/futuun', followers_url: 'https://api.github.com/users/futuun/followers', following_url: 'https://api.github.com/users/futuun/following{/other_user}', gists_url: 'https://api.github.com/users/futuun/gists{/gist_id}', starred_url: 'https://api.github.com/users/futuun/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/futuun/subscriptions', organizations_url: 'https://api.github.com/users/futuun/orgs', repos_url: 'https://api.github.com/users/futuun/repos', events_url: 'https://api.github.com/users/futuun/events{/privacy}', received_events_url: 'https://api.github.com/users/futuun/received_events', type: 'User', site_admin: false, }, repo: { id: 87418771, name: 'react-native-shadow', full_name: 'futuun/react-native-shadow', owner: { login: 'futuun', id: 15254260, avatar_url: 'https://avatars2.githubusercontent.com/u/15254260?v=3', gravatar_id: '', url: 'https://api.github.com/users/futuun', html_url: 'https://github.com/futuun', followers_url: 'https://api.github.com/users/futuun/followers', following_url: 'https://api.github.com/users/futuun/following{/other_user}', gists_url: 'https://api.github.com/users/futuun/gists{/gist_id}', starred_url: 'https://api.github.com/users/futuun/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/futuun/subscriptions', organizations_url: 'https://api.github.com/users/futuun/orgs', repos_url: 'https://api.github.com/users/futuun/repos', events_url: 'https://api.github.com/users/futuun/events{/privacy}', received_events_url: 'https://api.github.com/users/futuun/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/futuun/react-native-shadow', description: 'A SVG shadow component powered with react-native-svg,which can provide shadow on Android like iOS ^_^', fork: true, url: 'https://api.github.com/repos/futuun/react-native-shadow', forks_url: 'https://api.github.com/repos/futuun/react-native-shadow/forks', keys_url: 'https://api.github.com/repos/futuun/react-native-shadow/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/futuun/react-native-shadow/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/futuun/react-native-shadow/teams', hooks_url: 'https://api.github.com/repos/futuun/react-native-shadow/hooks', issue_events_url: 'https://api.github.com/repos/futuun/react-native-shadow/issues/events{/number}', events_url: 'https://api.github.com/repos/futuun/react-native-shadow/events', assignees_url: 'https://api.github.com/repos/futuun/react-native-shadow/assignees{/user}', branches_url: 'https://api.github.com/repos/futuun/react-native-shadow/branches{/branch}', tags_url: 'https://api.github.com/repos/futuun/react-native-shadow/tags', blobs_url: 'https://api.github.com/repos/futuun/react-native-shadow/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/futuun/react-native-shadow/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/futuun/react-native-shadow/git/refs{/sha}', trees_url: 'https://api.github.com/repos/futuun/react-native-shadow/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/futuun/react-native-shadow/statuses/{sha}', languages_url: 'https://api.github.com/repos/futuun/react-native-shadow/languages', stargazers_url: 'https://api.github.com/repos/futuun/react-native-shadow/stargazers', contributors_url: 'https://api.github.com/repos/futuun/react-native-shadow/contributors', subscribers_url: 'https://api.github.com/repos/futuun/react-native-shadow/subscribers', subscription_url: 'https://api.github.com/repos/futuun/react-native-shadow/subscription', commits_url: 'https://api.github.com/repos/futuun/react-native-shadow/commits{/sha}', git_commits_url: 'https://api.github.com/repos/futuun/react-native-shadow/git/commits{/sha}', comments_url: 'https://api.github.com/repos/futuun/react-native-shadow/comments{/number}', issue_comment_url: 'https://api.github.com/repos/futuun/react-native-shadow/issues/comments{/number}', contents_url: 'https://api.github.com/repos/futuun/react-native-shadow/contents/{+path}', compare_url: 'https://api.github.com/repos/futuun/react-native-shadow/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/futuun/react-native-shadow/merges', archive_url: 'https://api.github.com/repos/futuun/react-native-shadow/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/futuun/react-native-shadow/downloads', issues_url: 'https://api.github.com/repos/futuun/react-native-shadow/issues{/number}', pulls_url: 'https://api.github.com/repos/futuun/react-native-shadow/pulls{/number}', milestones_url: 'https://api.github.com/repos/futuun/react-native-shadow/milestones{/number}', notifications_url: 'https://api.github.com/repos/futuun/react-native-shadow/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/futuun/react-native-shadow/labels{/name}', releases_url: 'https://api.github.com/repos/futuun/react-native-shadow/releases{/id}', deployments_url: 'https://api.github.com/repos/futuun/react-native-shadow/deployments', created_at: '2017-04-06T10:51:08Z', updated_at: '2017-04-06T10:51:09Z', pushed_at: '2017-04-06T11:06:31Z', git_url: 'git://github.com/futuun/react-native-shadow.git', ssh_url: 'git@github.com:futuun/react-native-shadow.git', clone_url: 'https://github.com/futuun/react-native-shadow.git', svn_url: 'https://github.com/futuun/react-native-shadow', homepage: null, size: 13, stargazers_count: 0, watchers_count: 0, language: 'JavaScript', has_issues: false, has_projects: true, has_downloads: true, has_wiki: true, has_pages: false, forks_count: 0, mirror_url: null, open_issues_count: 0, forks: 0, open_issues: 0, watchers: 0, default_branch: 'master', }, }, base: { label: '879479119:master', ref: 'master', sha: '3166c476c947084188211f4da4cee2dc23b4fe73', user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, repo: { id: 69021740, name: 'react-native-shadow', full_name: '879479119/react-native-shadow', owner: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/879479119/react-native-shadow', description: 'A SVG shadow component powered with react-native-svg,which can provide shadow on Android like iOS ^_^', fork: false, url: 'https://api.github.com/repos/879479119/react-native-shadow', forks_url: 'https://api.github.com/repos/879479119/react-native-shadow/forks', keys_url: 'https://api.github.com/repos/879479119/react-native-shadow/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/879479119/react-native-shadow/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/879479119/react-native-shadow/teams', hooks_url: 'https://api.github.com/repos/879479119/react-native-shadow/hooks', issue_events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/events{/number}', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/events', assignees_url: 'https://api.github.com/repos/879479119/react-native-shadow/assignees{/user}', branches_url: 'https://api.github.com/repos/879479119/react-native-shadow/branches{/branch}', tags_url: 'https://api.github.com/repos/879479119/react-native-shadow/tags', blobs_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/refs{/sha}', trees_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/879479119/react-native-shadow/statuses/{sha}', languages_url: 'https://api.github.com/repos/879479119/react-native-shadow/languages', stargazers_url: 'https://api.github.com/repos/879479119/react-native-shadow/stargazers', contributors_url: 'https://api.github.com/repos/879479119/react-native-shadow/contributors', subscribers_url: 'https://api.github.com/repos/879479119/react-native-shadow/subscribers', subscription_url: 'https://api.github.com/repos/879479119/react-native-shadow/subscription', commits_url: 'https://api.github.com/repos/879479119/react-native-shadow/commits{/sha}', git_commits_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/commits{/sha}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/comments{/number}', issue_comment_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/comments{/number}', contents_url: 'https://api.github.com/repos/879479119/react-native-shadow/contents/{+path}', compare_url: 'https://api.github.com/repos/879479119/react-native-shadow/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/879479119/react-native-shadow/merges', archive_url: 'https://api.github.com/repos/879479119/react-native-shadow/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/879479119/react-native-shadow/downloads', issues_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues{/number}', pulls_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls{/number}', milestones_url: 'https://api.github.com/repos/879479119/react-native-shadow/milestones{/number}', notifications_url: 'https://api.github.com/repos/879479119/react-native-shadow/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/labels{/name}', releases_url: 'https://api.github.com/repos/879479119/react-native-shadow/releases{/id}', deployments_url: 'https://api.github.com/repos/879479119/react-native-shadow/deployments', created_at: '2016-09-23T12:13:33Z', updated_at: '2017-04-06T11:19:05Z', pushed_at: '2017-04-07T04:06:11Z', git_url: 'git://github.com/879479119/react-native-shadow.git', ssh_url: '<EMAIL>:879479119/react-native-shadow.git', clone_url: 'https://github.com/879479119/react-native-shadow.git', svn_url: 'https://github.com/879479119/react-native-shadow', homepage: null, size: 13, stargazers_count: 44, watchers_count: 44, language: 'JavaScript', has_issues: true, has_projects: true, has_downloads: true, has_wiki: true, has_pages: false, forks_count: 8, mirror_url: null, open_issues_count: 0, forks: 8, open_issues: 0, watchers: 44, default_branch: 'master', }, }, _links: { self: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/8', }, html: { href: 'https://github.com/879479119/react-native-shadow/pull/8', }, issue: { href: 'https://api.github.com/repos/879479119/react-native-shadow/issues/8', }, comments: { href: 'https://api.github.com/repos/879479119/react-native-shadow/issues/8/comments', }, review_comments: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/8/comments', }, review_comment: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/comments{/number}', }, commits: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/8/commits', }, statuses: { href: 'https://api.github.com/repos/879479119/react-native-shadow/statuses/e498becc36b5a71fe021fa1a68857d97ae9020d4', }, }, merged: true, mergeable: null, mergeable_state: 'unknown', merged_by: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, comments: 1, review_comments: 0, maintainer_can_modify: false, commits: 1, additions: 5, deletions: 6, changed_files: 2, }, }, public: true, created_at: '2017-04-07T04:06:11Z', }, { id: '5644204620', type: 'IssueCommentEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'created', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/8', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/8/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/8/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/8/events', html_url: 'https://github.com/879479119/react-native-shadow/pull/8', id: 219862087, number: 8, title: 'fix corners of shadow on iOS', user: { login: 'futuun', id: 15254260, avatar_url: 'https://avatars2.githubusercontent.com/u/15254260?v=3', gravatar_id: '', url: 'https://api.github.com/users/futuun', html_url: 'https://github.com/futuun', followers_url: 'https://api.github.com/users/futuun/followers', following_url: 'https://api.github.com/users/futuun/following{/other_user}', gists_url: 'https://api.github.com/users/futuun/gists{/gist_id}', starred_url: 'https://api.github.com/users/futuun/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/futuun/subscriptions', organizations_url: 'https://api.github.com/users/futuun/orgs', repos_url: 'https://api.github.com/users/futuun/repos', events_url: 'https://api.github.com/users/futuun/events{/privacy}', received_events_url: 'https://api.github.com/users/futuun/received_events', type: 'User', site_admin: false, }, labels: [], state: 'open', locked: false, assignee: null, assignees: [], milestone: null, comments: 0, created_at: '2017-04-06T11:04:47Z', updated_at: '2017-04-07T04:06:03Z', closed_at: null, pull_request: { url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/8', html_url: 'https://github.com/879479119/react-native-shadow/pull/8', diff_url: 'https://github.com/879479119/react-native-shadow/pull/8.diff', patch_url: 'https://github.com/879479119/react-native-shadow/pull/8.patch', }, body: 'Hello,\r\n\r\ni found an issue with iOS, which looks like this:\r\n<img width="374" alt="glass_and_iphone_6_ _ios_10_3__14e269_" src="https://cloud.githubusercontent.com/assets/15254260/24751340/7eddb0b2-1ac9-11e7-8c7d-aa75c642ceca.png">\r\nThis pull request will fix that by changing focal point of gradient.', }, comment: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/comments/292427734', html_url: 'https://github.com/879479119/react-native-shadow/pull/8#issuecomment-292427734', issue_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/8', id: 292427734, user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, created_at: '2017-04-07T04:06:03Z', updated_at: '2017-04-07T04:06:03Z', body: 'thanks for help ~ ', }, }, public: true, created_at: '2017-04-07T04:06:03Z', }, { id: '5636865272', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1662498712, size: 3, distinct_size: 3, ref: 'refs/heads/master', head: '0ab83b287b206628d2e61c33f58c696191b2178d', before: 'ebdf59688961e8c8ff4486e3088398195afe3d5f', commits: [ { sha: '507886cbdbcc072270572dd0901c93d9063b80d1', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'resolve - fetch cannot work with cookie :smile:', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/507886cbdbcc072270572dd0901c93d9063b80d1', }, { sha: 'b8713678e5d320b28e8fef43ac88eaebcdfd545f', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'abstract the DAO layer', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/b8713678e5d320b28e8fef43ac88eaebcdfd545f', }, { sha: '0ab83b287b206628d2e61c33f58c696191b2178d', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'API works well as thought', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/0ab83b287b206628d2e61c33f58c696191b2178d', }, ], }, public: true, created_at: '2017-04-06T07:30:48Z', }, { id: '5623449541', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1658210569, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: 'ebdf59688961e8c8ff4486e3088398195afe3d5f', before: 'ffa4448bf94acbce6b180a95126da2eaae0fffce', commits: [ { sha: 'ebdf59688961e8c8ff4486e3088398195afe3d5f', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'successfully login :weary:', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/ebdf59688961e8c8ff4486e3088398195afe3d5f', }, ], }, public: true, created_at: '2017-04-04T14:59:33Z', }, { id: '5622620232', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1657940876, size: 2, distinct_size: 2, ref: 'refs/heads/master', head: 'ffa4448bf94acbce6b180a95126da2eaae0fffce', before: '92a8b078b30b9fa0b1c9d1ea937d39bcce2e2f18', commits: [ { sha: 'a982825db3a9bd948295960710b94d931b61a584', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Add the server !', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/a982825db3a9bd948295960710b94d931b61a584', }, { sha: 'ffa4448bf94acbce6b180a95126da2eaae0fffce', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'logger added:weary:', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/ffa4448bf94acbce6b180a95126da2eaae0fffce', }, ], }, public: true, created_at: '2017-04-04T13:16:38Z', }, { id: '5616085296', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 61774942, name: 'trungdq88/github-explorer', url: 'https://api.github.com/repos/trungdq88/github-explorer', }, payload: { action: 'started', }, public: true, created_at: '2017-04-03T15:59:37Z', }, { id: '5613043186', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 711976, name: 'mikedeboer/node-github', url: 'https://api.github.com/repos/mikedeboer/node-github', }, payload: { action: 'started', }, public: true, created_at: '2017-04-03T08:02:18Z', }, { id: '5612757489', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 34713704, name: 'mortenjust/androidtool-mac', url: 'https://api.github.com/repos/mortenjust/androidtool-mac', }, payload: { action: 'started', }, public: true, created_at: '2017-04-03T06:55:16Z', }, { id: '5612749463', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85457673, name: 'chuanwu/Tinker', url: 'https://api.github.com/repos/chuanwu/Tinker', }, payload: { action: 'started', }, public: true, created_at: '2017-04-03T06:53:10Z', }, { id: '5612063389', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 711976, name: 'mikedeboer/node-github', url: 'https://api.github.com/repos/mikedeboer/node-github', }, payload: { action: 'started', }, public: true, created_at: '2017-04-03T02:34:51Z', }, { id: '5610502338', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 12244426, name: 'rstacruz/nprogress', url: 'https://api.github.com/repos/rstacruz/nprogress', }, payload: { action: 'started', }, public: true, created_at: '2017-04-02T13:30:00Z', }, { id: '5610440742', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 38565895, name: 'gaearon/redux-devtools', url: 'https://api.github.com/repos/gaearon/redux-devtools', }, payload: { action: 'started', }, public: true, created_at: '2017-04-02T12:54:49Z', }, { id: '5610440216', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1653824596, size: 2, distinct_size: 2, ref: 'refs/heads/master', head: '92a8b078b30b9fa0b1c9d1ea937d39bcce2e2f18', before: '4acba2000d677bc7c546ff6c7d4c2bfe435ec643', commits: [ { sha: '900e7cff9fbc56a137e9d784a5acdd99d73c67ba', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':smile: safely running !!!', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/900e7cff9fbc56a137e9d784a5acdd99d73c67ba', }, { sha: '92a8b078b30b9fa0b1c9d1ea937d39bcce2e2f18', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Advanced framework built ready for usage ~', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/92a8b078b30b9fa0b1c9d1ea937d39bcce2e2f18', }, ], }, public: true, created_at: '2017-04-02T12:54:30Z', }, { id: '5610274576', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 19872456, name: 'ReactTraining/react-router', url: 'https://api.github.com/repos/ReactTraining/react-router', }, payload: { action: 'started', }, public: true, created_at: '2017-04-02T11:14:39Z', org: { id: 11823761, login: 'ReactTraining', gravatar_id: '', url: 'https://api.github.com/orgs/ReactTraining', avatar_url: 'https://avatars.githubusercontent.com/u/11823761?', }, }, { id: '5609852460', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { push_id: 1653581778, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '4acba2000d677bc7c546ff6c7d4c2bfe435ec643', before: 'e95f05a343c887bf1a4fd4919b682767da273057', commits: [ { sha: '4acba2000d677bc7c546ff6c7d4c2bfe435ec643', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'init project', distinct: true, url: 'https://api.github.com/repos/879479119/Github-Mobile/commits/4acba2000d677bc7c546ff6c7d4c2bfe435ec643', }, ], }, public: true, created_at: '2017-04-02T06:26:53Z', }, { id: '5608605031', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 57121262, name: '879479119/879479119.github.io', url: 'https://api.github.com/repos/879479119/879479119.github.io', }, payload: { push_id: 1653053622, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '3132d219bd62753c96ffe22bad0c0872a5a13a0f', before: '7a2d30074c176bf700657308564d9cb7172c577c', commits: [ { sha: '3132d219bd62753c96ffe22bad0c0872a5a13a0f', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Create CNAME', distinct: true, url: 'https://api.github.com/repos/879479119/879479119.github.io/commits/3132d219bd62753c96ffe22bad0c0872a5a13a0f', }, ], }, public: true, created_at: '2017-04-01T16:42:55Z', }, { id: '5608436616', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86921892, name: '879479119/879479119.github.io', url: 'https://api.github.com/repos/879479119/879479119.github.io', }, payload: { push_id: 1652984185, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: 'b8859dff6e2451d1c57cd06c09b0c515b0556476', before: '44f9dad487c616dc712fff10ea8ad313e6855f3d', commits: [ { sha: 'b8859dff6e2451d1c57cd06c09b0c515b0556476', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Added CNAME file for custom domain (rocksama.me)', distinct: true, url: 'https://api.github.com/repos/879479119/879479119.github.io/commits/b8859dff6e2451d1c57cd06c09b0c515b0556476', }, ], }, public: true, created_at: '2017-04-01T15:15:14Z', }, { id: '5608436541', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86921892, name: '879479119/879479119.github.io', url: 'https://api.github.com/repos/879479119/879479119.github.io', }, payload: { ref: 'master', ref_type: 'branch', master_branch: 'master', description: null, pusher_type: 'user', }, public: true, created_at: '2017-04-01T15:15:13Z', }, { id: '5608436496', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86921892, name: '879479119/879479119.github.io', url: 'https://api.github.com/repos/879479119/879479119.github.io', }, payload: { ref: null, ref_type: 'repository', master_branch: 'master', description: null, pusher_type: 'user', }, public: true, created_at: '2017-04-01T15:15:11Z', }, { id: '5607255802', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { ref: 'master', ref_type: 'branch', master_branch: 'master', description: 'Application built with React, Koa, data powerd by github', pusher_type: 'user', }, public: true, created_at: '2017-04-01T03:18:53Z', }, { id: '5607255768', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 86879936, name: '879479119/Github-Mobile', url: 'https://api.github.com/repos/879479119/Github-Mobile', }, payload: { ref: null, ref_type: 'repository', master_branch: 'master', description: 'Application built with React, Koa, data powerd by github', pusher_type: 'user', }, public: true, created_at: '2017-04-01T03:18:52Z', }, { id: '5607192666', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69651820, name: 'ddz-mark/News', url: 'https://api.github.com/repos/ddz-mark/News', }, payload: { action: 'started', }, public: true, created_at: '2017-04-01T02:45:50Z', }, { id: '5606876618', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 39226969, name: 'gdestiny/graduation_github', url: 'https://api.github.com/repos/gdestiny/graduation_github', }, payload: { action: 'started', }, public: true, created_at: '2017-04-01T00:26:20Z', }, { id: '5604281214', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 71330626, name: '879479119/SPA-starter-kit', url: 'https://api.github.com/repos/879479119/SPA-starter-kit', }, payload: { push_id: 1651569299, size: 4, distinct_size: 4, ref: 'refs/heads/master', head: 'c6299ca106d065bc67ea31aa8e3038898e5ce262', before: 'cebaebc56e62f75f945df100e6a31654e75d0306', commits: [ { sha: '2fab02ee6991c63784dcad0f217214647ec0f177', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'require files when needed', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/2fab02ee6991c63784dcad0f217214647ec0f177', }, { sha: '5ef9835334fc9eb59c0764684eaf1b63a9fd1412', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'clear files & update again', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/5ef9835334fc9eb59c0764684eaf1b63a9fd1412', }, { sha: '7cd17778ea570a4c3124f1804612511f0b8b5928', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'linux version', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/7cd17778ea570a4c3124f1804612511f0b8b5928', }, { sha: 'c6299ca106d065bc67ea31aa8e3038898e5ce262', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':lollipop: link the sample with this', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/c6299ca106d065bc67ea31aa8e3038898e5ce262', }, ], }, public: true, created_at: '2017-03-31T16:13:48Z', }, { id: '5584037942', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { push_id: 1644897982, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '3166c476c947084188211f4da4cee2dc23b4fe73', before: '8fa3b2306701dc7d2350a7dc0deb3856c0f31c82', commits: [ { sha: '3166c476c947084188211f4da4cee2dc23b4fe73', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'update version and npm', distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/3166c476c947084188211f4da4cee2dc23b4fe73', }, ], }, public: true, created_at: '2017-03-29T03:03:20Z', }, { id: '5584004355', type: 'IssuesEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'closed', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/2', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/2/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/2/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/2/events', html_url: 'https://github.com/879479119/react-native-shadow/issues/2', id: 200296958, number: 2, title: ' error: package com.facebook.yoga does not exist', user: { login: 'gungungun93', id: 6262268, avatar_url: 'https://avatars0.githubusercontent.com/u/6262268?v=3', gravatar_id: '', url: 'https://api.github.com/users/gungungun93', html_url: 'https://github.com/gungungun93', followers_url: 'https://api.github.com/users/gungungun93/followers', following_url: 'https://api.github.com/users/gungungun93/following{/other_user}', gists_url: 'https://api.github.com/users/gungungun93/gists{/gist_id}', starred_url: 'https://api.github.com/users/gungungun93/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/gungungun93/subscriptions', organizations_url: 'https://api.github.com/users/gungungun93/orgs', repos_url: 'https://api.github.com/users/gungungun93/repos', events_url: 'https://api.github.com/users/gungungun93/events{/privacy}', received_events_url: 'https://api.github.com/users/gungungun93/received_events', type: 'User', site_admin: false, }, labels: [], state: 'closed', locked: false, assignee: null, assignees: [], milestone: null, comments: 2, created_at: '2017-01-12T07:29:49Z', updated_at: '2017-03-29T02:54:09Z', closed_at: '2017-03-29T02:54:09Z', body: 'I got this error \r\n/node_modules/react-native-svg/android/src/main/java/com/horcrux/svg/SvgViewManager.java:14: error: package com.facebook.yoga does not exist \r\nimport com.facebook.yoga.YogaMeasureMode;\r\n ^\r\n\r\n', }, }, public: true, created_at: '2017-03-29T02:54:09Z', }, { id: '5583999371', type: 'IssuesEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'closed', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5/events', html_url: 'https://github.com/879479119/react-native-shadow/issues/5', id: 210414005, number: 5, title: 'how to change shadow backgroundColor', user: { login: 'JourneyL', id: 18393378, avatar_url: 'https://avatars2.githubusercontent.com/u/18393378?v=3', gravatar_id: '', url: 'https://api.github.com/users/JourneyL', html_url: 'https://github.com/JourneyL', followers_url: 'https://api.github.com/users/JourneyL/followers', following_url: 'https://api.github.com/users/JourneyL/following{/other_user}', gists_url: 'https://api.github.com/users/JourneyL/gists{/gist_id}', starred_url: 'https://api.github.com/users/JourneyL/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/JourneyL/subscriptions', organizations_url: 'https://api.github.com/users/JourneyL/orgs', repos_url: 'https://api.github.com/users/JourneyL/repos', events_url: 'https://api.github.com/users/JourneyL/events{/privacy}', received_events_url: 'https://api.github.com/users/JourneyL/received_events', type: 'User', site_admin: false, }, labels: [], state: 'closed', locked: false, assignee: null, assignees: [], milestone: null, comments: 4, created_at: '2017-02-27T08:09:35Z', updated_at: '2017-03-29T02:52:48Z', closed_at: '2017-03-29T02:52:48Z', body: 'i set x,y and appear a box that backgroundColor is black ,how to change the backgroundColor of this box ?', }, }, public: true, created_at: '2017-03-29T02:52:48Z', }, { id: '5583998028', type: 'IssuesEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'closed', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/1', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/1/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/1/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/1/events', html_url: 'https://github.com/879479119/react-native-shadow/issues/1', id: 193043564, number: 1, title: '_(:з」∠)_这个会继续维护咩', user: { login: 'Elvenisboy', id: 11287864, avatar_url: 'https://avatars2.githubusercontent.com/u/11287864?v=3', gravatar_id: '', url: 'https://api.github.com/users/Elvenisboy', html_url: 'https://github.com/Elvenisboy', followers_url: 'https://api.github.com/users/Elvenisboy/followers', following_url: 'https://api.github.com/users/Elvenisboy/following{/other_user}', gists_url: 'https://api.github.com/users/Elvenisboy/gists{/gist_id}', starred_url: 'https://api.github.com/users/Elvenisboy/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/Elvenisboy/subscriptions', organizations_url: 'https://api.github.com/users/Elvenisboy/orgs', repos_url: 'https://api.github.com/users/Elvenisboy/repos', events_url: 'https://api.github.com/users/Elvenisboy/events{/privacy}', received_events_url: 'https://api.github.com/users/Elvenisboy/received_events', type: 'User', site_admin: false, }, labels: [], state: 'closed', locked: false, assignee: null, assignees: [], milestone: null, comments: 1, created_at: '2016-12-02T06:26:22Z', updated_at: '2017-03-29T02:52:27Z', closed_at: '2017-03-29T02:52:27Z', body: '能有一个可以解决安卓阴影问题的组件真的是太好惹,不过作者会继续维护下去咩', }, }, public: true, created_at: '2017-03-29T02:52:27Z', }, { id: '5583997500', type: 'IssueCommentEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'created', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/1', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/1/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/1/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/1/events', html_url: 'https://github.com/879479119/react-native-shadow/issues/1', id: 193043564, number: 1, title: '_(:з」∠)_这个会继续维护咩', user: { login: 'Elvenisboy', id: 11287864, avatar_url: 'https://avatars2.githubusercontent.com/u/11287864?v=3', gravatar_id: '', url: 'https://api.github.com/users/Elvenisboy', html_url: 'https://github.com/Elvenisboy', followers_url: 'https://api.github.com/users/Elvenisboy/followers', following_url: 'https://api.github.com/users/Elvenisboy/following{/other_user}', gists_url: 'https://api.github.com/users/Elvenisboy/gists{/gist_id}', starred_url: 'https://api.github.com/users/Elvenisboy/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/Elvenisboy/subscriptions', organizations_url: 'https://api.github.com/users/Elvenisboy/orgs', repos_url: 'https://api.github.com/users/Elvenisboy/repos', events_url: 'https://api.github.com/users/Elvenisboy/events{/privacy}', received_events_url: 'https://api.github.com/users/Elvenisboy/received_events', type: 'User', site_admin: false, }, labels: [], state: 'open', locked: false, assignee: null, assignees: [], milestone: null, comments: 0, created_at: '2016-12-02T06:26:22Z', updated_at: '2017-03-29T02:52:18Z', closed_at: null, body: '能有一个可以解决安卓阴影问题的组件真的是太好惹,不过作者会继续维护下去咩', }, comment: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/comments/289966480', html_url: 'https://github.com/879479119/react-native-shadow/issues/1#issuecomment-289966480', issue_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/1', id: 289966480, user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, created_at: '2017-03-29T02:52:18Z', updated_at: '2017-03-29T02:52:18Z', body: '哈哈 有段时间没做RN了 不知道诶', }, }, public: true, created_at: '2017-03-29T02:52:18Z', }, { id: '5583993632', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { push_id: 1644881520, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '8fa3b2306701dc7d2350a7dc0deb3856c0f31c82', before: '122597223c50b5ef982a0ff35fde44854799ca4f', commits: [ { sha: '8fa3b2306701dc7d2350a7dc0deb3856c0f3<PASSWORD>', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Delete yarn.lock', distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/8fa3b2306701dc7d2350a7dc0deb3856c0f31c82', }, ], }, public: true, created_at: '2017-03-29T02:51:11Z', }, { id: '5583991707', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { push_id: 1644880796, size: 2, distinct_size: 2, ref: 'refs/heads/master', head: '122597223c50b5ef982a0ff35fde44854799ca4f', before: '72c9a8623f1765ea9afbb7bd475c1940b09f5c13', commits: [ { sha: 'f3988a06ffd0ce744e1a71<PASSWORD>', author: { email: '<EMAIL>', name: '<NAME>', }, message: 'Fix Each Child warning by adding key prop', distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/f3988a06ffd0ce744e1a71c658e52e09666847f1', }, { sha: '122597223c50b5ef982a0ff35fde44854799ca4f', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Merge pull request #7 from jimthedev/master\n\nFix Each Child warning by adding key prop #4', distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/122597223c50b5ef982a0ff35fde44854799ca4f', }, ], }, public: true, created_at: '2017-03-29T02:50:39Z', }, { id: '5583991684', type: 'PullRequestEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'closed', number: 7, pull_request: { url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/7', id: 113066665, html_url: 'https://github.com/879479119/react-native-shadow/pull/7', diff_url: 'https://github.com/879479119/react-native-shadow/pull/7.diff', patch_url: 'https://github.com/879479119/react-native-shadow/pull/7.patch', issue_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/7', number: 7, state: 'closed', locked: false, title: 'Fix Each Child warning by adding key prop', user: { login: 'jimthedev', id: 108938, avatar_url: 'https://avatars3.githubusercontent.com/u/108938?v=3', gravatar_id: '', url: 'https://api.github.com/users/jimthedev', html_url: 'https://github.com/jimthedev', followers_url: 'https://api.github.com/users/jimthedev/followers', following_url: 'https://api.github.com/users/jimthedev/following{/other_user}', gists_url: 'https://api.github.com/users/jimthedev/gists{/gist_id}', starred_url: 'https://api.github.com/users/jimthedev/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/jimthedev/subscriptions', organizations_url: 'https://api.github.com/users/jimthedev/orgs', repos_url: 'https://api.github.com/users/jimthedev/repos', events_url: 'https://api.github.com/users/jimthedev/events{/privacy}', received_events_url: 'https://api.github.com/users/jimthedev/received_events', type: 'User', site_admin: false, }, body: 'It turns out that we needed to add a key to each <Stop>. This modifies linear and radial to be functions instead so that the keys on items can be dynamic.\r\n\r\nFixes #4 ', created_at: '2017-03-28T21:02:59Z', updated_at: '2017-03-29T02:50:38Z', closed_at: '2017-03-29T02:50:38Z', merged_at: '2017-03-29T02:50:38Z', merge_commit_sha: '122597223c50b5ef982a0ff35fde44854799ca4f', assignee: null, assignees: [], milestone: null, commits_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/7/commits', review_comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/7/comments', review_comment_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/comments{/number}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/7/comments', statuses_url: 'https://api.github.com/repos/879479119/react-native-shadow/statuses/f3988a06ffd0ce744e1a71c658e52e09666847f1', head: { label: 'jimthedev:master', ref: 'master', sha: 'f3988a06ffd0ce744e1a71c658e52e09666847f1', user: { login: 'jimthedev', id: 108938, avatar_url: 'https://avatars3.githubusercontent.com/u/108938?v=3', gravatar_id: '', url: 'https://api.github.com/users/jimthedev', html_url: 'https://github.com/jimthedev', followers_url: 'https://api.github.com/users/jimthedev/followers', following_url: 'https://api.github.com/users/jimthedev/following{/other_user}', gists_url: 'https://api.github.com/users/jimthedev/gists{/gist_id}', starred_url: 'https://api.github.com/users/jimthedev/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/jimthedev/subscriptions', organizations_url: 'https://api.github.com/users/jimthedev/orgs', repos_url: 'https://api.github.com/users/jimthedev/repos', events_url: 'https://api.github.com/users/jimthedev/events{/privacy}', received_events_url: 'https://api.github.com/users/jimthedev/received_events', type: 'User', site_admin: false, }, repo: { id: 86488142, name: 'react-native-shadow', full_name: 'jimthedev/react-native-shadow', owner: { login: 'jimthedev', id: 108938, avatar_url: 'https://avatars3.githubusercontent.com/u/108938?v=3', gravatar_id: '', url: 'https://api.github.com/users/jimthedev', html_url: 'https://github.com/jimthedev', followers_url: 'https://api.github.com/users/jimthedev/followers', following_url: 'https://api.github.com/users/jimthedev/following{/other_user}', gists_url: 'https://api.github.com/users/jimthedev/gists{/gist_id}', starred_url: 'https://api.github.com/users/jimthedev/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/jimthedev/subscriptions', organizations_url: 'https://api.github.com/users/jimthedev/orgs', repos_url: 'https://api.github.com/users/jimthedev/repos', events_url: 'https://api.github.com/users/jimthedev/events{/privacy}', received_events_url: 'https://api.github.com/users/jimthedev/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/jimthedev/react-native-shadow', description: 'A SVG shadow component powered with react-native-svg,which can provide shadow on Android like iOS ^_^', fork: true, url: 'https://api.github.com/repos/jimthedev/react-native-shadow', forks_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/forks', keys_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/teams', hooks_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/hooks', issue_events_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/issues/events{/number}', events_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/events', assignees_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/assignees{/user}', branches_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/branches{/branch}', tags_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/tags', blobs_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/git/refs{/sha}', trees_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/statuses/{sha}', languages_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/languages', stargazers_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/stargazers', contributors_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/contributors', subscribers_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/subscribers', subscription_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/subscription', commits_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/commits{/sha}', git_commits_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/git/commits{/sha}', comments_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/comments{/number}', issue_comment_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/issues/comments{/number}', contents_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/contents/{+path}', compare_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/merges', archive_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/downloads', issues_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/issues{/number}', pulls_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/pulls{/number}', milestones_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/milestones{/number}', notifications_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/labels{/name}', releases_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/releases{/id}', deployments_url: 'https://api.github.com/repos/jimthedev/react-native-shadow/deployments', created_at: '2017-03-28T17:28:30Z', updated_at: '2017-03-28T17:28:31Z', pushed_at: '2017-03-28T20:59:25Z', git_url: 'git://github.com/jimthedev/react-native-shadow.git', ssh_url: 'git@github.com:jimthedev/react-native-shadow.git', clone_url: 'https://github.com/jimthedev/react-native-shadow.git', svn_url: 'https://github.com/jimthedev/react-native-shadow', homepage: null, size: 11, stargazers_count: 0, watchers_count: 0, language: 'JavaScript', has_issues: false, has_projects: true, has_downloads: true, has_wiki: true, has_pages: false, forks_count: 0, mirror_url: null, open_issues_count: 0, forks: 0, open_issues: 0, watchers: 0, default_branch: 'master', }, }, base: { label: '879479119:master', ref: 'master', sha: '24ecc87265f94f5889b0dc31f8a72864b2590169', user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, repo: { id: 69021740, name: 'react-native-shadow', full_name: '879479119/react-native-shadow', owner: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/879479119/react-native-shadow', description: 'A SVG shadow component powered with react-native-svg,which can provide shadow on Android like iOS ^_^', fork: false, url: 'https://api.github.com/repos/879479119/react-native-shadow', forks_url: 'https://api.github.com/repos/879479119/react-native-shadow/forks', keys_url: 'https://api.github.com/repos/879479119/react-native-shadow/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/879479119/react-native-shadow/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/879479119/react-native-shadow/teams', hooks_url: 'https://api.github.com/repos/879479119/react-native-shadow/hooks', issue_events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/events{/number}', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/events', assignees_url: 'https://api.github.com/repos/879479119/react-native-shadow/assignees{/user}', branches_url: 'https://api.github.com/repos/879479119/react-native-shadow/branches{/branch}', tags_url: 'https://api.github.com/repos/879479119/react-native-shadow/tags', blobs_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/refs{/sha}', trees_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/879479119/react-native-shadow/statuses/{sha}', languages_url: 'https://api.github.com/repos/879479119/react-native-shadow/languages', stargazers_url: 'https://api.github.com/repos/879479119/react-native-shadow/stargazers', contributors_url: 'https://api.github.com/repos/879479119/react-native-shadow/contributors', subscribers_url: 'https://api.github.com/repos/879479119/react-native-shadow/subscribers', subscription_url: 'https://api.github.com/repos/879479119/react-native-shadow/subscription', commits_url: 'https://api.github.com/repos/879479119/react-native-shadow/commits{/sha}', git_commits_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/commits{/sha}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/comments{/number}', issue_comment_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/comments{/number}', contents_url: 'https://api.github.com/repos/879479119/react-native-shadow/contents/{+path}', compare_url: 'https://api.github.com/repos/879479119/react-native-shadow/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/879479119/react-native-shadow/merges', archive_url: 'https://api.github.com/repos/879479119/react-native-shadow/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/879479119/react-native-shadow/downloads', issues_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues{/number}', pulls_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls{/number}', milestones_url: 'https://api.github.com/repos/879479119/react-native-shadow/milestones{/number}', notifications_url: 'https://api.github.com/repos/879479119/react-native-shadow/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/labels{/name}', releases_url: 'https://api.github.com/repos/879479119/react-native-shadow/releases{/id}', deployments_url: 'https://api.github.com/repos/879479119/react-native-shadow/deployments', created_at: '2016-09-23T12:13:33Z', updated_at: '2017-03-21T11:48:31Z', pushed_at: '2017-03-29T02:50:38Z', git_url: 'git://github.com/879479119/react-native-shadow.git', ssh_url: 'git@github.com:879479119/react-native-shadow.git', clone_url: 'https://github.com/879479119/react-native-shadow.git', svn_url: 'https://github.com/879479119/react-native-shadow', homepage: null, size: 9, stargazers_count: 36, watchers_count: 36, language: 'JavaScript', has_issues: true, has_projects: true, has_downloads: true, has_wiki: true, has_pages: false, forks_count: 7, mirror_url: null, open_issues_count: 3, forks: 7, open_issues: 3, watchers: 36, default_branch: 'master', }, }, _links: { self: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/7', }, html: { href: 'https://github.com/879479119/react-native-shadow/pull/7', }, issue: { href: 'https://api.github.com/repos/879479119/react-native-shadow/issues/7', }, comments: { href: 'https://api.github.com/repos/879479119/react-native-shadow/issues/7/comments', }, review_comments: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/7/comments', }, review_comment: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/comments{/number}', }, commits: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/7/commits', }, statuses: { href: 'https://api.github.com/repos/879479119/react-native-shadow/statuses/f3988a06ffd0ce744e1a71c658e52e09666847f1', }, }, merged: true, mergeable: null, mergeable_state: 'unknown', merged_by: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, comments: 1, review_comments: 0, maintainer_can_modify: false, commits: 1, additions: 134, deletions: 25, changed_files: 4, }, }, public: true, created_at: '2017-03-29T02:50:39Z', }, { id: '5583991682', type: 'IssuesEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'closed', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/4', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/4/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/4/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/4/events', html_url: 'https://github.com/879479119/react-native-shadow/issues/4', id: 208635816, number: 4, title: 'Each child in an array or iterator should have a unique "key" prop. Check the render method of `BoxShadow`. See https://fb.me/react-warning-keys for more information.', user: { login: 'Lxxyx', id: 13161470, avatar_url: 'https://avatars0.githubusercontent.com/u/13161470?v=3', gravatar_id: '', url: 'https://api.github.com/users/Lxxyx', html_url: 'https://github.com/Lxxyx', followers_url: 'https://api.github.com/users/Lxxyx/followers', following_url: 'https://api.github.com/users/Lxxyx/following{/other_user}', gists_url: 'https://api.github.com/users/Lxxyx/gists{/gist_id}', starred_url: 'https://api.github.com/users/Lxxyx/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/Lxxyx/subscriptions', organizations_url: 'https://api.github.com/users/Lxxyx/orgs', repos_url: 'https://api.github.com/users/Lxxyx/repos', events_url: 'https://api.github.com/users/Lxxyx/events{/privacy}', received_events_url: 'https://api.github.com/users/Lxxyx/received_events', type: 'User', site_admin: false, }, labels: [], state: 'closed', locked: false, assignee: null, assignees: [], milestone: null, comments: 1, created_at: '2017-02-18T11:36:01Z', updated_at: '2017-03-29T02:50:38Z', closed_at: '2017-03-29T02:50:38Z', body: 'Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `BoxShadow`. See https://fb.me/react-warning-keys for more information.\r\n\r\nBoxShadow._this.render\t@\tBoxShadow.js:32\r\n\r\n', }, }, public: true, created_at: '2017-03-29T02:50:38Z', }, { id: '5583989932', type: 'IssueCommentEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'created', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/7', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/7/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/7/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/7/events', html_url: 'https://github.com/879479119/react-native-shadow/pull/7', id: 217691857, number: 7, title: 'Fix Each Child warning by adding key prop', user: { login: 'jimthedev', id: 108938, avatar_url: 'https://avatars3.githubusercontent.com/u/108938?v=3', gravatar_id: '', url: 'https://api.github.com/users/jimthedev', html_url: 'https://github.com/jimthedev', followers_url: 'https://api.github.com/users/jimthedev/followers', following_url: 'https://api.github.com/users/jimthedev/following{/other_user}', gists_url: 'https://api.github.com/users/jimthedev/gists{/gist_id}', starred_url: 'https://api.github.com/users/jimthedev/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/jimthedev/subscriptions', organizations_url: 'https://api.github.com/users/jimthedev/orgs', repos_url: 'https://api.github.com/users/jimthedev/repos', events_url: 'https://api.github.com/users/jimthedev/events{/privacy}', received_events_url: 'https://api.github.com/users/jimthedev/received_events', type: 'User', site_admin: false, }, labels: [], state: 'open', locked: false, assignee: null, assignees: [], milestone: null, comments: 0, created_at: '2017-03-28T21:02:59Z', updated_at: '2017-03-29T02:50:10Z', closed_at: null, pull_request: { url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/7', html_url: 'https://github.com/879479119/react-native-shadow/pull/7', diff_url: 'https://github.com/879479119/react-native-shadow/pull/7.diff', patch_url: 'https://github.com/879479119/react-native-shadow/pull/7.patch', }, body: 'It turns out that we needed to add a key to each <Stop>. This modifies linear and radial to be functions instead so that the keys on items can be dynamic.\r\n\r\nFixes #4 ', }, comment: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/comments/289966200', html_url: 'https://github.com/879479119/react-native-shadow/pull/7#issuecomment-289966200', issue_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/7', id: 289966200, user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, created_at: '2017-03-29T02:50:10Z', updated_at: '2017-03-29T02:50:10Z', body: 'thx really helps', }, }, public: true, created_at: '2017-03-29T02:50:10Z', }, { id: '5583966292', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { push_id: 1644871761, size: 2, distinct_size: 2, ref: 'refs/heads/master', head: '72c9a8623f1765ea9afbb7bd475c1940b09f5c13', before: '24ecc87265f94f5889b0dc31f8a72864b2590169', commits: [ { sha: 'a128d4770cbf3f8c62efb005c5935d6171136823', author: { email: '<EMAIL>', name: 'GuoChen-WHU', }, message: 'typo', distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/a128d4770cbf3f8c62efb005c5935d6171136823', }, { sha: '72c9a8623f1765ea9afbb7bd475c1940b09f5c13', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Merge pull request #6 from GuoChen-WHU/master\n\nReadME typo #6 FIXED', distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/72c9a8623f1765ea9afbb7bd475c1940b09f5c13', }, ], }, public: true, created_at: '2017-03-29T02:43:39Z', }, { id: '5583966249', type: 'PullRequestEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'closed', number: 6, pull_request: { url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/6', id: 112888655, html_url: 'https://github.com/879479119/react-native-shadow/pull/6', diff_url: 'https://github.com/879479119/react-native-shadow/pull/6.diff', patch_url: 'https://github.com/879479119/react-native-shadow/pull/6.patch', issue_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/6', number: 6, state: 'closed', locked: false, title: 'typo', user: { login: 'GuoChen-WHU', id: 13191917, avatar_url: 'https://avatars0.githubusercontent.com/u/13191917?v=3', gravatar_id: '', url: 'https://api.github.com/users/GuoChen-WHU', html_url: 'https://github.com/GuoChen-WHU', followers_url: 'https://api.github.com/users/GuoChen-WHU/followers', following_url: 'https://api.github.com/users/GuoChen-WHU/following{/other_user}', gists_url: 'https://api.github.com/users/GuoChen-WHU/gists{/gist_id}', starred_url: 'https://api.github.com/users/GuoChen-WHU/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/GuoChen-WHU/subscriptions', organizations_url: 'https://api.github.com/users/GuoChen-WHU/orgs', repos_url: 'https://api.github.com/users/GuoChen-WHU/repos', events_url: 'https://api.github.com/users/GuoChen-WHU/events{/privacy}', received_events_url: 'https://api.github.com/users/GuoChen-WHU/received_events', type: 'User', site_admin: false, }, body: null, created_at: '2017-03-28T04:40:30Z', updated_at: '2017-03-29T02:43:39Z', closed_at: '2017-03-29T02:43:39Z', merged_at: '2017-03-29T02:43:39Z', merge_commit_sha: '72c9a8623f1765ea9afbb7bd475c1940b09f5c13', assignee: null, assignees: [], milestone: null, commits_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/6/commits', review_comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/6/comments', review_comment_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/comments{/number}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/6/comments', statuses_url: 'https://api.github.com/repos/879479119/react-native-shadow/statuses/a128d4770cbf3f8c62efb005c5935d6171136823', head: { label: 'GuoChen-WHU:master', ref: 'master', sha: 'a128d4770cbf3f8c62efb005c5935d6171136823', user: { login: 'GuoChen-WHU', id: 13191917, avatar_url: 'https://avatars0.githubusercontent.com/u/13191917?v=3', gravatar_id: '', url: 'https://api.github.com/users/GuoChen-WHU', html_url: 'https://github.com/GuoChen-WHU', followers_url: 'https://api.github.com/users/GuoChen-WHU/followers', following_url: 'https://api.github.com/users/GuoChen-WHU/following{/other_user}', gists_url: 'https://api.github.com/users/GuoChen-WHU/gists{/gist_id}', starred_url: 'https://api.github.com/users/GuoChen-WHU/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/GuoChen-WHU/subscriptions', organizations_url: 'https://api.github.com/users/GuoChen-WHU/orgs', repos_url: 'https://api.github.com/users/GuoChen-WHU/repos', events_url: 'https://api.github.com/users/GuoChen-WHU/events{/privacy}', received_events_url: 'https://api.github.com/users/GuoChen-WHU/received_events', type: 'User', site_admin: false, }, repo: { id: 86415246, name: 'react-native-shadow', full_name: 'GuoChen-WHU/react-native-shadow', owner: { login: 'GuoChen-WHU', id: 13191917, avatar_url: 'https://avatars0.githubusercontent.com/u/13191917?v=3', gravatar_id: '', url: 'https://api.github.com/users/GuoChen-WHU', html_url: 'https://github.com/GuoChen-WHU', followers_url: 'https://api.github.com/users/GuoChen-WHU/followers', following_url: 'https://api.github.com/users/GuoChen-WHU/following{/other_user}', gists_url: 'https://api.github.com/users/GuoChen-WHU/gists{/gist_id}', starred_url: 'https://api.github.com/users/GuoChen-WHU/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/GuoChen-WHU/subscriptions', organizations_url: 'https://api.github.com/users/GuoChen-WHU/orgs', repos_url: 'https://api.github.com/users/GuoChen-WHU/repos', events_url: 'https://api.github.com/users/GuoChen-WHU/events{/privacy}', received_events_url: 'https://api.github.com/users/GuoChen-WHU/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/GuoChen-WHU/react-native-shadow', description: 'A SVG shadow component powered with react-native-svg,which can provide shadow on Android like iOS ^_^', fork: true, url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow', forks_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/forks', keys_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/teams', hooks_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/hooks', issue_events_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/issues/events{/number}', events_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/events', assignees_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/assignees{/user}', branches_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/branches{/branch}', tags_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/tags', blobs_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/git/refs{/sha}', trees_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/statuses/{sha}', languages_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/languages', stargazers_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/stargazers', contributors_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/contributors', subscribers_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/subscribers', subscription_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/subscription', commits_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/commits{/sha}', git_commits_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/git/commits{/sha}', comments_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/comments{/number}', issue_comment_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/issues/comments{/number}', contents_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/contents/{+path}', compare_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/merges', archive_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/downloads', issues_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/issues{/number}', pulls_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/pulls{/number}', milestones_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/milestones{/number}', notifications_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/labels{/name}', releases_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/releases{/id}', deployments_url: 'https://api.github.com/repos/GuoChen-WHU/react-native-shadow/deployments', created_at: '2017-03-28T04:35:34Z', updated_at: '2017-03-28T04:35:35Z', pushed_at: '2017-03-28T04:40:27Z', git_url: 'git://github.com/GuoChen-WHU/react-native-shadow.git', ssh_url: 'git@github.com:GuoChen-WHU/react-native-shadow.git', clone_url: 'https://github.com/GuoChen-WHU/react-native-shadow.git', svn_url: 'https://github.com/GuoChen-WHU/react-native-shadow', homepage: null, size: 10, stargazers_count: 0, watchers_count: 0, language: 'JavaScript', has_issues: false, has_projects: true, has_downloads: true, has_wiki: true, has_pages: false, forks_count: 0, mirror_url: null, open_issues_count: 0, forks: 0, open_issues: 0, watchers: 0, default_branch: 'master', }, }, base: { label: '879479119:master', ref: 'master', sha: '24ecc87265f94f5889b0dc31f8a72864b2590169', user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, repo: { id: 69021740, name: 'react-native-shadow', full_name: '879479119/react-native-shadow', owner: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/879479119/react-native-shadow', description: 'A SVG shadow component powered with react-native-svg,which can provide shadow on Android like iOS ^_^', fork: false, url: 'https://api.github.com/repos/879479119/react-native-shadow', forks_url: 'https://api.github.com/repos/879479119/react-native-shadow/forks', keys_url: 'https://api.github.com/repos/879479119/react-native-shadow/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/879479119/react-native-shadow/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/879479119/react-native-shadow/teams', hooks_url: 'https://api.github.com/repos/879479119/react-native-shadow/hooks', issue_events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/events{/number}', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/events', assignees_url: 'https://api.github.com/repos/879479119/react-native-shadow/assignees{/user}', branches_url: 'https://api.github.com/repos/879479119/react-native-shadow/branches{/branch}', tags_url: 'https://api.github.com/repos/879479119/react-native-shadow/tags', blobs_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/refs{/sha}', trees_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/879479119/react-native-shadow/statuses/{sha}', languages_url: 'https://api.github.com/repos/879479119/react-native-shadow/languages', stargazers_url: 'https://api.github.com/repos/879479119/react-native-shadow/stargazers', contributors_url: 'https://api.github.com/repos/879479119/react-native-shadow/contributors', subscribers_url: 'https://api.github.com/repos/879479119/react-native-shadow/subscribers', subscription_url: 'https://api.github.com/repos/879479119/react-native-shadow/subscription', commits_url: 'https://api.github.com/repos/879479119/react-native-shadow/commits{/sha}', git_commits_url: 'https://api.github.com/repos/879479119/react-native-shadow/git/commits{/sha}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/comments{/number}', issue_comment_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/comments{/number}', contents_url: 'https://api.github.com/repos/879479119/react-native-shadow/contents/{+path}', compare_url: 'https://api.github.com/repos/879479119/react-native-shadow/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/879479119/react-native-shadow/merges', archive_url: 'https://api.github.com/repos/879479119/react-native-shadow/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/879479119/react-native-shadow/downloads', issues_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues{/number}', pulls_url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls{/number}', milestones_url: 'https://api.github.com/repos/879479119/react-native-shadow/milestones{/number}', notifications_url: 'https://api.github.com/repos/879479119/react-native-shadow/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/labels{/name}', releases_url: 'https://api.github.com/repos/879479119/react-native-shadow/releases{/id}', deployments_url: 'https://api.github.com/repos/879479119/react-native-shadow/deployments', created_at: '2016-09-23T12:13:33Z', updated_at: '2017-03-21T11:48:31Z', pushed_at: '2017-03-29T02:43:39Z', git_url: 'git://github.com/879479119/react-native-shadow.git', ssh_url: 'git@github.com:879479119/react-native-shadow.git', clone_url: 'https://github.com/879479119/react-native-shadow.git', svn_url: 'https://github.com/879479119/react-native-shadow', homepage: null, size: 9, stargazers_count: 36, watchers_count: 36, language: 'JavaScript', has_issues: true, has_projects: true, has_downloads: true, has_wiki: true, has_pages: false, forks_count: 7, mirror_url: null, open_issues_count: 5, forks: 7, open_issues: 5, watchers: 36, default_branch: 'master', }, }, _links: { self: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/6', }, html: { href: 'https://github.com/879479119/react-native-shadow/pull/6', }, issue: { href: 'https://api.github.com/repos/879479119/react-native-shadow/issues/6', }, comments: { href: 'https://api.github.com/repos/879479119/react-native-shadow/issues/6/comments', }, review_comments: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/6/comments', }, review_comment: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/comments{/number}', }, commits: { href: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/6/commits', }, statuses: { href: 'https://api.github.com/repos/879479119/react-native-shadow/statuses/a128d4770cbf3f8c62efb005c5935d6171136823', }, }, merged: true, mergeable: null, mergeable_state: 'unknown', merged_by: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, comments: 1, review_comments: 0, maintainer_can_modify: false, commits: 1, additions: 1, deletions: 1, changed_files: 1, }, }, public: true, created_at: '2017-03-29T02:43:39Z', }, { id: '5583964715', type: 'IssueCommentEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'created', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/6', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/6/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/6/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/6/events', html_url: 'https://github.com/879479119/react-native-shadow/pull/6', id: 217446294, number: 6, title: 'typo', user: { login: 'GuoChen-WHU', id: 13191917, avatar_url: 'https://avatars0.githubusercontent.com/u/13191917?v=3', gravatar_id: '', url: 'https://api.github.com/users/GuoChen-WHU', html_url: 'https://github.com/GuoChen-WHU', followers_url: 'https://api.github.com/users/GuoChen-WHU/followers', following_url: 'https://api.github.com/users/GuoChen-WHU/following{/other_user}', gists_url: 'https://api.github.com/users/GuoChen-WHU/gists{/gist_id}', starred_url: 'https://api.github.com/users/GuoChen-WHU/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/GuoChen-WHU/subscriptions', organizations_url: 'https://api.github.com/users/GuoChen-WHU/orgs', repos_url: 'https://api.github.com/users/GuoChen-WHU/repos', events_url: 'https://api.github.com/users/GuoChen-WHU/events{/privacy}', received_events_url: 'https://api.github.com/users/GuoChen-WHU/received_events', type: 'User', site_admin: false, }, labels: [], state: 'open', locked: false, assignee: null, assignees: [], milestone: null, comments: 0, created_at: '2017-03-28T04:40:30Z', updated_at: '2017-03-29T02:43:12Z', closed_at: null, pull_request: { url: 'https://api.github.com/repos/879479119/react-native-shadow/pulls/6', html_url: 'https://github.com/879479119/react-native-shadow/pull/6', diff_url: 'https://github.com/879479119/react-native-shadow/pull/6.diff', patch_url: 'https://github.com/879479119/react-native-shadow/pull/6.patch', }, body: null, }, comment: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/comments/289965234', html_url: 'https://github.com/879479119/react-native-shadow/pull/6#issuecomment-289965234', issue_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/6', id: 289965234, user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, created_at: '2017-03-29T02:43:12Z', updated_at: '2017-03-29T02:43:12Z', body: 'thx~', }, }, public: true, created_at: '2017-03-29T02:43:12Z', }, { id: '5576909681', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 43797718, name: 'acdlite/recompose', url: 'https://api.github.com/repos/acdlite/recompose', }, payload: { action: 'started', }, public: true, created_at: '2017-03-28T08:17:45Z', }, { id: '5547410438', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85547588, name: '879479119/Magic-Resume', url: 'https://api.github.com/repos/879479119/Magic-Resume', }, payload: { push_id: 1631955082, size: 3, distinct_size: 3, ref: 'refs/heads/master', head: '7796d521a002c89ee25faa758c052c9f5a3183c6', before: '2b66f3007c3e988766c8f60c168e34711ae759ea', commits: [ { sha: '0bb2607d701b1134e56f4162c3bcca857869a632', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'init the project', distinct: true, url: 'https://api.github.com/repos/879479119/Magic-Resume/commits/0bb2607d701b1134e56f4162c3bcca857869a632', }, { sha: '5c7aa461ec281a3f3293e0ed936b27533bdd368b', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':smoke: install all the loaders we need :lollipop:', distinct: true, url: 'https://api.github.com/repos/879479119/Magic-Resume/commits/5c7aa461ec281a3f3293e0ed936b27533bdd368b', }, { sha: '7796d521a002c89ee25faa758c052c9f5a3183c6', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':kiss: :kiss: :kiss: :kiss: ejs template added', distinct: true, url: 'https://api.github.com/repos/879479119/Magic-Resume/commits/7796d521a002c89ee25faa758c052c9f5a3183c6', }, ], }, public: true, created_at: '2017-03-23T05:29:21Z', }, { id: '5547341855', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 25683935, name: 'bazilio91/ejs-compiled-loader', url: 'https://api.github.com/repos/bazilio91/ejs-compiled-loader', }, payload: { action: 'started', }, public: true, created_at: '2017-03-23T05:08:32Z', }, { id: '5523587739', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85547588, name: '879479119/Magic-Resume', url: 'https://api.github.com/repos/879479119/Magic-Resume', }, payload: { ref: 'master', ref_type: 'branch', master_branch: 'master', description: ':cn:-:cookie: Just a personal page for fun ~', pusher_type: 'user', }, public: true, created_at: '2017-03-20T07:32:49Z', }, { id: '5523587687', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85547588, name: '879479119/Magic-Resume', url: 'https://api.github.com/repos/879479119/Magic-Resume', }, payload: { ref: null, ref_type: 'repository', master_branch: 'master', description: ':cn:-:cookie: Just a personal page for fun ~', pusher_type: 'user', }, public: true, created_at: '2017-03-20T07:32:48Z', }, { id: '5523543418', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 71330626, name: '879479119/SPA-starter-kit', url: 'https://api.github.com/repos/879479119/SPA-starter-kit', }, payload: { push_id: 1624167296, size: 3, distinct_size: 3, ref: 'refs/heads/master', head: 'cebaebc56e62f75f945df100e6a31654e75d0306', before: '850f0dbefb513d34a6397e0bfd42c0093424a9c0', commits: [ { sha: 'a8e3a86f9eadbdb29dcbfc8ab9d48c7d7bcbe42d', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'update webpack.config.js ! more powerful !', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/a8e3a86f9eadbdb29dcbfc8ab9d48c7d7bcbe42d', }, { sha: 'd57baab4b089f6cefe5b745be4763669512fd6b6', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'autoprefixer added', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/d57baab4b089f6cefe5b745be4763669512fd6b6', }, { sha: 'cebaebc56e62f75f945df100e6a31654e75d0306', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: "Merge remote-tracking branch 'origin/master'\n\n# Conflicts:\n#\tREADME.md", distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/cebaebc56e62f75f945df100e6a31654e75d0306', }, ], }, public: true, created_at: '2017-03-20T07:18:50Z', }, { id: '5521055850', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 3046807, name: 'mitsuhiko/webgl-meincraft', url: 'https://api.github.com/repos/mitsuhiko/webgl-meincraft', }, payload: { action: 'started', }, public: true, created_at: '2017-03-19T12:21:57Z', }, { id: '5520781603', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 71330626, name: '879479119/SPA-starter-kit', url: 'https://api.github.com/repos/879479119/SPA-starter-kit', }, payload: { push_id: 1623088412, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '850f0dbefb513d34a6397e0bfd42c0093424a9c0', before: '0b171484d50a1a0ca8b3405e01a6bb1aa4d6b8ce', commits: [ { sha: '850f0dbefb513d34a6397e0bfd42c0093424a9c0', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Update README.md', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/850f0dbefb513d34a6397e0bfd42c0093424a9c0', }, ], }, public: true, created_at: '2017-03-19T09:28:14Z', }, { id: '5520778343', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 71330626, name: '879479119/SPA-starter-kit', url: 'https://api.github.com/repos/879479119/SPA-starter-kit', }, payload: { push_id: 1623087158, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '0b171484d50a1a0ca8b3405e01a6bb1aa4d6b8ce', before: '610834462a75f4bc3e0d93a15df7391d0807a9ce', commits: [ { sha: '0b171484d50a1a0ca8b3405e01a6bb1aa4d6b8ce', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'update README.md', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/0b171484d50a1a0ca8b3405e01a6bb1aa4d6b8ce', }, ], }, public: true, created_at: '2017-03-19T09:25:58Z', }, { id: '5520690819', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 71330626, name: '879479119/SPA-starter-kit', url: 'https://api.github.com/repos/879479119/SPA-starter-kit', }, payload: { push_id: 1623051611, size: 4, distinct_size: 4, ref: 'refs/heads/master', head: '610834462a75f4bc3e0d93a15df7391d0807a9ce', before: 'ab9dcabc314711509067d0b340c7ea16262d2edb', commits: [ { sha: '4581fa818abcd8753411ecf4fd4882a1ff97506f', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Oh my broken heart', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/4581fa818abcd8753411ecf4fd4882a1ff97506f', }, { sha: 'c2618faf388aa9a859bff<PASSWORD>3<PASSWORD>', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'half complete ~ :smoke:', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/c2618faf388aa9a859bff9fc841be310aa1eed73', }, { sha: 'c8b8290d9593314409b6ea33063c96deff998118', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'music player added -- just one song there', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/c8b8290d9593314409b6ea33063c96deff998118', }, { sha: '610834462a75f4bc3e0d93a15df7391d0807a9ce', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'force push & give up tracked files', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/610834462a75f4bc3e0d93a15df7391d0807a9ce', }, ], }, public: true, created_at: '2017-03-19T08:25:07Z', }, { id: '5518683695', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 15349676, name: 'gulpjs/vinyl', url: 'https://api.github.com/repos/gulpjs/vinyl', }, payload: { action: 'started', }, public: true, created_at: '2017-03-18T11:48:54Z', org: { id: 6200624, login: 'gulpjs', gravatar_id: '', url: 'https://api.github.com/orgs/gulpjs', avatar_url: 'https://avatars.githubusercontent.com/u/6200624?', }, }, { id: '5518633413', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 46037934, name: 'mixtur/webpack-spritesmith', url: 'https://api.github.com/repos/mixtur/webpack-spritesmith', }, payload: { action: 'started', }, public: true, created_at: '2017-03-18T11:17:13Z', }, { id: '5518458460', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85290387, name: '879479119/Spirit-loader', url: 'https://api.github.com/repos/879479119/Spirit-loader', }, payload: { push_id: 1622164793, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: 'ddfe7eb23778dab27595043bb346718c5e39eb75', before: '24829d6b75b864e93835da8682144ff708f003fc', commits: [ { sha: 'ddfe7eb23778dab27595043bb346718c5e39eb75', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'And two badage and ready to Work!', distinct: true, url: 'https://api.github.com/repos/879479119/Spirit-loader/commits/ddfe7eb23778dab27595043bb346718c5e39eb75', }, ], }, public: true, created_at: '2017-03-18T09:26:54Z', }, { id: '5518330731', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85290387, name: '879479119/Spirit-loader', url: 'https://api.github.com/repos/879479119/Spirit-loader', }, payload: { push_id: 1622114566, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '24829d6b75b864e93835da8682144ff708f003fc', before: '13be1d4a2dded777aa508263fb42199341b45cbf', commits: [ { sha: '24829d6b75b864e93835da8682144ff708f003fc', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'last trial !', distinct: true, url: 'https://api.github.com/repos/879479119/Spirit-loader/commits/24829d6b75b864e93835da8682144ff708f003fc', }, ], }, public: true, created_at: '2017-03-18T07:58:19Z', }, { id: '5515459598', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85290387, name: '879479119/Spirit-loader', url: 'https://api.github.com/repos/879479119/Spirit-loader', }, payload: { push_id: 1621186398, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '13be1d4a2dded777aa508263fb42199341b45cbf', before: 'fb6dd936ec19ab2fa4eed171c817f084174dfc2c', commits: [ { sha: '13be1d4a2dded777aa508263fb42199341b45cbf', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'last trial !', distinct: true, url: 'https://api.github.com/repos/879479119/Spirit-loader/commits/13be1d4a2dded777aa508263fb42199341b45cbf', }, ], }, public: true, created_at: '2017-03-17T17:29:48Z', }, { id: '5515450630', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85290387, name: '879479119/Spirit-loader', url: 'https://api.github.com/repos/879479119/Spirit-loader', }, payload: { push_id: 1621183566, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: 'fb6dd936ec19ab2fa4eed171c817f084174dfc2c', before: '19a45975558f8b4cf10c3c2dd66635ebcbe6e5fa', commits: [ { sha: 'fb6dd936ec19ab2fa4eed171c817f084174dfc2c', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'last trial !', distinct: true, url: 'https://api.github.com/repos/879479119/Spirit-loader/commits/fb6dd936ec19ab2fa4eed171c817f084174dfc2c', }, ], }, public: true, created_at: '2017-03-17T17:28:24Z', }, { id: '5515410395', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85290387, name: '879479119/Spirit-loader', url: 'https://api.github.com/repos/879479119/Spirit-loader', }, payload: { push_id: 1621171138, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '19a45975558f8b4cf10c3c2dd66635ebcbe6e5fa', before: '35032a084bc3e9f161c8bfef0f7c441b051f8fd7', commits: [ { sha: '19a45975558f8b4cf10c3c2dd66635ebcbe6e5fa', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'just travis test', distinct: true, url: 'https://api.github.com/repos/879479119/Spirit-loader/commits/19a45975558f8b4cf10c3c2dd66635ebcbe6e5fa', }, ], }, public: true, created_at: '2017-03-17T17:22:22Z', }, { id: '5515257130', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85290387, name: '879479119/Spirit-loader', url: 'https://api.github.com/repos/879479119/Spirit-loader', }, payload: { push_id: 1621124164, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '35032a084bc3e9f161c8bfef0f7c441b051f8fd7', before: 'be151f2409d152a9b1aede8af32c04bb4cbb0713', commits: [ { sha: '35032a084bc3e9f161c8bfef0f7c441b051f8fd7', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'maybe right ?', distinct: true, url: 'https://api.github.com/repos/879479119/Spirit-loader/commits/35032a084bc3e9f161c8bfef0f7c441b051f8fd7', }, ], }, public: true, created_at: '2017-03-17T16:59:34Z', }, { id: '5512247261', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 85290387, name: '879479119/Spirit-loader', url: 'https://api.github.com/repos/879479119/Spirit-loader', }, payload: { ref: null, ref_type: 'repository', master_branch: 'master', description: 'A webpack plugin for spirit images, this must be a long way to go...', pusher_type: 'user', }, public: true, created_at: '2017-03-17T08:49:29Z', }, { id: '5511666142', type: 'ForkEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 58623321, name: 'Bilibili/flv.js', url: 'https://api.github.com/repos/Bilibili/flv.js', }, payload: { forkee: { id: 85277234, name: 'flv.js', full_name: '879479119/flv.js', owner: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/879479119/flv.js', description: 'HTML5 FLV Player', fork: true, url: 'https://api.github.com/repos/879479119/flv.js', forks_url: 'https://api.github.com/repos/879479119/flv.js/forks', keys_url: 'https://api.github.com/repos/879479119/flv.js/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/879479119/flv.js/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/879479119/flv.js/teams', hooks_url: 'https://api.github.com/repos/879479119/flv.js/hooks', issue_events_url: 'https://api.github.com/repos/879479119/flv.js/issues/events{/number}', events_url: 'https://api.github.com/repos/879479119/flv.js/events', assignees_url: 'https://api.github.com/repos/879479119/flv.js/assignees{/user}', branches_url: 'https://api.github.com/repos/879479119/flv.js/branches{/branch}', tags_url: 'https://api.github.com/repos/879479119/flv.js/tags', blobs_url: 'https://api.github.com/repos/879479119/flv.js/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/879479119/flv.js/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/879479119/flv.js/git/refs{/sha}', trees_url: 'https://api.github.com/repos/879479119/flv.js/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/879479119/flv.js/statuses/{sha}', languages_url: 'https://api.github.com/repos/879479119/flv.js/languages', stargazers_url: 'https://api.github.com/repos/879479119/flv.js/stargazers', contributors_url: 'https://api.github.com/repos/879479119/flv.js/contributors', subscribers_url: 'https://api.github.com/repos/879479119/flv.js/subscribers', subscription_url: 'https://api.github.com/repos/879479119/flv.js/subscription', commits_url: 'https://api.github.com/repos/879479119/flv.js/commits{/sha}', git_commits_url: 'https://api.github.com/repos/879479119/flv.js/git/commits{/sha}', comments_url: 'https://api.github.com/repos/879479119/flv.js/comments{/number}', issue_comment_url: 'https://api.github.com/repos/879479119/flv.js/issues/comments{/number}', contents_url: 'https://api.github.com/repos/879479119/flv.js/contents/{+path}', compare_url: 'https://api.github.com/repos/879479119/flv.js/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/879479119/flv.js/merges', archive_url: 'https://api.github.com/repos/879479119/flv.js/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/879479119/flv.js/downloads', issues_url: 'https://api.github.com/repos/879479119/flv.js/issues{/number}', pulls_url: 'https://api.github.com/repos/879479119/flv.js/pulls{/number}', milestones_url: 'https://api.github.com/repos/879479119/flv.js/milestones{/number}', notifications_url: 'https://api.github.com/repos/879479119/flv.js/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/879479119/flv.js/labels{/name}', releases_url: 'https://api.github.com/repos/879479119/flv.js/releases{/id}', deployments_url: 'https://api.github.com/repos/879479119/flv.js/deployments', created_at: '2017-03-17T06:12:49Z', updated_at: '2017-03-17T06:12:43Z', pushed_at: '2017-03-07T17:32:26Z', git_url: 'git://github.com/879479119/flv.js.git', ssh_url: 'git@github.com:879479119/flv.js.git', clone_url: 'https://github.com/879479119/flv.js.git', svn_url: 'https://github.com/879479119/flv.js', homepage: null, size: 422, stargazers_count: 0, watchers_count: 0, language: null, has_issues: false, has_downloads: true, has_wiki: true, has_pages: false, forks_count: 0, mirror_url: null, open_issues_count: 0, forks: 0, open_issues: 0, watchers: 0, default_branch: 'master', public: true, }, }, public: true, created_at: '2017-03-17T06:12:49Z', org: { id: 12002442, login: 'Bilibili', gravatar_id: '', url: 'https://api.github.com/orgs/Bilibili', avatar_url: 'https://avatars.githubusercontent.com/u/12002442?', }, }, { id: '5511665875', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 58623321, name: 'Bilibili/flv.js', url: 'https://api.github.com/repos/Bilibili/flv.js', }, payload: { action: 'started', }, public: true, created_at: '2017-03-17T06:12:43Z', org: { id: 12002442, login: 'Bilibili', gravatar_id: '', url: 'https://api.github.com/orgs/Bilibili', avatar_url: 'https://avatars.githubusercontent.com/u/12002442?', }, }, { id: '5503721610', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 42283287, name: 'developit/preact', url: 'https://api.github.com/repos/developit/preact', }, payload: { action: 'started', }, public: true, created_at: '2017-03-16T05:42:13Z', }, { id: '5495786504', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 34808241, name: 'WebAssembly/design', url: 'https://api.github.com/repos/WebAssembly/design', }, payload: { action: 'started', }, public: true, created_at: '2017-03-15T06:09:51Z', org: { id: 11578470, login: 'WebAssembly', gravatar_id: '', url: 'https://api.github.com/orgs/WebAssembly', avatar_url: 'https://avatars.githubusercontent.com/u/11578470?', }, }, { id: '5495181923', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 53998016, name: 'tusenpo/FlappyFrog', url: 'https://api.github.com/repos/tusenpo/FlappyFrog', }, payload: { action: 'started', }, public: true, created_at: '2017-03-15T03:00:58Z', }, { id: '5487792619', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { push_id: 1612134930, size: 5, distinct_size: 1, ref: 'refs/heads/master', head: '2c5fd91a1908d8327246c6d1dfe6912bb143b978', before: 'd341a0bb81faed384312a510c04ef8b91b3edd26', commits: [ { sha: '059cd9c9b295bc6f173796dc2e29712d922114f2', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'prepare for optimize:wink:', distinct: false, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/059cd9c9b295bc6f173796dc2e29712d922114f2', }, { sha: 'e255d3007d9d41902087d0ce9608be374c384e7a', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'optimize step 1', distinct: false, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/e255d3007d9d41902087d0ce9608be374c384e7a', }, { sha: '7fd735941cceb19570449d970c2278626f57531c', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'safely work in 60fps', distinct: false, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/7fd735941cceb19570449d970c2278626f57531c', }, { sha: '7793b5559a7f3914dbe1f1c36dca99d778de360e', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'add some selection animation~', distinct: false, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/7793b5559a7f3914dbe1f1c36dca99d778de360e', }, { sha: '2c5fd91a1908d8327246c6d1dfe6912bb143b978', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'Merge pull request #1 from 879479119/optimize\n\nOptimize', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/2c5fd91a1908d8327246c6d1dfe6912bb143b978', }, ], }, public: true, created_at: '2017-03-14T06:32:51Z', }, { id: '5487792588', type: 'PullRequestEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { action: 'closed', number: 1, pull_request: { url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1', id: 110556248, html_url: 'https://github.com/879479119/Battle-City-Advanced/pull/1', diff_url: 'https://github.com/879479119/Battle-City-Advanced/pull/1.diff', patch_url: 'https://github.com/879479119/Battle-City-Advanced/pull/1.patch', issue_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/1', number: 1, state: 'closed', locked: false, title: 'Optimize', user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, body: 'create another canvas to optimize the performance 👍 ', created_at: '2017-03-14T06:32:32Z', updated_at: '2017-03-14T06:32:50Z', closed_at: '2017-03-14T06:32:50Z', merged_at: '2017-03-14T06:32:50Z', merge_commit_sha: '2c5fd91a1908d8327246c6d1dfe6912bb143b978', assignee: null, assignees: [], milestone: null, commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1/commits', review_comments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1/comments', review_comment_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/comments{/number}', comments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/1/comments', statuses_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/statuses/7793b5559a7f3914dbe1f1c36dca99d778de360e', head: { label: '879479119:optimize', ref: 'optimize', sha: '7793b5559a7f3914dbe1f1c36dca99d778de360e', user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, repo: { id: 82656873, name: 'Battle-City-Advanced', full_name: '879479119/Battle-City-Advanced', owner: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/879479119/Battle-City-Advanced', description: ':lollipop: This is a game based on canvas! Editable and more smooth :video_game:', fork: false, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', forks_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/forks', keys_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/teams', hooks_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/hooks', issue_events_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/events{/number}', events_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/events', assignees_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/assignees{/user}', branches_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/branches{/branch}', tags_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/tags', blobs_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/refs{/sha}', trees_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/statuses/{sha}', languages_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/languages', stargazers_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/stargazers', contributors_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/contributors', subscribers_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/subscribers', subscription_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/subscription', commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits{/sha}', git_commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/commits{/sha}', comments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/comments{/number}', issue_comment_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/comments{/number}', contents_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/contents/{+path}', compare_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/merges', archive_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/downloads', issues_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues{/number}', pulls_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls{/number}', milestones_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/milestones{/number}', notifications_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/labels{/name}', releases_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/releases{/id}', deployments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/deployments', created_at: '2017-02-21T08:47:03Z', updated_at: '2017-03-04T05:17:46Z', pushed_at: '2017-03-14T06:32:50Z', git_url: 'git://github.com/879479119/Battle-City-Advanced.git', ssh_url: 'git@github.com:879479119/Battle-City-Advanced.git', clone_url: 'https://github.com/879479119/Battle-City-Advanced.git', svn_url: 'https://github.com/879479119/Battle-City-Advanced', homepage: null, size: 1281, stargazers_count: 1, watchers_count: 1, language: 'JavaScript', has_issues: true, has_downloads: true, has_wiki: true, has_pages: true, forks_count: 0, mirror_url: null, open_issues_count: 0, forks: 0, open_issues: 0, watchers: 1, default_branch: 'master', }, }, base: { label: '879479119:master', ref: 'master', sha: 'd341a0bb81faed384312a510c04ef8b91b3edd26', user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, repo: { id: 82656873, name: 'Battle-City-Advanced', full_name: '879479119/Battle-City-Advanced', owner: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/879479119/Battle-City-Advanced', description: ':lollipop: This is a game based on canvas! Editable and more smooth :video_game:', fork: false, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', forks_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/forks', keys_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/teams', hooks_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/hooks', issue_events_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/events{/number}', events_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/events', assignees_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/assignees{/user}', branches_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/branches{/branch}', tags_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/tags', blobs_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/refs{/sha}', trees_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/statuses/{sha}', languages_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/languages', stargazers_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/stargazers', contributors_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/contributors', subscribers_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/subscribers', subscription_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/subscription', commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits{/sha}', git_commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/commits{/sha}', comments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/comments{/number}', issue_comment_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/comments{/number}', contents_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/contents/{+path}', compare_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/merges', archive_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/downloads', issues_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues{/number}', pulls_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls{/number}', milestones_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/milestones{/number}', notifications_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/labels{/name}', releases_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/releases{/id}', deployments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/deployments', created_at: '2017-02-21T08:47:03Z', updated_at: '2017-03-04T05:17:46Z', pushed_at: '2017-03-14T06:32:50Z', git_url: 'git://github.com/879479119/Battle-City-Advanced.git', ssh_url: 'git@github.com:879479119/Battle-City-Advanced.git', clone_url: 'https://github.com/879479119/Battle-City-Advanced.git', svn_url: 'https://github.com/879479119/Battle-City-Advanced', homepage: null, size: 1281, stargazers_count: 1, watchers_count: 1, language: 'JavaScript', has_issues: true, has_downloads: true, has_wiki: true, has_pages: true, forks_count: 0, mirror_url: null, open_issues_count: 0, forks: 0, open_issues: 0, watchers: 1, default_branch: 'master', }, }, _links: { self: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1', }, html: { href: 'https://github.com/879479119/Battle-City-Advanced/pull/1', }, issue: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/1', }, comments: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/1/comments', }, review_comments: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1/comments', }, review_comment: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/comments{/number}', }, commits: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1/commits', }, statuses: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/statuses/7793b5559a7f3914dbe1f1c36dca99d778de360e', }, }, merged: true, mergeable: null, mergeable_state: 'unknown', merged_by: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, comments: 0, review_comments: 0, maintainer_can_modify: false, commits: 4, additions: 436, deletions: 275, changed_files: 8, }, }, public: true, created_at: '2017-03-14T06:32:50Z', }, { id: '5487791630', type: 'PullRequestEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { action: 'opened', number: 1, pull_request: { url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1', id: 110556248, html_url: 'https://github.com/879479119/Battle-City-Advanced/pull/1', diff_url: 'https://github.com/879479119/Battle-City-Advanced/pull/1.diff', patch_url: 'https://github.com/879479119/Battle-City-Advanced/pull/1.patch', issue_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/1', number: 1, state: 'open', locked: false, title: 'Optimize', user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, body: 'create another canvas to optimize the performance 👍 ', created_at: '2017-03-14T06:32:32Z', updated_at: '2017-03-14T06:32:32Z', closed_at: null, merged_at: null, merge_commit_sha: null, assignee: null, assignees: [], milestone: null, commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1/commits', review_comments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1/comments', review_comment_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/comments{/number}', comments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/1/comments', statuses_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/statuses/7793b5559a7f3914dbe1f1c36dca99d778de360e', head: { label: '879479119:optimize', ref: 'optimize', sha: '7793b5559a7f3914dbe1f1c36dca99d778de360e', user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, repo: { id: 82656873, name: 'Battle-City-Advanced', full_name: '879479119/Battle-City-Advanced', owner: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/879479119/Battle-City-Advanced', description: ':lollipop: This is a game based on canvas! Editable and more smooth :video_game:', fork: false, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', forks_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/forks', keys_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/teams', hooks_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/hooks', issue_events_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/events{/number}', events_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/events', assignees_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/assignees{/user}', branches_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/branches{/branch}', tags_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/tags', blobs_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/refs{/sha}', trees_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/statuses/{sha}', languages_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/languages', stargazers_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/stargazers', contributors_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/contributors', subscribers_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/subscribers', subscription_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/subscription', commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits{/sha}', git_commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/commits{/sha}', comments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/comments{/number}', issue_comment_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/comments{/number}', contents_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/contents/{+path}', compare_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/merges', archive_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/downloads', issues_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues{/number}', pulls_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls{/number}', milestones_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/milestones{/number}', notifications_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/labels{/name}', releases_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/releases{/id}', deployments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/deployments', created_at: '2017-02-21T08:47:03Z', updated_at: '2017-03-04T05:17:46Z', pushed_at: '2017-03-14T06:30:18Z', git_url: 'git://github.com/879479119/Battle-City-Advanced.git', ssh_url: 'git@github.com:879479119/Battle-City-Advanced.git', clone_url: 'https://github.com/879479119/Battle-City-Advanced.git', svn_url: 'https://github.com/879479119/Battle-City-Advanced', homepage: null, size: 1281, stargazers_count: 1, watchers_count: 1, language: 'JavaScript', has_issues: true, has_downloads: true, has_wiki: true, has_pages: true, forks_count: 0, mirror_url: null, open_issues_count: 1, forks: 0, open_issues: 1, watchers: 1, default_branch: 'master', }, }, base: { label: '879479119:master', ref: 'master', sha: 'd341a0bb81faed384312a510c04ef8b91b3edd26', user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, repo: { id: 82656873, name: 'Battle-City-Advanced', full_name: '879479119/Battle-City-Advanced', owner: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, private: false, html_url: 'https://github.com/879479119/Battle-City-Advanced', description: ':lollipop: This is a game based on canvas! Editable and more smooth :video_game:', fork: false, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', forks_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/forks', keys_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/keys{/key_id}', collaborators_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/collaborators{/collaborator}', teams_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/teams', hooks_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/hooks', issue_events_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/events{/number}', events_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/events', assignees_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/assignees{/user}', branches_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/branches{/branch}', tags_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/tags', blobs_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/blobs{/sha}', git_tags_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/tags{/sha}', git_refs_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/refs{/sha}', trees_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/trees{/sha}', statuses_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/statuses/{sha}', languages_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/languages', stargazers_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/stargazers', contributors_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/contributors', subscribers_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/subscribers', subscription_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/subscription', commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits{/sha}', git_commits_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/git/commits{/sha}', comments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/comments{/number}', issue_comment_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/comments{/number}', contents_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/contents/{+path}', compare_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/compare/{base}...{head}', merges_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/merges', archive_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/{archive_format}{/ref}', downloads_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/downloads', issues_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues{/number}', pulls_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls{/number}', milestones_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/milestones{/number}', notifications_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/notifications{?since,all,participating}', labels_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/labels{/name}', releases_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/releases{/id}', deployments_url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/deployments', created_at: '2017-02-21T08:47:03Z', updated_at: '2017-03-04T05:17:46Z', pushed_at: '2017-03-14T06:30:18Z', git_url: 'git://github.com/879479119/Battle-City-Advanced.git', ssh_url: 'git@github.com:879479119/Battle-City-Advanced.git', clone_url: 'https://github.com/879479119/Battle-City-Advanced.git', svn_url: 'https://github.com/879479119/Battle-City-Advanced', homepage: null, size: 1281, stargazers_count: 1, watchers_count: 1, language: 'JavaScript', has_issues: true, has_downloads: true, has_wiki: true, has_pages: true, forks_count: 0, mirror_url: null, open_issues_count: 1, forks: 0, open_issues: 1, watchers: 1, default_branch: 'master', }, }, _links: { self: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1', }, html: { href: 'https://github.com/879479119/Battle-City-Advanced/pull/1', }, issue: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/1', }, comments: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/issues/1/comments', }, review_comments: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1/comments', }, review_comment: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/comments{/number}', }, commits: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/pulls/1/commits', }, statuses: { href: 'https://api.github.com/repos/879479119/Battle-City-Advanced/statuses/7793b5559a7f3914dbe1f1c36dca99d778de360e', }, }, merged: false, mergeable: null, mergeable_state: 'unknown', merged_by: null, comments: 0, review_comments: 0, maintainer_can_modify: false, commits: 4, additions: 436, deletions: 275, changed_files: 8, }, }, public: true, created_at: '2017-03-14T06:32:33Z', }, { id: '5487784133', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { push_id: 1612131938, size: 2, distinct_size: 2, ref: 'refs/heads/optimize', head: '7793b5559a7f3914dbe1f1c36dca99d778de360e', before: 'e255d3007d9d41902087d0ce9608be374c384e7a', commits: [ { sha: '7fd735941cceb19570449d970c2278626f57531c', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'safely work in 60fps', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/7fd735941cceb19570449d970c2278626f57531c', }, { sha: '7793b5559a7f3914dbe1f1c36dca99d778de360e', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'add some selection animation~', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/7793b5559a7f3914dbe1f1c36dca99d778de360e', }, ], }, public: true, created_at: '2017-03-14T06:30:18Z', }, { id: '5483634318', type: 'CreateEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { ref: 'optimize', ref_type: 'branch', master_branch: 'master', description: ':lollipop: This is a game based on canvas! Editable and more smooth :video_game:', pusher_type: 'user', }, public: true, created_at: '2017-03-13T16:34:24Z', }, { id: '5477076357', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { push_id: 1608412658, size: 3, distinct_size: 3, ref: 'refs/heads/master', head: 'd341a0bb81faed384312a510c04ef8b91b3edd26', before: '089bca72359756882ff927fe1c13d00d6e1442a2', commits: [ { sha: '1570a931ef817eef7ce8ccf9920d03bfece31d26', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'fix some bugs :traffic_light:', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/1570a931ef817eef7ce8ccf9920d03bfece31d26', }, { sha: 'e737588c555bd6<PASSWORD>', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: '0.0 add some new images', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/e737588c555bd679f2808e81039723ecdbef17f0', }, { sha: 'd341a0bb81faed384312a510c04ef8b91b3edd26', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'change canvas lies in the right center', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/d341a0bb81faed384312a510c04ef8b91b3edd26', }, ], }, public: true, created_at: '2017-03-12T03:37:41Z', }, { id: '5475630983', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 49323219, name: 'lcxfs1991/html-res-webpack-plugin', url: 'https://api.github.com/repos/lcxfs1991/html-res-webpack-plugin', }, payload: { action: 'started', }, public: true, created_at: '2017-03-11T13:15:55Z', }, { id: '5470281358', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { push_id: 1606044390, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '089bca72359756882ff927fe1c13d00d6e1442a2', before: '2a197276369b21fdb53abb0a4d26af4e9860e18f', commits: [ { sha: '089bca72359756882ff927fe1c13d00d6e1442a2', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'fix some bugs :traffic_light:', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/089bca72359756882ff927fe1c13d00d6e1442a2', }, ], }, public: true, created_at: '2017-03-10T12:37:15Z', }, { id: '5452484390', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { push_id: 1600201978, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '2a197276369b21fdb53abb0a4d26af4e9860e18f', before: '638bee99dc00440cd7cb8168562d9af3a3500dd7', commits: [ { sha: '2a197276369b21fdb53abb0a4d26af4e9860e18f', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'TODO LIST ADDED :smile:', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/2a197276369b21fdb53abb0a4d26af4e9860e18f', }, ], }, public: true, created_at: '2017-03-08T03:15:01Z', }, { id: '5438083036', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 57121262, name: '879479119/879479119.github.com', url: 'https://api.github.com/repos/879479119/879479119.github.com', }, payload: { push_id: 1595554637, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '7a2d30074c176bf700657308564d9cb7172c577c', before: 'df849aec1e27e625a6c35f249e6a94a8bd2c018d', commits: [ { sha: '7a2d30074c176bf700657308564d9cb7172c577c', author: { email: '<PASSWORD> <EMAIL>', name: 'RockSAMA', }, message: 'Site updated: 2017-03-06 17:25:27', distinct: true, url: 'https://api.github.com/repos/879479119/879479119.github.com/commits/7a2d30074c176bf700657308564d9cb7172c577c', }, ], }, public: true, created_at: '2017-03-06T09:26:02Z', }, { id: '5432547502', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { push_id: 1593377187, size: 2, distinct_size: 2, ref: 'refs/heads/master', head: '638bee99dc00440cd7cb8168562d9af3a3500dd7', before: 'b4834e6a1a65d9635477c1a078405e2d9eda8c0a', commits: [ { sha: '7f91bce29b5bd8<PASSWORD>', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'fix all functional buttons :sunglasses:', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/7f91bce29b5bd83080362e8ed3ab38e01940c6e1', }, { sha: '638bee99dc00440cd7cb8168562d9af3a3500dd7', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'daily update', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/638bee99dc00440cd7cb8168562d9af3a3500dd7', }, ], }, public: true, created_at: '2017-03-04T11:26:28Z', }, { id: '5432287936', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { push_id: 1593255164, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: 'b4834e6a1a65d9635477c1a078405e2d9eda8c0a', before: '9cb74c66dabd0433755a08860ccfd714b8e9b1b1', commits: [ { sha: 'b4834e6a1a65d9635477c1a078405e2d9eda8c0a', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'rerun this project', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/b4834e6a1a65d9635477c1a078405e2d9eda8c0a', }, ], }, public: true, created_at: '2017-03-04T08:41:56Z', }, { id: '5431940802', type: 'WatchEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { action: 'started', }, public: true, created_at: '2017-03-04T05:06:25Z', }, { id: '5431940047', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { push_id: 1593093854, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '9cb74c66dabd0433755a08860ccfd714b8e9b1b1', before: '994e2871227eabfdc7925abe35b09ce72fcb7483', commits: [ { sha: '9cb74c66dabd0433755a08860ccfd714b8e9b1b1', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'update readme:smile:', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/9cb74c66dabd0433755a08860ccfd714b8e9b1b1', }, ], }, public: true, created_at: '2017-03-04T05:05:56Z', }, { id: '5431897505', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 82656873, name: '879479119/Battle-City-Advanced', url: 'https://api.github.com/repos/879479119/Battle-City-Advanced', }, payload: { push_id: 1593077229, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '994e2871227eabfdc7925abe35b09ce72fcb7483', before: '8e5eae8f3707be9e50e20d4c4837dda2b706188e', commits: [ { sha: '994e2871227eabfdc7925abe35b09ce72fcb7483', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':lollipop: remove the redundant parts', distinct: true, url: 'https://api.github.com/repos/879479119/Battle-City-Advanced/commits/994e2871227eabfdc7925abe35b09ce72fcb7483', }, ], }, public: true, created_at: '2017-03-04T04:38:51Z', }, { id: '5431749985', type: 'IssueCommentEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'created', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5/events', html_url: 'https://github.com/879479119/react-native-shadow/issues/5', id: 210414005, number: 5, title: 'how to change shadow backgroundColor', user: { login: 'JourneyL', id: 18393378, avatar_url: 'https://avatars2.githubusercontent.com/u/18393378?v=3', gravatar_id: '', url: 'https://api.github.com/users/JourneyL', html_url: 'https://github.com/JourneyL', followers_url: 'https://api.github.com/users/JourneyL/followers', following_url: 'https://api.github.com/users/JourneyL/following{/other_user}', gists_url: 'https://api.github.com/users/JourneyL/gists{/gist_id}', starred_url: 'https://api.github.com/users/JourneyL/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/JourneyL/subscriptions', organizations_url: 'https://api.github.com/users/JourneyL/orgs', repos_url: 'https://api.github.com/users/JourneyL/repos', events_url: 'https://api.github.com/users/JourneyL/events{/privacy}', received_events_url: 'https://api.github.com/users/JourneyL/received_events', type: 'User', site_admin: false, }, labels: [], state: 'open', locked: false, assignee: null, assignees: [], milestone: null, comments: 3, created_at: '2017-02-27T08:09:35Z', updated_at: '2017-03-04T03:04:43Z', closed_at: null, body: 'i set x,y and appear a box that backgroundColor is black ,how to change the backgroundColor of this box ?', }, comment: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/comments/284122414', html_url: 'https://github.com/879479119/react-native-shadow/issues/5#issuecomment-284122414', issue_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5', id: 284122414, user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, created_at: '2017-03-04T03:04:43Z', updated_at: '2017-03-04T03:04:43Z', body: '没有啊~ RN适用范围还是很有限的,一根动画扯上关系就很卡了,视频播放也不现实只有调用原生的组件。 包刚刚更新到了1.1.1 update一下试试~', }, }, public: true, created_at: '2017-03-04T03:04:43Z', }, { id: '5431724376', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { push_id: 1593008985, size: 2, distinct_size: 2, ref: 'refs/heads/master', head: '24ecc87265f94f5889b0dc31f8a72864b2590169', before: '0f6b6ba85c51a7b9e6653fde663ba65a067d16d7', commits: [ { sha: 'de6d37c3ba012c06ad34bdf6abe6b9f0b8da3844', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':hammer: fix box shadow color', distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/de6d37c3ba012c06ad34bdf6abe6b9f0b8da3844', }, { sha: '24ecc87265f94f5889b0dc31f8a72864b2590169', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: "Merge branch 'master' of github.com:879479119/react-native-shadow", distinct: true, url: 'https://api.github.com/repos/879479119/react-native-shadow/commits/24ecc87265f94f5889b0dc31f8a72864b2590169', }, ], }, public: true, created_at: '2017-03-04T02:50:34Z', }, { id: '5411428807', type: 'IssuesEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69651820, name: 'ddz-mark/News', url: 'https://api.github.com/repos/ddz-mark/News', }, payload: { action: 'closed', issue: { url: 'https://api.github.com/repos/ddz-mark/News/issues/1', repository_url: 'https://api.github.com/repos/ddz-mark/News', labels_url: 'https://api.github.com/repos/ddz-mark/News/issues/1/labels{/name}', comments_url: 'https://api.github.com/repos/ddz-mark/News/issues/1/comments', events_url: 'https://api.github.com/repos/ddz-mark/News/issues/1/events', html_url: 'https://github.com/ddz-mark/News/issues/1', id: 180437013, number: 1, title: "Let's have a MVP trial", user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, labels: [], state: 'closed', locked: false, assignee: null, assignees: [], milestone: null, comments: 0, created_at: '2016-10-01T04:18:51Z', updated_at: '2017-03-01T11:39:05Z', closed_at: '2017-03-01T11:39:05Z', body: '# kekeke, mark before hot\n', }, }, public: true, created_at: '2017-03-01T11:39:05Z', }, { id: '5409304661', type: 'IssueCommentEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 69021740, name: '879479119/react-native-shadow', url: 'https://api.github.com/repos/879479119/react-native-shadow', }, payload: { action: 'created', issue: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5', repository_url: 'https://api.github.com/repos/879479119/react-native-shadow', labels_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5/labels{/name}', comments_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5/comments', events_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5/events', html_url: 'https://github.com/879479119/react-native-shadow/issues/5', id: 210414005, number: 5, title: 'how to change shadow backgroundColor', user: { login: 'JourneyL', id: 18393378, avatar_url: 'https://avatars2.githubusercontent.com/u/18393378?v=3', gravatar_id: '', url: 'https://api.github.com/users/JourneyL', html_url: 'https://github.com/JourneyL', followers_url: 'https://api.github.com/users/JourneyL/followers', following_url: 'https://api.github.com/users/JourneyL/following{/other_user}', gists_url: 'https://api.github.com/users/JourneyL/gists{/gist_id}', starred_url: 'https://api.github.com/users/JourneyL/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/JourneyL/subscriptions', organizations_url: 'https://api.github.com/users/JourneyL/orgs', repos_url: 'https://api.github.com/users/JourneyL/repos', events_url: 'https://api.github.com/users/JourneyL/events{/privacy}', received_events_url: 'https://api.github.com/users/JourneyL/received_events', type: 'User', site_admin: false, }, labels: [], state: 'open', locked: false, assignee: null, assignees: [], milestone: null, comments: 0, created_at: '2017-02-27T08:09:35Z', updated_at: '2017-03-01T03:26:33Z', closed_at: null, body: 'i set x,y and appear a box that backgroundColor is black ,how to change the backgroundColor of this box ?', }, comment: { url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/comments/283234406', html_url: 'https://github.com/879479119/react-native-shadow/issues/5#issuecomment-283234406', issue_url: 'https://api.github.com/repos/879479119/react-native-shadow/issues/5', id: 283234406, user: { login: '879479119', id: 12726506, avatar_url: 'https://avatars2.githubusercontent.com/u/12726506?v=3', gravatar_id: '', url: 'https://api.github.com/users/879479119', html_url: 'https://github.com/879479119', followers_url: 'https://api.github.com/users/879479119/followers', following_url: 'https://api.github.com/users/879479119/following{/other_user}', gists_url: 'https://api.github.com/users/879479119/gists{/gist_id}', starred_url: 'https://api.github.com/users/879479119/starred{/owner}{/repo}', subscriptions_url: 'https://api.github.com/users/879479119/subscriptions', organizations_url: 'https://api.github.com/users/879479119/orgs', repos_url: 'https://api.github.com/users/879479119/repos', events_url: 'https://api.github.com/users/879479119/events{/privacy}', received_events_url: 'https://api.github.com/users/879479119/received_events', type: 'User', site_admin: false, }, created_at: '2017-03-01T03:26:33Z', updated_at: '2017-03-01T03:26:33Z', body: "have you pass an `color` like '#999' to the conponent ? ", }, }, public: true, created_at: '2017-03-01T03:26:33Z', }, { id: '5383841094', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 71330626, name: '879479119/SPA-starter-kit', url: 'https://api.github.com/repos/879479119/SPA-starter-kit', }, payload: { push_id: 1577128464, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: 'ab9dcabc314711509067d0b340c7ea16262d2edb', before: '209b259c15bc5b047051014d3dccb4c9b3d499de', commits: [ { sha: 'ab9dcabc314711509067d0b340c7ea16262d2edb', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: 'dependency updated :smile:', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/ab9dcabc314711509067d0b340c7ea16262d2edb', }, ], }, public: true, created_at: '2017-02-24T08:34:03Z', }, { id: '5368502098', type: 'PushEvent', actor: { id: 12726506, login: '879479119', display_login: '879479119', gravatar_id: '', url: 'https://api.github.com/users/879479119', avatar_url: 'https://avatars.githubusercontent.com/u/12726506?', }, repo: { id: 71330626, name: '879479119/SPA-starter-kit', url: 'https://api.github.com/repos/879479119/SPA-starter-kit', }, payload: { push_id: 1572160915, size: 1, distinct_size: 1, ref: 'refs/heads/master', head: '209b259c15bc5b047051014d3dccb4c9b3d499de', before: 'd44228b9a37f7e30b915a63f56069a67e3a6aceb', commits: [ { sha: '209b259c15bc5b047051014d3dccb4c9b3d499de', author: { email: '<EMAIL>', name: 'RockSAMA', }, message: ':heartbeat: SINGLE PLAYER MODE COMPLETED !!!!!!', distinct: true, url: 'https://api.github.com/repos/879479119/SPA-starter-kit/commits/209b259c15bc5b047051014d3dccb4c9b3d499de', }, ], }, public: true, created_at: '2017-02-22T08:59:42Z', }, ] /* jshint node: true */ "use strict"; var inquirer = require('inquirer'), Graph = require('./Graph.js'), db = require('./db.js'), colors = require('colors'), total = 0, progress = 0; var processResults = function(graphs, callback) { var i = 0, j = 0, k, g, v, orderedNodes; var sortByDepth = function(a, b) { return g.prop(a, "depth") - g.prop(b, "depth"); }; var removeLeaves = function(val) { return g.prop(val, "match"); }; var includeCode = function(err, val) { if (err) { return callback(err); } j++; next(); }; var childCheckDone = function(val) { if (val.children) { g.getDescendents(v).forEach(function(p) { g.prop(p, "include", val.children.indexOf(p) > -1); }); } j++; next(); }; var childCheck = function(val) { var allChildrenIncluded = g.getDescendents(v).reduce(function(prev, cur) { return prev && (g.prop(cur, "include") || g.prop(cur, "include") === false); }, true); if (val.siblings) { //val.siblings is a list of included siblings val.siblings.forEach(function(sibling) { if (!g.hasNode(sibling.code)) { g.addNode(sibling.code, { description: sibling.description, children: [], parent: g.prop(v, "parent"), depth: g.prop(v, "depth") }); } g.prop(sibling.code, "include", true); }); } if (allChildrenIncluded) { j++; next(); } else { var checkboxes = g.getDescendents(v).map(function(val) { return { "value": val, "name": g.prop(val, "description"), "short": val, "checked": g.prop(val, "include") !== false }; }); inquirer.prompt([{ type: "checkbox", name: "children", message: "All child codes will be included (except ones already rejected) unless you deselect them:", choices: checkboxes }], childCheckDone); } }; var rejectCheck = function(val) { //reject parents unless already included g.prop(v, "parent").forEach(function(p) { if (!g.prop(p, "include")) g.prop(p, "include", false); }); //reject children g.getDescendents(v).forEach(function(p) { g.prop(p, "include", val.include.indexOf(p) > -1); }); j++; next(); }; var siblingCheck = function(val) { if (val.include || val.include === false) { //single parent included/excluded g.prop(g.prop(v, "parent")[0], "include", val.include); } else if (val.parents) { //val.parents is a list of included parents g.prop(v, "parent").forEach(function(p) { g.prop(p, "include", val.parents.indexOf(p) > -1); }); } //get siblings db.getSiblings(v, function(err, siblings) { if (err) { return callback(err); } var unmatchedSiblings = Object.keys(siblings).filter(function(val) { return !g.hasNode(val); }); if (unmatchedSiblings && unmatchedSiblings.length > 0) { var checkboxes = unmatchedSiblings.map(function(val) { return { "value": { code: val, description: siblings[val] }, "name": val + ": " + siblings[val].join(" | "), "short": val }; }); inquirer.prompt([{ type: "checkbox", name: "siblings", message: "Select sibling codes to include:", choices: checkboxes }], childCheck); } else { childCheck({ q: "y" }); } }); }; var parentCheck = function(val) { var allParentsIncluded = g.prop(v, "parent").reduce(function(prev, cur) { return prev && (g.prop(cur, "include") || g.prop(cur, "include") === false); }, true); if (val.include === "b") { return back(); } g.prop(v, "include", true); if (val.include==="n") { g.prop(v, "include", false); var allChildrenIncluded = g.getDescendents(v).reduce(function(prev, cur) { return prev && (g.prop(cur, "include") || g.prop(cur, "include") === false); }, true); if (g.prop(v, "children").length > 0 && !allChildrenIncluded) { inquirer.prompt([{ type: "checkbox", name: "include", message: "All children will be rejected unless you select them below", choices: g.getDescendents(v).map(function(val) { return { value: val, name: g.prop(val, "description"), short: val }; }) }], rejectCheck); } else { rejectCheck({ include: [] }); } } else if (allParentsIncluded) { childCheck({ q: "y" }); } else { if (g.prop(v, "parent").length === 1) { inquirer.prompt([{ type: "confirm", name: "include", message: "Include parent code " + g.prop(v, "parent")[0] + "?", default: "y" }], siblingCheck); } else { var checkboxes = g.prop(v, "parent").filter(function(val) { return !g.prop(val, "include"); }).map(function(val) { return { "value": val, "name": g.prop(val, "description").join(" | "), "short": val }; }); inquirer.prompt([{ type: "checkbox", name: "parents", message: "Select parent codes to include:", choices: checkboxes }], siblingCheck); } } }; //Go back to previous code var back = function() { if (j === 0) { if (i === 0) { progress--; next(); } else { i--; g = graphs[i]; orderedNodes = g.nodes().sort(sortByDepth).filter(removeLeaves); j = orderedNodes.length - 1; g.propDelete(orderedNodes[j], "include"); progress-=2; next(); } } else { j--; g.propDelete(orderedNodes[j], "include"); progress-=2; next(); } }; //Process the next code. var next = function() { if (i > graphs.length - 1) { //all done return callback(null, graphs); } if (orderedNodes && j > orderedNodes.length - 1) { //This subgraph is complete... move to the next j = 0; i++; next(); } else { progress++; if (j === 0) { //Load next graph g = graphs[i]; orderedNodes = g.nodes().sort(sortByDepth).filter(removeLeaves); } v = orderedNodes[j]; var status, progressText; console.log(""); console.log(""); for (k = 0; k < g.prop(v, "parent").length; k++) { status = ""; if (g.prop(g.prop(v, "parent")[k], "include")) status = " INCLUDED".cyan; if (g.prop(g.prop(v, "parent")[k], "include") === false) status = " REJECTED".red; console.log("PARENT: ".yellow + g.prop(v, "parent")[k] + "-" + g.prop(g.prop(v, "parent")[k], "description").join(" | ").yellow + status); } console.log("|".white); status = g.prop(v, "include") ? " INCLUDED".cyan : ""; if (g.prop(v, "include") === false) status = " REJECTED".red; progressText = " (code " + (progress + "").yellow + " of " + (total + "").green + ") "; console.log("+--".white + " CODE: ".green + v + "-" + g.prop(v, "description").join(" | ").green + progressText + status); g.displayChildrenInTree(v); console.log(""); if (!g.prop(v, "include") && g.prop(v, "include") !== false) { inquirer.prompt([{ type: "input", name: "include", message: "Include " + v + "? [y]es,[n]o,[b]ack", default: "y", validate: function(input) { var validAnswers = ["y", "n", "b"]; if (validAnswers.indexOf(input) > -1) return true; else return "Please enter one of " + validAnswers.join("/"); } }], parentCheck); } else { parentCheck({ "include": g.prop(v, "include") ? "y" : "n" }); } } }; graphs.forEach(function(v) { g = v; total += g.nodes().filter(removeLeaves).length; }); next(); }; var validateResults = function(graph, synonyms, callback) { // Show // Items rejected despite presence of a synonyms var currentNode; var notInDescription = function(synonym) { return graph.prop(currentNode, "description").join("|").toLowerCase().search(new RegExp(synonym.toLowerCase().replace("*", "").replace(" ", ".*"), 'g')) > -1; }; var nodeButNoSynonym = function(node) { currentNode = node; return graph.prop(node, "include") && synonyms.filter(notInDescription).length === 0; }; // Parent/children included but no synonym var vs = graph.nodes().filter(nodeButNoSynonym); vs.forEach(function(v) { console.log(v, graph.prop(v, "description").join(" | ")); }); var updateResults = function(v) { if (v.synonym === "") { vs = graph.nodes().filter(nodeButNoSynonym); vs.forEach(function(v) { graph.prop(v, "include", false); }); } else { synonyms.push(v.synonym); } vs = graph.nodes().filter(nodeButNoSynonym); vs.forEach(function(v) { console.log(v, graph.prop(v, "description").join(" | ")); }); if (vs.length > 0) { console.log("The following are currently matched but not by synonym."); console.log(""); inquirer.prompt([{ name: "synonym", message: "Please add a synonym to match some of the above - or hit enter to reject these" }], updateResults); } else { callback(); } }; if (vs.length > 0) { console.log("The following are currently matched but not by synonym."); console.log(""); inquirer.prompt([{ name: "synonym", message: "Please add a synonym to match some of the above - or hit enter to reject these" }], updateResults); } else { callback(); } }; var resultsAndProcess = function(meta, callback) { db.getFromSynonyms(meta, 'dictionary.sqlite', function(err, graphs) { if (err) { return callback(err); } processResults(graphs, function(err, graphs) { if (err) { return callback(err); } var i = 0; var doNext = function() { if (i >= graphs.length) return callback(null, graphs); validateResults(graphs[i], meta.synonyms, function() { i++; doNext(); }); }; doNext(); }); }); }; module.exports = { resultsAndProcess: resultsAndProcess }; /** * @format */ import {AppRegistry} from 'react-native'; import App from './App'; import {name as appName} from './app.json'; import messaging from '@react-native-firebase/messaging'; import PushNotification from 'react-native-push-notification'; // Register background handler messaging().setBackgroundMessageHandler(async (remoteMessage) => { console.log('Message handled in the background!', remoteMessage); }); PushNotification.getChannels(function (channel_ids) { console.log(channel_ids); // ['channel_id_1'] }); PushNotification.createChannel( { channelId: 'channel_id_1', // (required) channelName: 'My channel', // (required) soundName: 'default', // (optional) See `soundName` parameter of `localNotification` function importance: 4, // (optional) default: 4. Int value of the Android notification importance vibrate: true, // (optional) default: true. Creates the default vibration patten if true. }, (created) => console.log(`createChannel returned '${created}'`), // (optional) callback returns whether the channel was created, false means it already existed. ); PushNotification.configure({ onRegister: function (token) { console.log('TOKEN:', token); }, onNotification: function (notification) { console.log('NOTIFICATION:', notification); // process the notification }, popInitialNotification: true, requestPermissions: true, }); AppRegistry.registerComponent(appName, () => App); const createLicensee = require('../creates/CreateLicensee'); const searchLicensee = require('../searches/FindLicensee'); const constants = require('../config/Constants'); module.exports = { key: searchLicensee.key, display: { // the label goes up in sidebar label: constants.search_or_creates.SEARCH_OR_CREATE_LICENSEE_LABEL, description: constants.search_or_creates.SEARCH_OR_CREATE_LICENSEE_DESCRIPTION, }, search: searchLicensee.key, create: createLicensee.key, }; <reponame>emman24/landingpage<filename>src/components/search.js import { Link } from "gatsby" import PropTypes from "prop-types" import React from "react" const Search = ({ siteTitle }) => ( <div className="is-fullwidth header-background" style={{height:'80vh', textAlign:'center'}} > <div className="container-fluid" style={{top:'35%'}}> <div className="row"> <div className="twelve columns"> <div> <h1 style={{color:'#fff'}}>SEARCH</h1> <input type="text" style={{width: '60%', padding:'30px'}} placeholder="Search" /> </div> </div> </div> </div> </div> ) Search.propTypes = { siteTitle: PropTypes.string, } Search.defaultProps = { siteTitle: ``, } export default Search<gh_stars>0 var searchData= [ ['b_0',['b',['../struct_b_l_a_k_e2_b___c_t_x.html#a5e41b09a2d5a8e3e05970f2bd6c64a06',1,'BLAKE2B_CTX::b()'],['../struct_s_h_a3___k_e_c_c_a_k___c_t_x.html#affd13b52f63b0f71abcf69c29acc5f9d',1,'SHA3_KECCAK_CTX::b()']]], ['bitlen_1',['bitlen',['../struct_m_d5___c_t_x.html#a0d98945b478e7ae383387caf768802c4',1,'MD5_CTX::bitlen()'],['../struct_s_h_a1___c_t_x.html#a0d98945b478e7ae383387caf768802c4',1,'SHA1_CTX::bitlen()'],['../struct_s_h_a256___c_t_x.html#a0d98945b478e7ae383387caf768802c4',1,'SHA256_CTX::bitlen()']]] ]; <filename>index.js module.exports = { generate: require('./src/gen.js'), plain: require('./src/plain.js') } module.exports = [ { id: "organizer", title: "Demo", icon: "human-greeting", menus: [ { qid: 1, id: "todo", text: "To-Do List", icon: "todo.gif" }, { qid: 2, id: "contact", text: "Address Book", icon: "contact.gif" }, { qid: 4, id: "restaurant", text: "Restaurants", icon: "resto.gif" }, { qid: 3, id: "comics", text: "Graphic novels", icon: "comics.png", defaultViewMany: "cards", }, { qid: 5, id: "winecellar", text: "Wine Cellar", icon: "wine-bottle.png", defaultViewMany: "cards", }, { qid: 6, id: "winetasting", text: "Wine Tasting", icon: "wine.gif" }, ], }, { id: "music", title: "Music", icon: "music", menus: [ { qid: 8, id: "artist", text: "Artists", icon: "star.png", defaultViewMany: "cards", }, { qid: 7, id: "album", text: "Albums", icon: "cd.png", defaultViewMany: "cards", }, { qid: 9, id: "track", text: "Tracks", icon: "music.png" }, ], } /* { id: 'test', title: 'Test', icon: 'water', menus: [ {id: 'test', text: 'Tests', defaultViewMany: 'cards'}, ], }, */, /* { id: 'designer', title: 'Designer', icon: 'cogs', menus: [ {id: 'world', text: 'Apps', icon: 'designer/world.png'}, {id: 'object', text: 'Objects', icon: 'designer/object.png'}, {id: 'field', text: 'Fields', icon: 'designer/field.png'}, {id: 'group', text: 'Field Groups', icon: "designer/group.png"}, {id: 'collection', text: 'Collections', icon: "designer/collection.png"}, //{id: 'test', text: 'Test', icon: "car.png", defaultViewMany: 'cards'}, ], }, */ ]; const Discord = require('discord.js'); exports.run = async (client, message, settings) => { let config = client.config let functions = client.functions let checkMessages = settings.checkMessages if (checkMessages) checkMessages = false else checkMessages = true await functions.updateGuild(message.guild.id, {checkMessages: checkMessages}, client) if (checkMessages) message.channel.send(`${config.emoji.on} Automatic fact checking enabled`) else message.channel.send(`${config.emoji.off} Automatic fact checking disabled`) } exports.help = { name: "toggle", usage: "toggle", aliases: [], description: "Toggle automatic fact checking", permissions: "perms", category: "info" }function calc(op){ var result = document.getElementById("result"); var operacao = op.value; a = parseInt(document.getElementById("input-1").value); b = parseInt(document.getElementById("input-2").value); var calculo = eval(a+operacao+b); result.innerHTML = "<p>"+calculo+"</p>"; } <reponame>Groestlcoin/shocknet-wallet<filename>app/screens/Advanced/Modals/InfoChannel.js import React from 'react' import { View, StyleSheet, Text, ActivityIndicator } from 'react-native' import Modal from 'react-native-modalbox' import Logger from 'react-native-file-log' import Ionicons from 'react-native-vector-icons/Ionicons' import Head from '../../../components/PopupModal/Head' import Body from '../../../components/PopupModal/Body' import Footer from '../../../components/PopupModal/Footer' import { Colors } from '../../../res/css' import { getChaninfo } from '../../../services/wallet' /** * @typedef {import('../../../services/wallet').Channel} Channel * @typedef {import('../../../services/wallet').ChanInfo} ChanInfo * @typedef {import('../../../services/wallet').RoutingPolicy} RoutingPolicy */ /** * @typedef {object} Props * @prop {React.RefObject<any>} modalRef * @prop {(key: keyof import("../index").State) => (value: any) => void} onChange * @prop {() => void} submit * @prop {() => void} closeChannel * @prop {boolean} keyboardOpen * @prop {number} keyboardHeight * @prop {boolean} loading * @prop {string} error * @prop {Channel} channel */ /** * @typedef {object} State * @prop {ChanInfo} chanInfo * @prop {boolean} chanInfoReady * @prop {RoutingPolicy} myPolicy * @prop {RoutingPolicy} otherPolicy */ /** * @type {RoutingPolicy} defaultPolicy */ const defaultPolicy = { disabled: false, fee_base_msat: 0, fee_rate_milli_msat: 0, last_update: 0, min_htlc: 0, time_lock_delta: 0, } /** * @augments React.Component<Props, State, never> */ class InfoChannelModal extends React.Component { /** @type {State} */ state = { chanInfoReady: false, chanInfo: { capacity: 0, chan_point: '', channel_id: 0, last_update: 0, node1_policy: defaultPolicy, node1_pub: '', node2_policy: defaultPolicy, node2_pub: '', }, myPolicy: defaultPolicy, otherPolicy: defaultPolicy, } /** * @param {Props} prevProps */ componentDidUpdate(prevProps) { if (this.props.channel !== prevProps.channel) { const { channel } = this.props getChaninfo(channel.chan_id) .then(res => { if (channel.remote_pubkey === res.node1_pub) { this.setState({ chanInfo: res, chanInfoReady: true, otherPolicy: res.node1_policy, myPolicy: res.node2_policy, }) } else { this.setState({ chanInfo: res, chanInfoReady: true, myPolicy: res.node1_policy, otherPolicy: res.node2_policy, }) } }) .catch(e => { Logger.log(e) }) } } render() { const { modalRef, submit, closeChannel, keyboardHeight = 0, keyboardOpen, loading, error, channel, } = this.props const { chanInfo, chanInfoReady, myPolicy, otherPolicy } = this.state return ( <Modal position="center" style={[ styles.modal, keyboardOpen ? { marginTop: -1 * (keyboardHeight / 2), } : null, ]} ref={modalRef} backButtonClose useNativeDriver > {loading ? ( <View style={styles.modalLoading}> <ActivityIndicator color="white" size="large" /> </View> ) : null} <Head closeModal={modalRef.current ? modalRef.current.close : undefined} > {/* <Icon name="ios-link" color="white" size={35} /> */} <Text style={styles.modalTitle}>{channel.chan_id}</Text> </Head> <Body> {/*<Text style={styles.modalTitle}>Close Channel?</Text>*/} {error ? <Text style={styles.modalError}>{error}</Text> : null} {chanInfoReady && ( <> <View style={styles.content}> <Text>Capacity:</Text> <Text style={styles.bold}>{chanInfo.capacity}</Text> </View> <View style={styles.hr} /> <Text>My Policy</Text> <View style={styles.content}> <Text>Disabled:</Text> <Text style={styles.bold}> {myPolicy.disabled ? 'true' : 'false'} </Text> </View> <View style={styles.content}> <Text>Fee base msat:</Text> <Text style={styles.bold}>{myPolicy.fee_base_msat}</Text> </View> <View style={styles.content}> <Text>Fee rate milli mstat:</Text> <Text style={styles.bold}>{myPolicy.fee_rate_milli_msat}</Text> </View> <View style={styles.content}> <Text>Last update:</Text> <Text style={styles.bold}> {new Date(myPolicy.last_update * 1000).toISOString()} </Text> </View> <View style={styles.hr} /> <Text>Other node Policy</Text> <View style={styles.content}> <Text>Disabled:</Text> <Text style={styles.bold}> {otherPolicy.disabled ? 'true' : 'false'} </Text> </View> <View style={styles.content}> <Text>Fee base msat:</Text> <Text style={styles.bold}>{otherPolicy.fee_base_msat}</Text> </View> <View style={styles.content}> <Text>Fee rate milli mstat:</Text> <Text style={styles.bold}> {otherPolicy.fee_rate_milli_msat} </Text> </View> <View style={styles.content}> <Text>Last update:</Text> <Text style={styles.bold}> {new Date(otherPolicy.last_update * 1000).toISOString()} </Text> </View> <View style={styles.hr} /> <View style={styles.content}> <Text>Close channel</Text> <Ionicons name="ios-close-circle-outline" color="#222" size={22} onPress={closeChannel} /> </View> </> )} </Body> <Footer value="OK" onPress={submit} /> </Modal> ) } } export default InfoChannelModal const styles = StyleSheet.create({ hr: { height: 1, backgroundColor: '#222', width: '80%', }, modal: { justifyContent: 'space-between', alignItems: 'center', elevation: 10, zIndex: 100, height: 400, width: '80%', borderRadius: 15, }, modalLoading: { position: 'absolute', width: '100%', height: '100%', backgroundColor: Colors.LOADING_BACKDROP, alignItems: 'center', justifyContent: 'center', zIndex: 1000, }, modalTitle: { fontFamily: 'Montserrat-800', color: Colors.TEXT_GRAY, textAlign: 'center', width: '100%', fontSize: 16, }, modalError: { textAlign: 'center', paddingVertical: 10, paddingHorizontal: 15, marginBottom: 15, backgroundColor: Colors.ICON_RED, color: Colors.TEXT_WHITE, fontFamily: 'Montserrat-700', width: '90%', borderRadius: 15, fontSize: 11, }, content: { width: '80%', display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }, bold: { fontWeight: 'bold', }, }) <filename>test.js const test = require('tape') const raf = require('random-access-file') const rah = require('random-access-http') const ram = require('random-access-memory') const fs = require('fs') const { createServer } = require('./server') test('basic', (t) => { const server = createServer({ storage(pathname) { return raf(__filename) } }) server.listen(0, () => { const { port } = server.address() const file = rah(`http://localhost:${port}`) file.open((err) => { t.error(err) file.read(0, file.length, (err, buffer) => { const expected = fs.readFileSync(__filename) t.error(err) t.ok(0 === Buffer.compare(buffer, expected)) file.read(4, 8, (err, buffer) => { const expected = fs.readFileSync(__filename).slice(4, 12) t.error(err) t.ok(0 === Buffer.compare(buffer, expected)) t.end() server.close() }) }) }) }) }) test('basic in memory', (t) => { const server = createServer({ storage() { return ram(Buffer.from('hello')) } }) server.listen(0, () => { const { port } = server.address() const hello = rah(`http://localhost:${port}`) hello.open((err) => { t.error(err) hello.read(0, hello.length, (err, buffer) => { const expected = Buffer.from('hello') t.error(err) t.ok(0 === Buffer.compare(buffer, expected)) t.end() server.close() }) }) }) }) test('basic http proxy', (t) => { const server = createServer({ storage() { return ram(Buffer.from('hello')) } }) const proxy = createServer({ storage(pathname) { const { port } = server.address() return rah(`http://localhost:${port}${pathname}`) } }) server.listen(0, () => { proxy.listen(0, () => { const { port } = proxy.address() const hello = rah(`http://localhost:${port}`) hello.open((err) => { t.error(err) hello.read(0, hello.length, (err, buffer) => { const expected = Buffer.from('hello') t.error(err) t.ok(0 === Buffer.compare(buffer, expected)) t.end() server.close() proxy.close() }) }) }) }) }) const { query } = require("express"); const { GoogleSpreadsheet } = require("google-spreadsheet"); const propluginKey = require("../../proplugin-eb842ee31da8.json"); //const {getCategoryProductSlide} = require('./src/db/hubquery') const {getUser} = require('../db/user.query'); exports.usercontroller = async () => { // Initialize the sheet - doc ID is the long id in the sheets URL const doc = new GoogleSpreadsheet( "1v1raNRlYWGzMgKEzrbstwHcPvYnF2otJPXcUmU4nSFM", ); let User =await getUser(); console.log(User); // Initialize Auth - see more available options at https://theoephraim.github.io/node-google-spreadsheet/#/getting-started/authentication await doc.useServiceAccountAuth({ client_email: propluginKey.client_email, private_key: propluginKey.private_key, }); await doc.loadInfo(); // loads document properties and worksheets console.log(doc.title); await doc.updateProperties({ title: "user renamed doc" }); const sheet = doc.sheetsByIndex[0]; const rows = await sheet.getRows(); const larryRow = await sheet.addRow({ email: "", _website: "", _store:"", website_id:"", store_id:"", created_in:"", prefix:"", firstname:"", middlename:"", lastname:"", suffix:"", group_id:"", dob:"", password_hash:"", rp_token:"", rp_token_created_at:"", taxvat:"", confirmation:"", created_at:"", gender:"", disable_auto_group_change:"", updated_at:"", failures_num:"", first_failure:"", lock_expires:"", password:"" }); console.log("larryRow => ", larryRow); let i = 0; while (true) { if (i >= rows) break; // console.log(rows[i].email); // data.push(rows[i].email); User = User.filter((item) => item != rows[i].email); i += 1; } console.log(User); }; // const CheckEmail = (rows, count, data, index) => { // data.push(rows[index].email); // console.log("rows[index].email ", rows[index].email); // if (index < count) { // index += 1; // CheckEmail(rows, count, data, index); // } else { // return data; // } // }; exports.addresscontroller = async () => { // Initialize the sheet - doc ID is the long id in the sheets URL const doc = new GoogleSpreadsheet( "1698_dmQElYK8g0cYatJ_jh5DFUko5mRZonTcTNo2vAo" ); // Initialize Auth - see more available options at https://theoephraim.github.io/node-google-spreadsheet/#/getting-started/authentication await doc.useServiceAccountAuth({ client_email: propluginKey.client_email, private_key: propluginKey.private_key, }); await doc.loadInfo(); // loads document properties and worksheets console.log(doc.title); await doc.updateProperties({ title: " renamed add doc" }); const sheet = doc.sheetsByIndex[0]; const larryRow = await sheet.addRow({ _website:"", _email:"", _entity_id:"", prefix:"", firstname:"", middlename:"", lastname:"", suffix:"", company:"", street:"", city:"", country_id:"", region:"", region_id:"", postcode:"", telephone:"", fax:"", vat_id:"", vat_is_valid:"", vat_request_id:"", vat_request_date:"", vat_request_success:"", _address_default_billing_:"", _address_default_shipping_:"" }); console.log("larryRow => ", larryRow); }; // const user = [] // const data = doc; // const results = data.filter((doc, query)=> { // for(let i=0; i<doc.lenght; i++){ // if(doc.email != query.email ){ // user(doc.id[i]); // } // } // console.log(results); // });import { Vector3, Color, Mesh, Group, OrthographicCamera, ShaderMaterial, IcosahedronGeometry } from 'three'; import noiseDisp from '../Shaders/noise-displacement.vert'; import basicuvvies from '../Shaders/noise-view-uv.frag'; export default class MorphingSphere { constructor({scene, onLoad}) { const clearColor = new Color(); clearColor.setHSL(0.62, 0.9, 0.2); scene.renderer.setClearColor(clearColor); const frustumSize = 10; const aspect = scene.camera.aspect; scene.camera = new OrthographicCamera( frustumSize * aspect / - 2, frustumSize * aspect / 2, frustumSize / 2, frustumSize / - 2, 1, 150 ); scene.camera.position.copy(new Vector3(0, 50, 50)); scene.camera.lookAt(new Vector3(0, 0, 0)); this.root = new Group(); this.material = new ShaderMaterial( { uniforms: { time: { type: "f", value: 0.0 } }, vertexShader: noiseDisp, fragmentShader: basicuvvies }); const mesh = new Mesh( new IcosahedronGeometry( 3, 5 ), this.material ); this.root.add( mesh ); this.inspiredBy = document.createElement('div'); this.inspiredBy.innerHTML = 'Edit from: https://www.clicktorelease.com/blog/vertex-displacement-noise-3d-webgl-glsl-three-js.html'; this.inspiredBy.style.position = 'absolute'; this.inspiredBy.style.bottom = 3; this.inspiredBy.style.right = 3; this.inspiredBy.style.color = 'darkcyan'; document.body.appendChild(this.inspiredBy); if (onLoad) onLoad(); } update(timeElapsed) { this.root.rotateY(0.0001); this.root.rotateX(0.0006); this.material.uniforms[ 'time' ].value = timeElapsed * 0.1; } onRemove() { document.body.removeChild(this.inspiredBy); } } <filename>src/Ml.Cli.WebApp/ClientApp/src/Local/Comparison/StatsTable.js import React, {useState} from "react"; import {normalizeKeys, totalScores} from "./score"; import {filterItems} from './TableResult'; import ExcelExport from "./ExcelExport"; import {CheckboxInput, CheckboxModes} from "@axa-fr/react-toolkit-form-input-checkbox"; import Help from "@axa-fr/react-toolkit-help"; export const computeTotalTimeMs = items => { const timeLeft = items.reduce((accumulator, currentItem) => accumulator + currentItem.left.TimeMs, 0); const timeRight = items.reduce((accumulator, currentItem) => accumulator + currentItem.right.TimeMs, 0); return {rightTimeMs: timeRight, leftTimeMs: timeLeft}; }; export const orderByStatusCode = items => { const statusCodes = {}; items.forEach(item => setStatusCodesList(statusCodes, item)); return statusCodes; }; const setStatusCodesList = (statusCodes, item) => { if(!item.right.StatusCode || !item.left.StatusCode){ return; } if(!statusCodes[item.right.StatusCode.toString()]){ statusCodes[item.right.StatusCode.toString()] = { right: 1, left:0 }; } else{ statusCodes[item.right.StatusCode.toString()].right ++; } if(!statusCodes[item.left.StatusCode.toString()]){ statusCodes[item.left.StatusCode.toString()] = { right: 0, left:1 }; } else{ statusCodes[item.left.StatusCode.toString()].left ++; } } const calcSideTotalCompleteness = (side, levenshteinResults, numberItems) => { const totalValues = []; for(const key of Object.keys(levenshteinResults)){ const tempObject = levenshteinResults[key]; if(!(tempObject[side].ok === tempObject[side].ko && tempObject[side].ok === 0)){ const tempValueByKey = tempObject[side].ok * 100 / numberItems; totalValues.push(tempValueByKey); } } const reduced = totalValues.reduce((a, b) => a + b, 0); return (reduced / totalValues.length).toFixed(2); }; export const calcTotalCompleteness = (levenshteinResults, numberItems) => { const totalLeftCompleteness = calcSideTotalCompleteness("completeness_left", levenshteinResults, numberItems); const totalRightCompleteness = calcSideTotalCompleteness("completeness_right", levenshteinResults, numberItems); return {left: totalLeftCompleteness, right: totalRightCompleteness}; }; const StatusCode = ({statusCodes}) => { const statuses = Object.keys(statusCodes).map(function(key) { const value = statusCodes[key]; return <div className="stats__results" key={key}> <div className="stats__results-info stats__results-info--separator"> <span>Status Code : {key} </span></div> <div className="stats__results-info stats__results-info--separator"> <span>Number on the left : {value.left} </span></div> <div className="stats__results-info"> <span>Number on the right : {value.right} </span></div> </div> }); return <>{statuses}</> } const Scores = ({levenshteinResults}) => { let keys = Object.keys(levenshteinResults); const ScoreItems = keys.map(function(key) { const keyValue = levenshteinResults[key]; return <div className="stats__results" key={key}> <div className="stats__results-info stats__results-info--separator"> <span>Key : {key} </span></div> <div className="stats__results-info stats__results-info--separator"> <ul> <li>Levenshtein score : {keyValue.score} </li> <li>Number OK : {keyValue.score_ok} </li> <li>Number KO : {keyValue.score_ko} </li> <li>Number Total : {keyValue.total} </li> <li>Percentage OK : {keyValue.percentages.ok}</li> </ul> </div> <div className="stats__results-info"> <span>Completeness OK Left : {keyValue.completeness_left.ok}</span> <br /> <span>Completeness KO Left : {keyValue.completeness_left.ko}</span> <br /> <span>Completeness OK Right : {keyValue.completeness_right.ok}</span> <br /> <span>Completeness KO Right : {keyValue.completeness_right.ko}</span> <br /> <span>Percentage completeness OK Left : {keyValue.percentages.completeness_ok_left}</span> <br /> <span>Percentage completeness OK Right : {keyValue.percentages.completeness_ok_right}</span> </div> </div> }); return <>{ScoreItems}</> } const statsErrorsOptions = [ { key:"checkbox_areErrorsCounted", id:"are_errors_counted_checkbox", value:"errorsValue", label:"Are errors counted ?", disabled: false } ]; const statsMergeOptions = [ { key:"checkbox_isMerging", id:"is_merging_checkbox", value:"mergeValue", label:"Is merge activated ?", disabled: false } ]; const StatsTable = ({state, setState, items}) => { const [statsState, setStatsState] = useState({ areErrorsRemoved: false, isMerging: true }); const filteredItems = statsState.areErrorsRemoved ? items.filter(item => item.left.StatusCode === 200 && item.right.StatusCode === 200) : items; let levenshteinResults = totalScores(filteredItems, ["document_id", "document_type"]); if(statsState.isMerging){ levenshteinResults = normalizeKeys(levenshteinResults, Object.keys(levenshteinResults)); } const totalTimeMs = computeTotalTimeMs(filteredItems); const statusCodes = orderByStatusCode(filteredItems); const totalCompleteness = calcTotalCompleteness(levenshteinResults, filteredItems.length); const fileInfo = { ok: filterItems(filteredItems, "OK").length, ko: filterItems(filteredItems, "KO").length, total: filteredItems.length }; return( <> <div className="stats" key="StatsTableKey"> <div className="stats__title"> <span>Stats:</span> <div className="table-result__collapse-button" onClick={() => {setState({...state, isStatsTableShowed: !state.isStatsTableShowed})}}>{state.isStatsTableShowed ? "-" : "+"}</div> </div> {state.isStatsTableShowed && ( <> <div className="stats__results stats__results--header"> <CheckboxInput id="are_errors_counted_checkbox" name="areErrorsCountedCheckbox" mode={CheckboxModes.toggle} isChecked={statsState.areErrorsRemoved} label="Remove errors from stats:" onChange={() => setStatsState({...statsState, areErrorsRemoved: !statsState.areErrorsRemoved})} options={statsErrorsOptions} /> <CheckboxInput id="merge" name="merge" mode={CheckboxModes.toggle} isChecked={statsState.isMerging} label="Merge keys" onChange={() => setStatsState({...statsState, isMerging: !statsState.isMerging})} options={statsMergeOptions} /> <ExcelExport fileInfo={fileInfo} statusCodes={statusCodes} levenshteinResults={levenshteinResults} totalCompleteness={totalCompleteness} timeMS={totalTimeMs} /> </div> <div className="stats__results"> <div className="stats__results-info stats__results-info--separator"> <span>OK Files: {filterItems(filteredItems, "OK").length}</span></div> <div className="stats__results-info stats__results-info--separator"> <span>KO Files: {filterItems(filteredItems, "KO").length}</span></div> <div className="stats__results-info"><span>Total : {filteredItems.length}</span></div> </div> <div className="stats__results"> <div className="stats__results-info stats__results-info--double-columns stats__results-info--separator"> <Help placement="right" children="Number of files containing all the keys (non null and not empty)" mode="hover" /> <span>Completeness left : {totalCompleteness.left}%</span> </div> <div className="stats__results-info stats__results-info--double-columns"> <span>Completeness right : {totalCompleteness.right}%</span> </div> </div> <div className="stats__results"> <div className="stats__results-info stats__results-info--separator"> <span>Total time left : {totalTimeMs.leftTimeMs / 1000} seconds</span></div> <div className="stats__results-info stats__results-info--separator"> <span>Total time right : {totalTimeMs.rightTimeMs / 1000} seconds</span></div> <div className="stats__results-info"><span>Difference : {(totalTimeMs.rightTimeMs - totalTimeMs.leftTimeMs) / 1000} seconds (+{Math.round((totalTimeMs.leftTimeMs / totalTimeMs.rightTimeMs) *100)}% gain)</span></div> </div> <div className="stats__results"> <div className="stats__results-info stats__results-info--separator"> <span>Average time left : {(totalTimeMs.leftTimeMs / filteredItems.length) / 1000} seconds</span></div> <div className="stats__results-info stats__results-info--separator"> <span>Average time right : {(totalTimeMs.rightTimeMs / filteredItems.length) / 1000} seconds</span></div> <div className="stats__results-info"><span>Difference : {((totalTimeMs.rightTimeMs - totalTimeMs.leftTimeMs) / filteredItems.length) / 1000} seconds (+{Math.round((totalTimeMs.leftTimeMs / totalTimeMs.rightTimeMs) * 100)}% gain)</span></div> </div> <StatusCode statusCodes={statusCodes} /> <Scores levenshteinResults={levenshteinResults} /> </> )} </div> </> ) } export default StatsTable;var searchData= [ ['winner',['winner',['../class_tick_tack_toe_1_1_game.html#ac64246842fe1f18c3038c5cb33d07ddd',1,'TickTackToe::Game']]] ]; <filename>lib/logChecker.js<gh_stars>0 var events = require('events'), request = require('request'), sugar = require('sugar'), moment = require('moment'); function LogChecker(options) { this.options = options; this.time = options.time; this.events = []; var that; events.EventEmitter.call(this); this.makeRequest = function (callback) { request({ uri: "http://" + that.options.ip + "/get_log.cgi?", method: "GET", qs: { user: that.options.user, pwd: <PASSWORD>.options.<PASSWORD> } }, function (error, response, body) { if (!error && response.statusCode == 200) { callback(body) } }); } this.init = function () { that = this; console.log("Log updater started..."); that.makeRequest(function (body) { var logs = body.remove("var log_text='").remove("';").split("\\n").compact(true); logs = logs.filter(a => a.includes("motion detect")); that.events = logs }); //Start interval setInterval(that.run, that.time); }; this.run = function () { that.makeRequest(function (body) { var logs = body.remove("var log_text='").remove("';").split("\\n").compact(true); logs = logs.filter(a => a.includes("motion detect")); var current = logs.last(); var last_motion = that.events.last(); if (current !== last_motion) { that.emit('motion', { time: null, timeStamp: null }); that.events = logs; console.log("Motion detected! emitting event"); } }); }; } LogChecker.prototype.__proto__ = events.EventEmitter.prototype; exports.LogChecker = LogChecker; <reponame>kosaki08/frontend-sandbox import { INCREMENT, DECREMENT, RESET } from "../actions/actionTypes" const initialState = { value: 0 } function counterReducer(state = initialState, action) { switch (action.type) { case INCREMENT: return { value: state.value + 1 } case DECREMENT: return { value: state.value - 1 } case RESET: return { value: 0 } default: return state } } export default counterReducer <reponame>SlayterDev/natural /* Copyright (c) 2012, <NAME> 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. */ var NounInflector = require('../lib/natural/inflectors/fr/noun_inflector'), inflector = new NounInflector(); describe('NounInflector', function() { describe('.pluralize()', function() { it('should pluralize exception nouns ending by -al', function() { expect(inflector.pluralize('carnaval')).toBe('carnavals'); expect(inflector.pluralize('narval')).toBe('narvals'); expect(inflector.pluralize('récital')).toBe('récitals'); }); it('should pluralize regular nouns ending by -al', function() { expect(inflector.pluralize('amiral')).toBe('amiraux'); expect(inflector.pluralize('cheval')).toBe('chevaux'); expect(inflector.pluralize('général')).toBe('généraux'); }); it('should pluralize exception nouns ending by -ail', function() { expect(inflector.pluralize('bail')).toBe('baux'); expect(inflector.pluralize('vitrail')).toBe('vitraux'); expect(inflector.pluralize('émail')).toBe('émaux'); }); it('should pluralize regular nouns ending by -ail', function() { expect(inflector.pluralize('détail')).toBe('détails'); expect(inflector.pluralize('poitrail')).toBe('poitrails'); expect(inflector.pluralize('chandail')).toBe('chandails'); }); it('should pluralize exception nouns ending by -il', function() { expect(inflector.pluralize('ciel')).toBe('cieux'); expect(inflector.pluralize('œil')).toBe('yeux'); }); it('should pluralize exception nouns ending by -ou', function() { expect(inflector.pluralize('bijou')).toBe('bijoux'); expect(inflector.pluralize('joujou')).toBe('joujoux'); expect(inflector.pluralize('hibou')).toBe('hiboux'); }); it('should pluralize regular nouns ending by -ou', function() { expect(inflector.pluralize('trou')).toBe('trous'); expect(inflector.pluralize('bambou')).toBe('bambous'); expect(inflector.pluralize('toutou')).toBe('toutous'); }); it('should pluralize exception nouns ending by -au', function() { expect(inflector.pluralize('berimbau')).toBe('berimbaus'); expect(inflector.pluralize('landau')).toBe('landaus'); expect(inflector.pluralize('pilau')).toBe('pilaus'); }); it('should pluralize regular nouns ending by -au', function() { expect(inflector.pluralize('cadeau')).toBe('cadeaux'); expect(inflector.pluralize('beau')).toBe('beaux'); expect(inflector.pluralize('étau')).toBe('étaux'); }); it('should pluralize exception nouns ending by -eu', function() { expect(inflector.pluralize('bleu')).toBe('bleus'); expect(inflector.pluralize('émeu')).toBe('émeus'); expect(inflector.pluralize('pneu')).toBe('pneus'); }); it('should pluralize regular nouns ending by -eu', function() { expect(inflector.pluralize('pieu')).toBe('pieux'); expect(inflector.pluralize('lieu')).toBe('lieux'); expect(inflector.pluralize('feu')).toBe('feux'); }); it('should pluralize regular nouns ending by -eau', function() { expect(inflector.pluralize('eau')).toBe('eaux'); expect(inflector.pluralize('manteau')).toBe('manteaux'); expect(inflector.pluralize('arbrisseau')).toBe('arbrisseaux'); }); it('should pluralize regular nouns ending by -œu', function() { expect(inflector.pluralize('vœu')).toBe('vœux'); }); it('should pluralize regular nouns ending by -s, -x or -z', function() { expect(inflector.pluralize('os')).toBe('os'); expect(inflector.pluralize('cas')).toBe('cas'); expect(inflector.pluralize('rhinocéros')).toBe('rhinocéros'); expect(inflector.pluralize('houx')).toBe('houx'); expect(inflector.pluralize('lynx')).toBe('lynx'); expect(inflector.pluralize('roux')).toBe('roux'); expect(inflector.pluralize('gaz')).toBe('gaz'); expect(inflector.pluralize('quartz')).toBe('quartz'); expect(inflector.pluralize('quiz')).toBe('quiz'); }); it('should pluralize exception nouns', function() { expect(inflector.pluralize('ail')).toBe('aulx'); expect(inflector.pluralize('bétail')).toBe('bestiaux'); }); it('should pluralize regular nouns', function() { expect(inflector.pluralize('chai')).toBe('chais'); expect(inflector.pluralize('vérité')).toBe('vérités'); expect(inflector.pluralize('orange')).toBe('oranges'); }); }); describe('.singularize()', function() { it('should singularize regular nouns ending by -aux', function() { expect(inflector.singularize('amiraux')).toBe('amiral'); expect(inflector.singularize('chevaux')).toBe('cheval'); expect(inflector.singularize('généraux')).toBe('général'); }); it('should singularize exception nouns ending by -aux', function() { expect(inflector.singularize('baux')).toBe('bail'); expect(inflector.singularize('vitraux')).toBe('vitrail'); expect(inflector.singularize('émaux')).toBe('émail'); }); it('should singularize regular nouns ending by -aux', function() { expect(inflector.singularize('cadeaux')).toBe('cadeau'); expect(inflector.singularize('beaux')).toBe('beau'); expect(inflector.singularize('étaux')).toBe('étau'); }); it('should singularize nouns with multiple plural forms', function() { expect(inflector.singularize('ails')).toBe('ail'); expect(inflector.singularize('aulx')).toBe('ail'); expect(inflector.singularize('ciels')).toBe('ciel'); expect(inflector.singularize('cieux')).toBe('ciel'); expect(inflector.singularize('œils')).toBe('œil'); expect(inflector.singularize('yeux')).toBe('œil'); expect(inflector.singularize('aïeuls')).toBe('aïeul'); // Regular expect(inflector.singularize('aïeux')).toBe('aïeul'); expect(inflector.singularize('bisaïeuls')).toBe('bisaïeul'); // Regular expect(inflector.singularize('bisaïeux')).toBe('bisaïeul'); expect(inflector.singularize('craus')).toBe('crau'); expect(inflector.singularize('craux')).toBe('crau'); expect(inflector.singularize('graus')).toBe('grau'); expect(inflector.singularize('graux')).toBe('grau'); expect(inflector.singularize('sénaus')).toBe('sénau'); expect(inflector.singularize('sénaux')).toBe('sénau'); expect(inflector.singularize('tussaus')).toBe('tussau'); expect(inflector.singularize('tussaux')).toBe('tussau'); expect(inflector.singularize('emposieus')).toBe('emposieu'); expect(inflector.singularize('emposieux')).toBe('emposieu'); expect(inflector.singularize('richelieus')).toBe('richelieu'); expect(inflector.singularize('richelieux')).toBe('richelieu'); //expect(inflector.singularize('feus')).toBe('feu'); // This one is an adjective. expect(inflector.singularize('feux')).toBe('feu'); expect(inflector.singularize('lieus')).toBe('lieu'); // Fish expect(inflector.singularize('lieux')).toBe('lieu'); expect(inflector.singularize('corails')).toBe('corail'); expect(inflector.singularize('coraux')).toBe('corail'); }); it('should singularize exception nouns ending by -oux', function() { expect(inflector.singularize('bijoux')).toBe('bijou'); expect(inflector.singularize('joujoux')).toBe('joujou'); expect(inflector.singularize('hiboux')).toBe('hibou'); }); it('should singularize exception nouns ending by -eus', function() { expect(inflector.singularize('bleus')).toBe('bleu'); expect(inflector.singularize('émeus')).toBe('émeu'); expect(inflector.singularize('pneus')).toBe('pneu'); }); it('should singularize regular nouns ending by -eux', function() { expect(inflector.singularize('pieux')).toBe('pieu'); expect(inflector.singularize('lieux')).toBe('lieu'); expect(inflector.singularize('feux')).toBe('feu'); }); it('should singularize regular nouns ending by -eaux', function() { expect(inflector.singularize('eaux')).toBe('eau'); expect(inflector.singularize('manteaux')).toBe('manteau'); expect(inflector.singularize('arbrisseaux')).toBe('arbrisseau'); }); it('should singularize regular nouns ending by -œux', function() { expect(inflector.singularize('vœux')).toBe('vœu'); }); it('should singularize regular nouns ending by -s, -x or -z', function() { expect(inflector.singularize('cas')).toBe('cas'); expect(inflector.singularize('os')).toBe('os'); expect(inflector.singularize('rhinocéros')).toBe('rhinocéros'); expect(inflector.singularize('houx')).toBe('houx'); expect(inflector.singularize('lynx')).toBe('lynx'); expect(inflector.singularize('roux')).toBe('roux'); expect(inflector.singularize('gaz')).toBe('gaz'); expect(inflector.singularize('quartz')).toBe('quartz'); expect(inflector.singularize('quiz')).toBe('quiz'); }); it('should singularize exception nouns', function() { expect(inflector.singularize('bestiaux')).toBe('bétail'); }); it('should singularize regular nouns', function() { expect(inflector.singularize('chais')).toBe('chai'); expect(inflector.singularize('vérités')).toBe('vérité'); expect(inflector.singularize('oranges')).toBe('orange'); // Exception nouns ending by -als expect(inflector.singularize('carnavals')).toBe('carnaval'); expect(inflector.singularize('narvals')).toBe('narval'); expect(inflector.singularize('récitals')).toBe('récital'); // Regular nouns ending by -ails expect(inflector.singularize('détails')).toBe('détail'); expect(inflector.singularize('poitrails')).toBe('poitrail'); expect(inflector.singularize('chandails')).toBe('chandail'); // Regular nouns ending by -ous expect(inflector.singularize('trous')).toBe('trou'); expect(inflector.singularize('bambous')).toBe('bambou'); expect(inflector.singularize('toutous')).toBe('toutou'); // Exception nouns ending by -aus expect(inflector.singularize('berimbaus')).toBe('berimbau'); expect(inflector.singularize('landaus')).toBe('landau'); expect(inflector.singularize('pilaus')).toBe('pilau'); }); }); /* These tests ensure pluralizing plurals or singularizing singulars won't lead to wrong results. */ describe('pluralize()', function() { it('should pluralize exception nouns ending by -al', function() { expect(inflector.pluralize('carnavals')).toBe('carnavals'); expect(inflector.pluralize('narvals')).toBe('narvals'); expect(inflector.pluralize('récitals')).toBe('récitals'); }); it('should pluralize regular nouns ending by -al', function() { expect(inflector.pluralize('amiraux')).toBe('amiraux'); expect(inflector.pluralize('chevaux')).toBe('chevaux'); expect(inflector.pluralize('généraux')).toBe('généraux'); }); it('should pluralize exception nouns ending by -ail', function() { expect(inflector.pluralize('baux')).toBe('baux'); expect(inflector.pluralize('vitraux')).toBe('vitraux'); expect(inflector.pluralize('émaux')).toBe('émaux'); }); it('should pluralize regular nouns ending by -ail', function() { expect(inflector.pluralize('détails')).toBe('détails'); expect(inflector.pluralize('poitrails')).toBe('poitrails'); expect(inflector.pluralize('chandails')).toBe('chandails'); }); it('should pluralize exception nouns ending by -il', function() { expect(inflector.pluralize('cieux')).toBe('cieux'); expect(inflector.pluralize('yeux')).toBe('yeux'); }); it('should pluralize exception nouns ending by -ou', function() { expect(inflector.pluralize('bijoux')).toBe('bijoux'); expect(inflector.pluralize('joujoux')).toBe('joujoux'); expect(inflector.pluralize('hiboux')).toBe('hiboux'); }); it('should pluralize regular nouns ending by -ou', function() { expect(inflector.pluralize('trous')).toBe('trous'); expect(inflector.pluralize('bambous')).toBe('bambous'); expect(inflector.pluralize('toutous')).toBe('toutous'); }); it('should pluralize exception nouns ending by -au', function() { expect(inflector.pluralize('berimbaus')).toBe('berimbaus'); expect(inflector.pluralize('landaus')).toBe('landaus'); expect(inflector.pluralize('pilaus')).toBe('pilaus'); }); it('should pluralize regular nouns ending by -au', function() { expect(inflector.pluralize('cadeaux')).toBe('cadeaux'); expect(inflector.pluralize('beaux')).toBe('beaux'); expect(inflector.pluralize('étaux')).toBe('étaux'); }); it('should pluralize exception nouns ending by -eu', function() { expect(inflector.pluralize('bleus')).toBe('bleus'); expect(inflector.pluralize('émeus')).toBe('émeus'); expect(inflector.pluralize('pneus')).toBe('pneus'); }); it('should pluralize regular nouns ending by -eu', function() { expect(inflector.pluralize('pieux')).toBe('pieux'); expect(inflector.pluralize('lieux')).toBe('lieux'); expect(inflector.pluralize('feux')).toBe('feux'); }); it('should pluralize regular nouns ending by -eau', function() { expect(inflector.pluralize('eaux')).toBe('eaux'); expect(inflector.pluralize('manteaux')).toBe('manteaux'); expect(inflector.pluralize('arbrisseaux')).toBe('arbrisseaux'); }); it('should pluralize regular nouns ending by -œu', function() { expect(inflector.pluralize('vœux')).toBe('vœux'); }); it('should pluralize regular nouns ending by -s, -x or -z', function() { expect(inflector.pluralize('os')).toBe('os'); expect(inflector.pluralize('cas')).toBe('cas'); expect(inflector.pluralize('rhinocéros')).toBe('rhinocéros'); expect(inflector.pluralize('houx')).toBe('houx'); expect(inflector.pluralize('lynx')).toBe('lynx'); expect(inflector.pluralize('roux')).toBe('roux'); expect(inflector.pluralize('gaz')).toBe('gaz'); expect(inflector.pluralize('quartz')).toBe('quartz'); expect(inflector.pluralize('quiz')).toBe('quiz'); }); it('should pluralize exception nouns', function() { expect(inflector.pluralize('aulx')).toBe('aulx'); expect(inflector.pluralize('bestiaux')).toBe('bestiaux'); }); it('should pluralize regular nouns', function() { expect(inflector.pluralize('chais')).toBe('chais'); expect(inflector.pluralize('vérités')).toBe('vérités'); expect(inflector.pluralize('oranges')).toBe('oranges'); }); }); describe('.singularize()', function() { it('should singularize regular nouns ending by -aux', function() { expect(inflector.singularize('amiral')).toBe('amiral'); expect(inflector.singularize('cheval')).toBe('cheval'); expect(inflector.singularize('général')).toBe('général'); }); it('should singularize exception nouns ending by -aux', function() { expect(inflector.singularize('bail')).toBe('bail'); expect(inflector.singularize('vitrail')).toBe('vitrail'); expect(inflector.singularize('émail')).toBe('émail'); }); it('should singularize regular nouns ending by -aux', function() { expect(inflector.singularize('cadeau')).toBe('cadeau'); expect(inflector.singularize('beau')).toBe('beau'); expect(inflector.singularize('étau')).toBe('étau'); }); it('should singularize nouns with multiple plural forms', function() { expect(inflector.singularize('ail')).toBe('ail'); expect(inflector.singularize('ciel')).toBe('ciel'); expect(inflector.singularize('œil')).toBe('œil'); expect(inflector.singularize('aïeul')).toBe('aïeul'); expect(inflector.singularize('bisaïeul')).toBe('bisaïeul'); expect(inflector.singularize('crau')).toBe('crau'); expect(inflector.singularize('grau')).toBe('grau'); expect(inflector.singularize('sénau')).toBe('sénau'); expect(inflector.singularize('tussau')).toBe('tussau'); expect(inflector.singularize('emposieu')).toBe('emposieu'); expect(inflector.singularize('richelieu')).toBe('richelieu'); expect(inflector.singularize('feu')).toBe('feu'); expect(inflector.singularize('lieu')).toBe('lieu'); // Fish expect(inflector.singularize('corail')).toBe('corail'); }); it('should singularize exception nouns ending by -oux', function() { expect(inflector.singularize('bijou')).toBe('bijou'); expect(inflector.singularize('joujou')).toBe('joujou'); expect(inflector.singularize('hibou')).toBe('hibou'); }); it('should singularize exception nouns ending by -eus', function() { expect(inflector.singularize('bleu')).toBe('bleu'); expect(inflector.singularize('émeu')).toBe('émeu'); expect(inflector.singularize('pneu')).toBe('pneu'); }); it('should singularize regular nouns ending by -eux', function() { expect(inflector.singularize('pieu')).toBe('pieu'); expect(inflector.singularize('lieu')).toBe('lieu'); expect(inflector.singularize('feu')).toBe('feu'); }); it('should singularize regular nouns ending by -eaux', function() { expect(inflector.singularize('eau')).toBe('eau'); expect(inflector.singularize('manteau')).toBe('manteau'); expect(inflector.singularize('arbrisseau')).toBe('arbrisseau'); }); it('should singularize regular nouns ending by -œux', function() { expect(inflector.singularize('vœu')).toBe('vœu'); }); it('should singularize regular nouns ending by -s, -x or -z', function() { expect(inflector.singularize('cas')).toBe('cas'); expect(inflector.singularize('os')).toBe('os'); expect(inflector.singularize('rhinocéros')).toBe('rhinocéros'); expect(inflector.singularize('houx')).toBe('houx'); expect(inflector.singularize('lynx')).toBe('lynx'); expect(inflector.singularize('roux')).toBe('roux'); expect(inflector.singularize('gaz')).toBe('gaz'); expect(inflector.singularize('quartz')).toBe('quartz'); expect(inflector.singularize('quiz')).toBe('quiz'); }); it('should singularize exception nouns', function() { expect(inflector.singularize('bétail')).toBe('bétail'); }); it('should singularize regular nouns', function() { expect(inflector.singularize('chai')).toBe('chai'); expect(inflector.singularize('vérité')).toBe('vérité'); expect(inflector.singularize('orange')).toBe('orange'); // Exception nouns ending by -als expect(inflector.singularize('carnaval')).toBe('carnaval'); expect(inflector.singularize('narval')).toBe('narval'); expect(inflector.singularize('récital')).toBe('récital'); // Regular nouns ending by -ails expect(inflector.singularize('détail')).toBe('détail'); expect(inflector.singularize('poitrail')).toBe('poitrail'); expect(inflector.singularize('chandail')).toBe('chandail'); // Regular nouns ending by -ous expect(inflector.singularize('trou')).toBe('trou'); expect(inflector.singularize('bambou')).toBe('bambou'); expect(inflector.singularize('toutou')).toBe('toutou'); // Exception nouns ending by -aus expect(inflector.singularize('berimbau')).toBe('berimbau'); expect(inflector.singularize('landau')).toBe('landau'); expect(inflector.singularize('pilau')).toBe('pilau'); }); }); describe('.attach()', function() { it('should attach new methods to String', function() { inflector.attach(); expect('corail'.pluralizeNoun()).toBe('coraux'); expect('coraux'.singularizeNoun()).toBe('corail'); expect('récital'.pluralizeNoun()).toBe('récitals'); expect('récitals'.singularizeNoun()).toBe('récital'); }); }); }); <reponame>diMItuR10/JavaScript-Advanced function lockedProfile() { document.getElementById('main').addEventListener('click', (ev) => { if (ev.target.tagName === 'BUTTON') { const profile = ev.target.parentNode; const isLocked = profile.querySelector('input[type=radio]:checked').value === 'lock'; if (isLocked) { return; } let div = profile.querySelector('div'); let isVisible = profile.style.display === 'block'; div.style.display = isVisible ? 'none' : 'block'; ev.target.textContent = isVisible ? 'Hide it' : 'Show more' } }) }/** * @license Copyright (c) 2003-2015, CKSource - <NAME>. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.editorConfig = function (config) { // Define changes to default configuration here. // For complete reference see: // http://docs.ckeditor.com/#!/api/CKEDITOR.config // The toolbar groups arrangement, optimized for two toolbar rows. config.allowedContent=true; config.extraPlugins = 'smiley'; config.toolbarGroups = [ {name: 'tools'}, {name: 'insert', items: ['Smiley']}, {name: 'styles'}, {name: 'colors'}, ]; config.toolbar = [ {name: 'insert', items: ['Smiley']}, {name: 'document', groups: ['mode', 'document', 'doctools'], items: ['Source']}, { name: 'basicstyles', groups: ['basicstyles', 'cleanup'], items: ['Bold', 'Italic', 'Strike', '-', 'RemoveFormat'] }, {name: 'styles'}, {name: 'colors'} ]; config.uiColor = '#F4F4F4'; // Remove some buttons provided by the standard plugins, which are // not needed in the Standard(s) toolbar. config.removeButtons = 'Underline,Subscript,Superscript'; // Set the most common block elements. config.format_tags = 'p;h1;h2;h3;pre'; // Simplify the dialog windows. config.removeDialogTabs = 'image:advanced;link:advanced'; config.enterMode=CKEDITOR.ENTER_BR; config.htmlEncodeOutput= false; config.entities= false; config.fillEmptyBlocks= false; config.forcePasteAsPlainText = true; config.pasteFromWordPromptCleanup = true; config.pasteFromWordRemoveFontStyles = true; config.ignoreEmptyParagraph = true; config.removeFormatAttributes = true; }; import { _getDecks } from './DATA' import { Notifications } from 'expo'; import * as Permissions from 'expo-permissions' import { AsyncStorage } from 'react-native'; const NOTIFICATIONS_KEY= "Udacicards:notifications" export function retrieveDecks() { return Promise.all([ _getDecks() ]).then((decks) => ({ decks })) } export function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array } export function clearLocalNotification() { return AsyncStorage.removeItem(NOTIFICATIONS_KEY) .then(Notifications.cancelAllScheduledNotificationsAsync()) } function createNotification() { return { title: 'Exercise your brain!', body: "You didn't play your daily quiz today!", android: { sound: true, priority: 'high', sticky: false, vibrate: true } } } export function setLocalNotification() { AsyncStorage.getItem(NOTIFICATIONS_KEY) .then(JSON.parse) .then(async (data) => { if (data === null) { const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS) if(status === 'granted') { Notifications.cancelAllScheduledNotificationsAsync() let tomorrow = new Date() tomorrow.setDate(tomorrow.getDate() + 1) tomorrow.setHours(20) tomorrow.setMinutes(0) tomorrow.setSeconds(0) Notifications.scheduleLocalNotificationAsync( createNotification(), { time: tomorrow, repeat: 'day' } ) AsyncStorage.setItem(NOTIFICATIONS_KEY, JSON.stringify(true)) } } }) }<reponame>allyjunio/k010 var mongoose = require('mongoose'); var tables = require('../tables').Tables; // Cliente var Cliente = new mongoose.Schema({ nome: { type: String, required: true }, email: {type: String}, amigo: {type: mongoose.Schema.ObjectId, ref: tables.pessoa} }); // Cliente.index({coordenadas: '2dsphere'}); mongoose.model(tables.pessoa, Cliente);<filename>node-process-interactions/node-ipc/ipc.process.1.js const ipc = require("node-ipc"); ipc.config.id = "a-unique-process-name1"; ipc.config.retry = 1500; ipc.config.silent = true; ipc.serve(() => ipc.server.on("a-unique-message-name", (message) => { console.log(message); }) ); ipc.server.start(); <filename>src/components/welcomeText.js import React, { useState, useEffect } from 'react'; import firebase from 'firebase'; import '../styles/welcomeText.css'; const WelcomeText = () => { const [date, setDate] = useState(new Date()); const user = firebase.auth().currentUser; var name; var email; useEffect(() => { var timer = setInterval(()=>setDate(new Date()), 1000 ) return function cleanup() { clearInterval(timer); } }) if (user!=null) { name = user.displayName; email = user.email; } return ( <div className="welcome-text-wrapper"> <h6>{date.toLocaleDateString()}</h6> <h1>Welcome Back,</h1> <h1>{name || email}</h1> </div> ) } export default WelcomeText/** * 禁止不必要的布尔类型转换 * 在上下文中比如if语句中 * 表达式结果已经被强制转换成了布尔值 * 再通过!!或Boolean转化是不必要的 */ const bar = false; let foo = !!!bar; foo = !!bar ? 1 : 0; foo = new Boolean(!!bar); console.log(foo); angular.module("das.system") .directive('uiBundleSlider', function($timeout) { return { restrict: 'E', scope: { options: '@', min: '@', max: '@', model:'=ngModel' }, templateUrl: '/js/directives/ui-bundle-slider/ui-bundle-slider.html', link: function($scope, $elem, $attrs) { $timeout(function() { var $target = $('<div class="ui-slider-selected-area"></div>'); $elem.find('div.ui-slider').prepend($target); ['model', 'min', 'max'].forEach(function(param) { $scope.$watch(param, function() { $target.width( ($scope.model - $scope.min)/($scope.max - $scope.min) * 100 + '%' ); }); }); }); } }; });<gh_stars>100-1000 import {ItemView} from 'backbone.marionette'; import {className} from '../../decorators'; import template from './DescriptionView.hbs'; @className('pane__section') class DescriptionView extends ItemView { template = template; serializeData() { return this.model.get('description'); } } export default DescriptionView; function PrePostSelected() { return (choices.installer_choice_2.selected || choices.installer_choice_3.selected || choices.installer_choice_4.selected || choices.installer_choice_5.selected || choices.installer_choice_6.selected || choices.installer_choice_7.selected || choices.installer_choice_8.selected || choices.installer_choice_9.selected || choices.installer_choice_10.selected); } function CommonSelected() { return (choices.installer_choice_2.selected); } function DSDTSelected() { return (choices.installer_choice_4_1.selected || choices.installer_choice_4_2.selected || choices.installer_choice_4_3.selected || choices.installer_choice_4_4.selected); } function SysDefSelected() { return (choices.installer_choice_6_1.selected || choices.installer_choice_6_2.selected || choices.installer_choice_6_3.selected || choices.installer_choice_6_4.selected || choices.installer_choice_6_5.selected || choices.installer_choice_6_6.selected); }'use strict'; const path = require('path'); const helpers = require('yeoman-test'); const assert = require('yeoman-assert'); module.exports = () => { describe('when using restangular', () => { before(done => { this.generator = helpers .run(path.join(__dirname, '../../generators/app')) .withPrompts({ resource: 'restangular' }) .toPromise() .then(() => done()); }); it('should add restangular to the package.json', () => { assert.fileContent('package.json', 'restangular'); }); it('should import restangular in the angular modules', () => { assert.fileContent('src/app/app.js', 'import \'lodash\''); assert.fileContent('src/app/app.js', 'import \'restangular\''); assert.fileContent('src/app/app.js', /angular\.module\([\s\S]*, [\s\S]*?restangular/); }); }); describe('when using ngResource', () => { before(done => { this.generator = helpers .run(path.join(__dirname, '../../generators/app')) .withPrompts({ resource: 'ngResource' }) .toPromise() .then(() => done()); }); it('should add angular-resource to the package.json', () => { assert.fileContent('package.json', 'angular-resource'); }); it('should import angular-resource in the angular modules', () => { assert.fileContent('src/app/app.js', 'import ngResource from \'angular-resource\''); assert.fileContent('src/app/app.js', /angular\.module\([\s\S]*, [\s\S]*?ngResource/); }); }); }; <reponame>realtechnicalsci/DuccBOX.js<gh_stars>0 import * as THREE from "../three.module.js"; function key_down(event){ var W = 87; var S = 83; var A = 65; var D = 68; var minus = 189; var plus = 187; var k = event.keyCode; console.log(k); if(k == A){ // rotate left playerIsRotatingLeft = 1; } if(k == D){ // rotate right playerIsRotatingRight = 1; } if(k == W){ // go forward playerIsMovingForward = 1; } if(k == S){ // go back playerIsMovingBackwards = 1; } }export const RunMode = { DEV: "dev", TEST: "test", PROD: "production", }; export const DevMode = { REGULAR: "regular", }; const Print = () => { return ( <div> <Page/> </div> ); }; ReactDOM.render( <Print />, document.getElementById('print') ); <gh_stars>0 import React from 'react' import { UserConsumer } from '../context/Context' function ComponentC(props) { console.log('ComponentC',props) return ( <div> <UserConsumer> { (userData)=>{ return( <h2 style={{color:"blue"}}>Data from Context: {userData}</h2> ) } } </UserConsumer> <h1 style={{color:"red"}}>data from props drilling: {props.uname}</h1> </div> ) } export default ComponentC <reponame>maisans-maid/tamako-api<gh_stars>1-10 module.exports = { TAMAKOAPI: require("./src/tamakoapi"), version: require('./package.json').version } var dir_040677b3de113a5d50359e1bf1f7d2b7 = [ [ "Uniform.hpp", "_uniform_8hpp_source.html", null ], [ "UniformBuffer.hpp", "_uniform_buffer_8hpp_source.html", null ], [ "UniformPerCamera.hpp", "_uniform_per_camera_8hpp_source.html", null ], [ "UniformPerObject.hpp", "_uniform_per_object_8hpp_source.html", null ], [ "UniformsPerFrame.hpp", "_uniforms_per_frame_8hpp_source.html", null ] ];"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = __importDefault(require("react")); const ReactComponent = props => (react_1.default.createElement("svg", Object.assign({ viewBox: "0 0 24 24", width: "1em", height: "1em" }, props), react_1.default.createElement("path", { fill: "none", d: "M0 0h24v24H0V0z" }), react_1.default.createElement("path", { d: "M12 2C8.14 2 5 5.14 5 9c0 4.17 4.42 9.92 6.23 12.11.4.48 1.13.48 1.53 0C14.58 18.92 19 13.17 19 9c0-3.86-3.14-7-7-7zm.88 13.75h-1.75V14h1.75v1.75zm.38-4.04c-.03.04-.06.09-.09.14-.02.04-.05.08-.07.12-.03.05-.05.1-.07.15-.02.04-.04.08-.05.13-.06.19-.1.4-.1.63H11.12c0-.36.04-.66.11-.93h.02v-.06c.51-1.76 2.36-1.86 2.48-3.24.07-.85-.53-1.67-1.36-1.85-.91-.2-1.74.33-2.03 1.12-.11.33-.4.58-.76.58h-.16c-.55 0-.93-.53-.76-1.05.5-1.58 2.09-2.68 3.89-2.4 1.52.23 2.72 1.53 2.92 3.05.27 1.99-1.42 2.51-2.21 3.61z" }))); exports.default = ReactComponent; <filename>module/slspress/test/integration/example-app/handlers/example-container-handler.js 'use strict'; const { NotFoundError } = require('../../../..'); module.exports = function(req, res) { if (!req.event.pathParameters.id) { throw new NotFoundError('id'); } return this.component('components/resources/fake-database') .find(req.event.pathParameters.id) .then(res.send.bind(res)) .catch(res.handleError.bind(res)); };<reponame>jfarris10/pdxtipjar import React, { useState } from "react"; import { Link } from "gatsby"; import Layout from "../components/layout"; import SEO from "../components/seo"; import RandomButton from "../components/RandomButton"; import RandomPerson from "../components/RandomPerson"; import social1 from "../images/social-1.png"; import social2 from "../images/social-2.png"; import social3 from "../images/social-3.png"; import social4 from "../images/social-4.png"; const Intro = () => ( <div className="intro"> <h2>About PDX Tip Jar</h2> <p> PDX Tip Jar is an opportunity to share a small act of kindness with our Service Industry community during these uncertain times. With a government mandate in effect as of Tuesday, March 17th, all bars and restaurants in the state of Oregon are required to close for the next four weeks—with the exception of take-out and delivery operations—which has put many folks out of work. </p> <p> The premise is simple: Tip a dollar, $5, $10, $20—or whatever you’d like—directly to a Service Industry worker! Tip someone at random or browse the <Link to="/donate">full list to find your favorite spots</Link> . </p> <p> If you’re a Service Industry worker,{" "} <Link to="/signup">fill out the form to receive tips</Link> directly through your Cashapp, Venmo, or PayPal. </p> </div> ); const Pledge = () => ( <div className="pledge"> <h2>Take the pledge!</h2> <p> Take the pledge to tip every time you make a cocktail at home, miss going out, wish you were drinking a latte, wish you had a wood-fired oven, or don’t want to do the dishes. </p> <h3>Help spread the word and share on social media!</h3> <a href={social1}> <img src={social1} alt="Send some love on PDX tip jar" /> </a> <a href={social2}> <img src={social2} alt="I pledge to tip for every meal I wish someone else made" /> </a> <a href={social3}> <img src={social3} alt="I pledge to tip for every drink I make at home because I really miss going out" /> </a> <a href={social4}> <img src={social4} alt="I pledge to tip for every cup of coffee I wish was a latte" /> </a> </div> ); const IndexPage = () => { const [randomPerson, setRandomPerson] = useState({}); return ( <Layout> <SEO title="Home" /> <Intro /> {Object.keys(randomPerson).length > 0 && ( <RandomPerson person={randomPerson} clearPerson={() => setRandomPerson({})} random={true} /> )} <RandomButton handleClick={setRandomPerson} text="Find a random person to tip" /> <nav> <Link to="/donate">Browse the full list</Link> <Link to="/signup">Sign up to receive tips</Link> </nav> <Pledge /> </Layout> ); }; export default IndexPage; // onload function bindReady(handler){var called=false;function ready(){if(called)return;called=true;handler();} function tryScroll(){if(called)return;if(!document.body)return;try{document.documentElement.doScroll('left');ready();} catch(e){setTimeout(tryScroll,0);}}if(document.addEventListener){document.addEventListener('DOMContentLoaded',function(){ready();},false);} else if(document.attachEvent){if(document.documentElement.doScroll&&window==window.top){tryScroll();} document.attachEvent('onreadystatechange',function(){if(document.readyState==='complete'){ready();}});} if(window.addEventListener)window.addEventListener('load',ready,false);else if(window.attachEvent) window.attachEvent('onload',ready);else window.onload=ready;}var readyList=[];function onReady(handler) {if(!readyList.length){bindReady(function(){for(var i=0;i<readyList.length;i++){readyList[i]();}});}readyList.push(handler);} onReady(function(){ var thash = getUri('hash')[0] && checkHash(getUri('hash')[1]) ? getUri('hash')[1] : false; if(thash){ document.getElementById('hash').value = thash; update(); } }); function encUri(text){ return encodeURIComponent(text); } function getUri(name) { var uriEl = (RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search)); return uriEl ? [true, decodeURIComponent(uriEl[1].split('&')[0])] : [false, '']; } function sel_all(el){ el.focus(); el.select(); } function update(){ try{ var hash_data = document.getElementById('hash').value; if(checkHash(hash_data)){ var data = 'magnet:'; data += '?xt=urn:btih:' + encUri(document.getElementById('hash').value); data += '&tr=' + encUri('udp://tracker.coppersurfer.tk:6969/announce'); data += '&tr=' + encUri('udp://tracker.internetwarriors.net:1337/announce'); data += '&tr=' + encUri('udp://tracker.leechers-paradise.org:6969/announce'); data += '&tr=' + encUri('http://tracker.internetwarriors.net:1337/announce'); data += '&tr=' + encUri('udp://tracker.opentrackr.org:1337/announce'); data += '&tr=' + encUri('http://tracker.opentrackr.org:1337/announce'); data += '&tr=' + encUri('udp://tracker.zer0day.to:1337/announce'); data += '&tr=' + encUri('udp://tracker.pirateparty.gr:6969/announce'); data += '&tr=' + encUri('http://explodie.org:6969/announce'); data += '&tr=' + encUri('http://p4p.arenabg.com:1337/announce'); data += '&tr=' + encUri('http://mgtracker.org:6969/announce'); document.getElementById('link').href = data; document.getElementById('link_text').value = data; } var uri = location.protocol + '//' + location.hostname + location.pathname; uri += checkHash(hash_data) ? '?hash='+hash_data : ''; } catch(e){ alert('exception: ' + e); } } function checkHash(hash){ return hash.length == 32 && hash.match(/^[2-7A-Za-z]+$/) || hash.length == 40 && hash.match(/^[0-9A-Fa-f]+$/) ? hash : false; } <reponame>doberman/dbrmn-github-repo-cleanup #!/usr/bin/env node const path = require('path'); const { promisify } = require('util'); const shellSource = promisify(require('shell-source')); const chalk = require('chalk'); const columnify = require('columnify'); const args = require('commander'); const inquirer = require('inquirer'); const pkg = require('./package.json'); // lib const cleanup = require('./lib/cleanup'); const compress = require('./lib/compress'); const clone = require('./lib/clone'); const verifySshKeys = require('./lib/verify-ssh-keys'); const uploadToDropbox = require('./lib/dropbox-upload'); const deleteFromGithub = require('./lib/delete-from-github'); // configure CLI args .version(pkg.version) .description(pkg.description) .usage('<github-repo-slug> [options]') .option('-d, --deleteFromGithub', 'Delete GitHub reposity upon successful archive') .option('-v --verbose', 'Show debug information') .parse(process.argv); const homeDir = process.env.HOME || process.env.USERPROFILE; const settings = { homeDir, configFilePath: path.join(homeDir, '.githubrepocleanuprc'), tempDir: '/tmp/github-repo-cleanup', deleteRepositoryFromGithub: args.deleteFromGithub, verbose: args.verbose, dropboxAccessToken: process.env.DROPBOX_ACCESS_TOKEN, githubAccessToken: process.env.GITHUB_ACCESS_TOKEN, // these are set below repositorySlug: null, repositoryName: null, repositoryUrl: null, clonedRepositoryPath: null, compressedRepositoryPath: null }; settings.repositorySlug = process.argv[2]; if (!settings.repositorySlug) { args.help(); } else if (!/^([^/\s]+)\/{1,}([^/\s]+)$/.test(settings.repositorySlug)) { console.error(`Invalid GitHub repository slug \`${settings.repositorySlug}\``); args.help(); } (async () => { // load up configuration file try { await shellSource(settings.configFilePath); } catch (e) { console.error(`Failed to load up configuration file ${settings.configFilePath}: `, e); cleanup.cleanUpAndExit(1); } // attempt to re-set access tokens from sourced environment variables settings.dropboxAccessToken = process.env.DROPBOX_ACCESS_TOKEN; settings.githubAccessToken = process.env.GITHUB_ACCESS_TOKEN; if (!settings.repositorySlug) { console.error(`Invalid repository slug '${settings.repositorySlug}'`); process.exit(1); } settings.repositoryName = path.basename(settings.repositorySlug); settings.repositoryUrl = `<EMAIL>:${settings.repositorySlug}`; settings.clonedRepositoryPath = path.join(settings.tempDir, settings.repositoryName); if (settings.verbose) { const settingsWithPlaceholderValues = {}; Object.keys(settings).forEach((key) => { settingsWithPlaceholderValues[key] = settings[key] || '<empty>'; }); console.log(chalk.dim('\nLoaded configuration:')); console.log(chalk.dim(columnify(settingsWithPlaceholderValues))); } if (settings.deleteRepositoryFromGithub) { // prompt the user for confirmation const confirmationKey = `confirmDelete_${settings.repositorySlug.replace(/[^a-z/_]/gi, '_')}`; const inquirerResults = await inquirer.prompt({ type: 'confirm', name: confirmationKey, message: `This will clone '${settings.repositorySlug}', archive it to Dropbox and finally ${chalk.underline(chalk.italic('delete'))} it from GitHub. Are you sure?`, default: false }); if (!inquirerResults[confirmationKey]) { // negative confirmation from user, clean up and exit return cleanup.cleanUpAndExit(1); } } try { // user confirmed, move on to verify SSH keys await verifySshKeys(settings); // SSH keys looks valid, move on to clone the repository await clone(settings); // repository cloned, move on to compress it await compress(settings); // repository compressed, move on to upload it to Dropbox await uploadToDropbox(settings); // repository uploaded to Dropbox, delete it from GitHub if (settings.deleteRepositoryFromGithub) { await deleteFromGithub(settings); } // all done, clean up await cleanup.cleanUp(settings); } catch (e) { console.error('Failed:', settings.verbose ? e : e.message); process.exit(1); } })(); <filename>lib/httpClient.js var Scanner = Java.type("java.util.Scanner") var URL = Java.type("java.net.URL") var StandardCharsets = Java.type("java.nio.charset.StandardCharsets") function mount_http_request(method, url, params) { var request = this var params = http.serializeParams(params || {}) var properties = { charset: StandardCharsets.UTF_8, "Content-Type": "application/x-www-form-urlencoded" } var fluent = { params: (function (pars) { params = http.serializeParams(pars) return fluent }).bind(request), property: (function (property, value) { properties[property] = value return request }).bind(request), charset: (function (value) { properties["Accept-Charset"] = value return fluent }).bind(request), contentType: (function (value) { properties["Content-Type"] = value return fluent }).bind(request), get_content: function(http_connection) { var inputStream = http_connection.getInputStream() var scanner = new Scanner(inputStream, "UTF-8") var content = scanner.useDelimiter("\\Z|\\A").next() scanner.close() return content }, fetch: (function _fetch() { var http_connection if (method.toUpperCase() == "POST") { var output; http_connection = new URL(url).openConnection() http_connection.setRequestMethod(method) Object.keys(properties).forEach(function(prop) { http_connection.setRequestProperty(prop, properties[prop]) }) http_connection.setDoOutput(true) http_connection.setRequestMethod(method) try { (output = http_connection.getOutputStream()).write(params.getBytes(properties.charset)) } catch(exception) { // if (output) // output.close() } } else /* if (method.toUpperCase() == "GET") */ { url += "?" + params http_connection = new URL(url).openConnection() } return fluent.get_content(http_connection) }).bind(request) } return fluent } /** * Busca informações em uma api REST * @example * // returns {nome: "David", idade: 10} * HTTPClient.post("http://localhost:8080/test/pecho").charset("UTF-8").fetch() * @example * // returns "Hello World!" * HTTPClient.post("http://localhost:8080/test/hello").fetch() */ var HTTPClient = { get: function (url, params) { return mount_http_request("GET", url, params) }, post: function (url, params) { return mount_http_request("POST", url, params) }, put: function (url, params) { return mount_http_request("PUT", url, params) }, delete: function (url, params) { return mount_http_request("DELETE", url, params) }, } exports = HTTPClient /* print ("\n", HTTPClient // .post("http://localhost:8080/test/pecho", {params: {nome: "<NAME>", idade: 13}}) .post("http://localhost:8080/test/pecho") .params({params: {nome: "David", idade: 10}}) // .get("http://example.com") // .get("http://localhost:8080/test/json") // .get("http://localhost:8080/test/echo", {params: {nome: "<NAME>", idade: 13}}) // .get("http://localhost:8080/test/echo") // .params({params: {nome: "<NAME>", idade: 13}}) .charset("UTF-8") .fetch() , "\n" ) */ const todoItem = require('../models/todo-item'); module.exports = (req, res, next) => { try{ const userName = req.params.username; todoItem.find({ 'user.userName': userName }, (err, data) => { if (err) throw err; res.body = data; next(); }); } catch(e){ return res.status(500).send(e); } }; <reponame>zlinker89/HELLO_WORLD01_02<gh_stars>0 // valor temporal var preguntalst = [ {pregunta: "Contribuye a generar una cultura orientada al logro de resultados velando por mantener la efectividad de los procesos." }, {pregunta: "Alinea sus propios planes de trabajo con las metas del área e identifica recursos y planes de acción realistas y necesarios a corto, mediano y largo plazo. " }, {pregunta: "Analiza posibles obstáculos o barreras que pueden impedir el logro de los objetivos y propone soluciones para removerlos. " }, {pregunta: "Analiza posibles obstáculos o barreras que pueden impedir el logro de los objetivos y propone soluciones para removerlos. " } ]; miApp.controller("preguntaList", function($scope, $filter, $http){ // init $scope.sortingOrder = sortingOrder; $scope.reverse = false; $scope.filteredItems = []; $scope.groupedItems = []; $scope.itemsPerPage = 1; $scope.pagedItems = []; $scope.currentPage = 0; $scope.items = [ {pregunta: "Contribuye a generar una cultura orientada al logro de resultados velando por mantener la efectividad de los procesos.", respuestas:[ {respuesta: "CASI NUNCA"}, {respuesta: "EN POCAS OCASIONES"}, {respuesta: "NORMALMENTE"}, {respuesta: "CON FRECUENCIA"}, {respuesta: "SIEMPRE"} ]}, {pregunta: "Alinea sus propios planes de trabajo con las metas del área e identifica recursos y planes de acción realistas y necesarios a corto, mediano y largo plazo. ", respuestas:[ {respuesta: "CASI NUNCA"}, {respuesta: "EN POCAS OCASIONES"}, {respuesta: "NORMALMENTE"}, {respuesta: "CON FRECUENCIA"}, {respuesta: "SIEMPRE"} ] }, {pregunta: "Analiza posibles obstáculos o barreras que pueden impedir el logro de los objetivos y propone soluciones para removerlos. ", respuestas:[ {respuesta: "<NAME>"}, {respuesta: "EN POCAS OCASIONES"}, {respuesta: "NORMALMENTE"}, {respuesta: "CON FRECUENCIA"}, {respuesta: "SIEMPRE"} ] }, {pregunta: "Analiza posibles obstáculos o barreras que pueden impedir el logro de los objetivos y propone soluciones para removerlos. ", respuestas:[ {respuesta: "<NAME>"}, {respuesta: "EN POCAS OCASIONES"}, {respuesta: "NORMALMENTE"}, {respuesta: "CON FRECUENCIA"}, {respuesta: "SIEMPRE"} ]}]; // respuestas que seleccionan var respuestas = []; var searchMatch = function (haystack, needle) { if (!needle) { return true; } return haystack.toLowerCase().indexOf(needle.toLowerCase()) !== -1; }; // init the filtered items $scope.search = function () { $scope.filteredItems = $filter('filter')($scope.items, function (item) { for(var attr in item) { if (searchMatch(item[attr], $scope.query)) return true; } return false; }); // take care of the sorting order if ($scope.sortingOrder !== '') { $scope.filteredItems = $filter('orderBy')($scope.filteredItems, $scope.sortingOrder, $scope.reverse); } $scope.currentPage = 0; // now group by pages $scope.groupToPages(); }; // calculate page in place $scope.groupToPages = function () { $scope.pagedItems = []; for (var i = 0; i < $scope.filteredItems.length; i++) { if (i % $scope.itemsPerPage === 0) { $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ]; } else { $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]); } } }; $scope.range = function (start, end) { var ret = []; if (!end) { end = start; start = 0; } for (var i = start; i < end; i++) { ret.push(i); } return ret; }; $scope.prevPage = function () { if ($scope.currentPage > 0) { $scope.currentPage--; } }; $scope.nextPage = function () { if ($scope.currentPage < $scope.pagedItems.length - 1) { $scope.currentPage++; } }; $scope.setPage = function () { $scope.currentPage = this.n; }; // functions have been describe process the data for display $scope.search(); $scope.seleccion = function (r) { /* Guardo la seleccion de las respuestas */ // deselecciono los demas for (var i in $scope.items[r.target.name].respuestas){ $scope.items[r.target.name].respuestas[i]["seleccion"] = false; } // marco la seleccion $scope.items[r.target.name].respuestas[r.target.value]["seleccion"] = true; // capturo la seleccion respuestas[r.target.name] = $scope.items[r.target.name].respuestas[r.target.value].respuesta; // refresco la paginacion var pagina = $scope.currentPage; // guardo la pagina $scope.search(); $scope.currentPage = pagina; // pongo la misma pagina }; $scope.EnviarRespuestas = function(){ // AQUI EL CODIGO PARA ENVIAR RESPUESTAS AL SERVIDOR var cont = 0; for(var i in respuestas){ cont++; }; if ((cont == $scope.pagedItems.length)) { alert(JSON.stringify(respuestas)); // Metodo post Angular // $http.post('/api/respuestas', respuestas).then(function(d){ // console.log(d.data); // }); }else{ $scope.error = true; } }; });var data = new Date() var dsem = data.getDay() switch (dsem) { case 0: console.log('Domingo') break case 1: console.log('Segunda') break case 2: console.log('Terça') break case 3: console.log('Quarta') break case 4: console.log('Quinta') break case 5: console.log('Sexta') break case 6: console.log('Sábado') break default: console.log('[ERROR] Insira um dia válido') } if (dsem == 0 || dsem == 6) { console.log('Fim de Semana') } else { console.log('Dia de Semana') }<gh_stars>0 'use strict'; const debug = require('debug')('ee-core:logger'); const Loggers = require('egg-logger').EggLoggers; const assert = require('assert'); class Logger { constructor (config) { debug('Loaded logger'); assert(Object.keys(config).length != 0, `logger config is null`); this.eggLogger = this.init(config); } /** * 单例 */ static getInstance (config = {}) { if (typeof this.instance === 'object') { return this.instance.eggLogger; } this.instance = new Logger(config); // 返回egg-logger实例 return this.instance.eggLogger; } /** * 初始化模块 */ init(config) { const loggerConfig = config.logger; loggerConfig.type = 'application'; // application、agent if (config.env === 'prod' && loggerConfig.level === 'DEBUG' && !loggerConfig.allowDebugAtProd) { loggerConfig.level = 'INFO'; } const loggers = new Loggers(config); loggers.coreLogger.info('[ee-core:logger] init all loggers with options: %j', loggerConfig); return loggers; }; } module.exports = Logger;/** * Created by iyobo on 2016-12-05. */ const log = require('../log'); const _ = require('lodash'); const storage = require('../filestorage') class HTTPUtil { /** * If request is multi-part, Make multidimensional objects/arrays from one dimensional form data, and process any files. * @param ctx */ * objectify(ctx) { let fields = {} try { const contentType = ctx.request.accept.headers['content-type']; if (contentType && contentType.indexOf('multipart') > -1) { //multi-dimensionalize ctx.fields for (let compoundKey in ctx.request.fields) { let v = ctx.request.fields[compoundKey]; //If value is a file, then store it if (Array.isArray(v) && v.length > 0 && v[0]._writeStream) { /** * Determine whether single or multi file field upload */ if (v.length == 1) { v = yield storage.store(v[0]) } else { v = v.map(function*(file) { const val = yield storage.store(file); return val; }); } } //split by dot const keypath = compoundKey.split('.'); //Thank God for lodash... _.set(fields, keypath, v) } //Update // ctx.request.jollofFields = fields; ctx.request.fields = fields; } } catch (ex) { log.error('Error while objectifying form data', ex.stack) } } handleError(ctx, err) { if (err.isOperational) { ctx.status = err.status || 500; ctx.body = err; //ctx.app.emit('error', err, ctx); } else if (err.hash) { //jql error ctx.status = 405; ctx.body = 'Bad JQL query.'; //ctx.app.emit('error', err.message, ctx); } else if (err.isBoom) { ctx.status = err.output.statusCode; ctx.body = err.message; } else { log.err(err); ctx.throw(err); } } } module.exports = new HTTPUtil();import React, { Component } from "react"; import history from "../../history"; import "./form.scss"; export class Form extends Component { constructor(props) { super(props); this.state = { username: "", password: "", loggedOn: false }; } // Presses "Log In" button when user presses enter handleKeyPress = e => { let { username, password } = this.state; if (e.key === "Enter" && username && password) { this.handleButtonClick(e); } } handleButtonClick = e => { let { username, password } = this.state; if (username === "saad" && password === "<PASSWORD>") { this.setState({loggedOn: true}); this.props.getLoggedIn(true); history.push("/dashboard"); } else { this.setState({loggedOn: false}); } } render() { let { username, password } = this.state; return ( <div> <div id="grid"> <input placeholder="Username" name="username" id="user" value={username} onChange={e => this.setState({username: e.target.value})} onKeyPress={this.handleKeyPress} /> <input placeholder="Password" type="password" name="password" id="pw" value={password} onChange={e => this.setState({password: e.target.value})} onKeyPress={this.handleKeyPress} /> </div> <div id="enterButton"> <button id="enter" type="button" disabled={!username || !password} onClick={this.handleButtonClick} > Log In </button> </div> </div> ); } } export default Form; const initialState = { type: null, message: null } export const setNotification = (message, type, timeout) => { return async dispatch => { if (type === 'success') { dispatch({ type: 'SUCCESS_NOTIFICATION', data: { message, timeoutID: null, type: 'success' } }) } else { dispatch({ type: 'ERROR_NOTIFICATION', data: { message, timeoutID: null, type: 'error' } }) } const timeoutID = setTimeout(() => { dispatch({ type: 'REMOVE_NOTIFICATION', data: { type: null, timeoutID: null } }) }, timeout * 1000) dispatch({ type: 'SET_TIMEOUTID', timeoutID }) } } const notificationReducer = (state = initialState, action) => { switch (action.type) { case 'REMOVE_NOTIFICATION': return action.data case 'SUCCESS_NOTIFICATION': if (state.timeoutID) { clearTimeout(state.timeoutID) } return action.data case 'ERROR_NOTIFICATION': if (state.timeoutID) { clearTimeout(state.timeoutID) } return action.data case 'SET_TIMEOUTID': return { ...state, timeoutID: action.timeoutID } default: return state } } export default notificationReducerconsole.log('leListeStr main01 start json de data maDataBlocs'); var maDataBlocs = { "data00" : { "fic1" : "./qc/apps/lib/http_server.c.html" , "texte" : "File apps/lib/http_server.c 131 rule violations " , "fic2" : "./qc/apps/lib/http_server.c.xml" , "fic3" : "" } , "data01" : [ ] , "data02" : [ ] , "data03" : [ ] , "data04" : [ ] , "data05" : [ ] , "data06" : [ ] , "data07" : [ ] , "data08" : [ ] , "data11" : [ ] , "data14" : [ ] , "data13a" : [ { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000005" , "c3" : "Check pointer declaration to unsigned char" , "c4" : "2" }} , { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000006" , "c3" : "Risk of infinite while loop" , "c4" : "2" }} , { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000011" , "c3" : "The condition expression on a single value can be confusing" , "c4" : "23" }} , { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000012" , "c3" : "The condition expression is invariable, always true or false" , "c4" : "62" }} , { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000015" , "c3" : "Suspicious use of a negative array index" , "c4" : "3" }} , { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000018" , "c3" : "A suspicious bitwise expression is compared to a numerical expression" , "c4" : "3" }} , { "ligne" : { "c1" : "MAJOR" , "c2" : "QC-CPP000007" , "c3" : "goto statement" , "c4" : "17" }} , { "ligne" : { "c1" : "MAJOR" , "c2" : "QC-CPPCWE481" , "c3" : "Assigning instead of comparing" , "c4" : "11" }} , { "ligne" : { "c1" : "MAJOR" , "c2" : "QC-CPP000014" , "c3" : "A pointer is defined but not initialized" , "c4" : "8" }} ] , "data13b" : [ { "ligne" : { "c1" : "01562" , "c1link" : "./qc/apps/lib/http_server.c.html#1562" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[01562] The pointer __p is declared but not initialized" }} , { "ligne" : { "c1" : "01725" , "c1link" : "./qc/apps/lib/http_server.c.html#1725" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01725] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01728" , "c1link" : "./qc/apps/lib/http_server.c.html#1728" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01728] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01752" , "c1link" : "./qc/apps/lib/http_server.c.html#1752" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01752] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01754" , "c1link" : "./qc/apps/lib/http_server.c.html#1754" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[01754] The expression ! __builtin_constant_p(__buflen) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "01756" , "c1link" : "./qc/apps/lib/http_server.c.html#1756" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01756] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01778" , "c1link" : "./qc/apps/lib/http_server.c.html#1778" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01778] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01778" , "c1link" : "./qc/apps/lib/http_server.c.html#1778" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01778] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01802" , "c1link" : "./qc/apps/lib/http_server.c.html#1802" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01802] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01804" , "c1link" : "./qc/apps/lib/http_server.c.html#1804" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[01804] The expression ! __builtin_constant_p(__len) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "01808" , "c1link" : "./qc/apps/lib/http_server.c.html#1808" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01808] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01833" , "c1link" : "./qc/apps/lib/http_server.c.html#1833" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01833] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "01835" , "c1link" : "./qc/apps/lib/http_server.c.html#1835" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[01835] The expression ! __builtin_constant_p(__len) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "01837" , "c1link" : "./qc/apps/lib/http_server.c.html#1837" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01837] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "02858" , "c1link" : "./qc/apps/lib/http_server.c.html#2858" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02858] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "02863" , "c1link" : "./qc/apps/lib/http_server.c.html#2863" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02863] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "02888" , "c1link" : "./qc/apps/lib/http_server.c.html#2888" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02888] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "02892" , "c1link" : "./qc/apps/lib/http_server.c.html#2892" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[02892] Suspicious mix of Bitwise and Literal expressions in (__size|__n)>=(((size_t )1)<<(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "02895" , "c1link" : "./qc/apps/lib/http_server.c.html#2895" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02895] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "02920" , "c1link" : "./qc/apps/lib/http_server.c.html#2920" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02920] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "02924" , "c1link" : "./qc/apps/lib/http_server.c.html#2924" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[02924] Suspicious mix of Bitwise and Literal expressions in (__size|__n)>=(((size_t )1)<<(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "02928" , "c1link" : "./qc/apps/lib/http_server.c.html#2928" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02928] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "02936" , "c1link" : "./qc/apps/lib/http_server.c.html#2936" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[02936] Suspicious mix of Bitwise and Literal expressions in (__size|__n)<(((size_t )1)<<(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "05664" , "c1link" : "./qc/apps/lib/http_server.c.html#5664" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05664] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "05666" , "c1link" : "./qc/apps/lib/http_server.c.html#5666" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[05666] The expression ! __builtin_constant_p(__nbytes) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "05669" , "c1link" : "./qc/apps/lib/http_server.c.html#5669" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05669] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "05694" , "c1link" : "./qc/apps/lib/http_server.c.html#5694" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05694] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05696" , "c1link" : "./qc/apps/lib/http_server.c.html#5696" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[05696] The expression ! __builtin_constant_p(__len) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "05699" , "c1link" : "./qc/apps/lib/http_server.c.html#5699" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05699] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05728" , "c1link" : "./qc/apps/lib/http_server.c.html#5728" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05728] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05730" , "c1link" : "./qc/apps/lib/http_server.c.html#5730" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[05730] The expression ! __builtin_constant_p(__len) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "05733" , "c1link" : "./qc/apps/lib/http_server.c.html#5733" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05733] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05754" , "c1link" : "./qc/apps/lib/http_server.c.html#5754" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05754] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05756" , "c1link" : "./qc/apps/lib/http_server.c.html#5756" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[05756] The expression ! __builtin_constant_p(__size) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "05759" , "c1link" : "./qc/apps/lib/http_server.c.html#5759" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05759] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05775" , "c1link" : "./qc/apps/lib/http_server.c.html#5775" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05775] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05794" , "c1link" : "./qc/apps/lib/http_server.c.html#5794" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05794] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05796" , "c1link" : "./qc/apps/lib/http_server.c.html#5796" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[05796] The expression ! __builtin_constant_p(__len) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "05799" , "c1link" : "./qc/apps/lib/http_server.c.html#5799" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05799] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05819" , "c1link" : "./qc/apps/lib/http_server.c.html#5819" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05819] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05824" , "c1link" : "./qc/apps/lib/http_server.c.html#5824" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05824] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05845" , "c1link" : "./qc/apps/lib/http_server.c.html#5845" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05845] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05847" , "c1link" : "./qc/apps/lib/http_server.c.html#5847" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[05847] The expression ! __builtin_constant_p(__buflen) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "05850" , "c1link" : "./qc/apps/lib/http_server.c.html#5850" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05850] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05871" , "c1link" : "./qc/apps/lib/http_server.c.html#5871" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05871] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05873" , "c1link" : "./qc/apps/lib/http_server.c.html#5873" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[05873] The expression ! __builtin_constant_p(__buflen) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "05876" , "c1link" : "./qc/apps/lib/http_server.c.html#5876" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05876] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05898" , "c1link" : "./qc/apps/lib/http_server.c.html#5898" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05898] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05900" , "c1link" : "./qc/apps/lib/http_server.c.html#5900" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[05900] The expression ! __builtin_constant_p(__buflen) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "05903" , "c1link" : "./qc/apps/lib/http_server.c.html#5903" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05903] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05927" , "c1link" : "./qc/apps/lib/http_server.c.html#5927" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05927] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "05929" , "c1link" : "./qc/apps/lib/http_server.c.html#5929" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[05929] The expression ! __builtin_constant_p(__buflen) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "05932" , "c1link" : "./qc/apps/lib/http_server.c.html#5932" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[05932] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "06297" , "c1link" : "./qc/apps/lib/http_server.c.html#6297" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[06297] The expression 2>1 is invariable" }} , { "ligne" : { "c1" : "07629" , "c1link" : "./qc/apps/lib/http_server.c.html#7629" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[07629] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "07631" , "c1link" : "./qc/apps/lib/http_server.c.html#7631" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[07631] The expression ! __builtin_constant_p(__n) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "07634" , "c1link" : "./qc/apps/lib/http_server.c.html#7634" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[07634] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "07660" , "c1link" : "./qc/apps/lib/http_server.c.html#7660" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[07660] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "07662" , "c1link" : "./qc/apps/lib/http_server.c.html#7662" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[07662] The expression ! __builtin_constant_p(__n) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "07665" , "c1link" : "./qc/apps/lib/http_server.c.html#7665" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[07665] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "09065" , "c1link" : "./qc/apps/lib/http_server.c.html#9065" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[09065] The expression __builtin_constant_p(__oflag) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "09098" , "c1link" : "./qc/apps/lib/http_server.c.html#9098" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[09098] The expression __builtin_constant_p(__oflag) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "21012" , "c1link" : "./qc/apps/lib/http_server.c.html#21012" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[21012] The expression multi applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "21106" , "c1link" : "./qc/apps/lib/http_server.c.html#21106" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[21106] The expression setpgid(0,0) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "21106" , "c1link" : "./qc/apps/lib/http_server.c.html#21106" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21106] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "21106" , "c1link" : "./qc/apps/lib/http_server.c.html#21106" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21106] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "21142" , "c1link" : "./qc/apps/lib/http_server.c.html#21142" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21142] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21224" , "c1link" : "./qc/apps/lib/http_server.c.html#21224" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[21224] The expression * __errno_location() applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "21243" , "c1link" : "./qc/apps/lib/http_server.c.html#21243" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[21243] The expression termsig applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "21246" , "c1link" : "./qc/apps/lib/http_server.c.html#21246" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21246] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21271" , "c1link" : "./qc/apps/lib/http_server.c.html#21271" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[21271] The expression termsig applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "21319" , "c1link" : "./qc/apps/lib/http_server.c.html#21319" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[21319] The pointer bufbio is declared but not initialized" }} , { "ligne" : { "c1" : "21328" , "c1link" : "./qc/apps/lib/http_server.c.html#21328" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21328] goto statement jump to err" }} , { "ligne" : { "c1" : "21335" , "c1link" : "./qc/apps/lib/http_server.c.html#21335" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21335] The expression 131 is invariable" }} , { "ligne" : { "c1" : "21335" , "c1link" : "./qc/apps/lib/http_server.c.html#21335" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21335] The expression 0x01 is invariable" }} , { "ligne" : { "c1" : "21340" , "c1link" : "./qc/apps/lib/http_server.c.html#21340" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21340] The expression 118 is invariable" }} , { "ligne" : { "c1" : "21340" , "c1link" : "./qc/apps/lib/http_server.c.html#21340" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21340] The expression 1 is invariable, always true" }} , { "ligne" : { "c1" : "21346" , "c1link" : "./qc/apps/lib/http_server.c.html#21346" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21346] goto statement jump to err" }} , { "ligne" : { "c1" : "21355" , "c1link" : "./qc/apps/lib/http_server.c.html#21355" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21355] The expression 101 is invariable" }} , { "ligne" : { "c1" : "21355" , "c1link" : "./qc/apps/lib/http_server.c.html#21355" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21355] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "21365" , "c1link" : "./qc/apps/lib/http_server.c.html#21365" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21365] goto statement jump to err" }} , { "ligne" : { "c1" : "21370" , "c1link" : "./qc/apps/lib/http_server.c.html#21370" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[21370] The expression ! report_server_accept(bio_out,asock,1,1) applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "21370" , "c1link" : "./qc/apps/lib/http_server.c.html#21370" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21370] The expression 1 is invariable, always true" }} , { "ligne" : { "c1" : "21370" , "c1link" : "./qc/apps/lib/http_server.c.html#21370" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21370] The expression 1 is invariable, always true" }} , { "ligne" : { "c1" : "21376" , "c1link" : "./qc/apps/lib/http_server.c.html#21376" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21376] goto statement jump to err" }} , { "ligne" : { "c1" : "21396" , "c1link" : "./qc/apps/lib/http_server.c.html#21396" , "c2" : "BLOCKER" , "c3" : "QC-CPP000005[21396] Suspicious declaration of a pointer to unsigned char, in case of memcpy" }} , { "ligne" : { "c1" : "21397" , "c1link" : "./qc/apps/lib/http_server.c.html#21397" , "c2" : "BLOCKER" , "c3" : "QC-CPP000005[21397] Suspicious declaration of a pointer to unsigned char, in case of memcpy" }} , { "ligne" : { "c1" : "21399" , "c1link" : "./qc/apps/lib/http_server.c.html#21399" , "c2" : "BLOCKER" , "c3" : "QC-CPP000011[21399] The expression * p applies to a single value or variable, might be ambiguous." }} , { "ligne" : { "c1" : "21450" , "c1link" : "./qc/apps/lib/http_server.c.html#21450" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[21450] The pointer meth is declared but not initialized" }} , { "ligne" : { "c1" : "21450" , "c1link" : "./qc/apps/lib/http_server.c.html#21450" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[21450] The pointer url is declared but not initialized" }} , { "ligne" : { "c1" : "21450" , "c1link" : "./qc/apps/lib/http_server.c.html#21450" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[21450] The pointer end is declared but not initialized" }} , { "ligne" : { "c1" : "21451" , "c1link" : "./qc/apps/lib/http_server.c.html#21451" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[21451] The pointer req is declared but not initialized" }} , { "ligne" : { "c1" : "21481" , "c1link" : "./qc/apps/lib/http_server.c.html#21481" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21481] The expression 101 is invariable" }} , { "ligne" : { "c1" : "21481" , "c1link" : "./qc/apps/lib/http_server.c.html#21481" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21481] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "21489" , "c1link" : "./qc/apps/lib/http_server.c.html#21489" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21489] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21504" , "c1link" : "./qc/apps/lib/http_server.c.html#21504" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21504] goto statement jump to out" }} , { "ligne" : { "c1" : "21526" , "c1link" : "./qc/apps/lib/http_server.c.html#21526" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21526] goto statement jump to out" }} , { "ligne" : { "c1" : "21528" , "c1link" : "./qc/apps/lib/http_server.c.html#21528" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21528] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21533" , "c1link" : "./qc/apps/lib/http_server.c.html#21533" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21533] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21545" , "c1link" : "./qc/apps/lib/http_server.c.html#21545" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21545] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21546" , "c1link" : "./qc/apps/lib/http_server.c.html#21546" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21546] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21547" , "c1link" : "./qc/apps/lib/http_server.c.html#21547" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21547] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21550" , "c1link" : "./qc/apps/lib/http_server.c.html#21550" , "c2" : "BLOCKER" , "c3" : "QC-CPP000015[21550] Suspicion use of negative array index -1" }} , { "ligne" : { "c1" : "21562" , "c1link" : "./qc/apps/lib/http_server.c.html#21562" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21562] goto statement jump to out" }} , { "ligne" : { "c1" : "21579" , "c1link" : "./qc/apps/lib/http_server.c.html#21579" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21579] goto statement jump to out" }} , { "ligne" : { "c1" : "21595" , "c1link" : "./qc/apps/lib/http_server.c.html#21595" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21595] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "21597" , "c1link" : "./qc/apps/lib/http_server.c.html#21597" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21597] goto statement jump to out" }} , { "ligne" : { "c1" : "21610" , "c1link" : "./qc/apps/lib/http_server.c.html#21610" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21610] goto statement jump to out" }} , { "ligne" : { "c1" : "21613" , "c1link" : "./qc/apps/lib/http_server.c.html#21613" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21613] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21618" , "c1link" : "./qc/apps/lib/http_server.c.html#21618" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21618] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21630" , "c1link" : "./qc/apps/lib/http_server.c.html#21630" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21630] goto statement jump to fatal" }} , { "ligne" : { "c1" : "21644" , "c1link" : "./qc/apps/lib/http_server.c.html#21644" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21644] goto statement jump to out" }} , { "ligne" : { "c1" : "21650" , "c1link" : "./qc/apps/lib/http_server.c.html#21650" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21650] The expression - 2 is invariable" }} , { "ligne" : { "c1" : "21650" , "c1link" : "./qc/apps/lib/http_server.c.html#21650" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21650] The expression - 1 is invariable" }} , { "ligne" : { "c1" : "21650" , "c1link" : "./qc/apps/lib/http_server.c.html#21650" , "c2" : "BLOCKER" , "c3" : "QC-CPP000015[21650] Suspicion use of negative array index -2" }} , { "ligne" : { "c1" : "21650" , "c1link" : "./qc/apps/lib/http_server.c.html#21650" , "c2" : "BLOCKER" , "c3" : "QC-CPP000015[21650] Suspicion use of negative array index -1" }} , { "ligne" : { "c1" : "21655" , "c1link" : "./qc/apps/lib/http_server.c.html#21655" , "c2" : "BLOCKER" , "c3" : "QC-CPP000006[21655] The condition of for loop is empty, infinite loop risk" }} , { "ligne" : { "c1" : "21655" , "c1link" : "./qc/apps/lib/http_server.c.html#21655" , "c2" : "BLOCKER" , "c3" : "QC-CPP000006[21655] The end expression of for loop is empty, infinite loop risk" }} , { "ligne" : { "c1" : "21656" , "c1link" : "./qc/apps/lib/http_server.c.html#21656" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[21656] The pointer key is declared but not initialized" }} , { "ligne" : { "c1" : "21656" , "c1link" : "./qc/apps/lib/http_server.c.html#21656" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[21656] The pointer value is declared but not initialized" }} , { "ligne" : { "c1" : "21670" , "c1link" : "./qc/apps/lib/http_server.c.html#21670" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21670] goto statement jump to out" }} , { "ligne" : { "c1" : "21673" , "c1link" : "./qc/apps/lib/http_server.c.html#21673" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21673] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "21673" , "c1link" : "./qc/apps/lib/http_server.c.html#21673" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21673] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "21690" , "c1link" : "./qc/apps/lib/http_server.c.html#21690" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21690] goto statement jump to out" }} , { "ligne" : { "c1" : "21714" , "c1link" : "./qc/apps/lib/http_server.c.html#21714" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21714] goto statement jump to out" }} , { "ligne" : { "c1" : "21723" , "c1link" : "./qc/apps/lib/http_server.c.html#21723" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21723] The expression 'Connection' is invariable" }} , { "ligne" : { "c1" : "21724" , "c1link" : "./qc/apps/lib/http_server.c.html#21724" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21724] The expression 'keep-alive' is invariable" }} , { "ligne" : { "c1" : "21726" , "c1link" : "./qc/apps/lib/http_server.c.html#21726" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[21726] The expression 'close' is invariable" }} , { "ligne" : { "c1" : "21763" , "c1link" : "./qc/apps/lib/http_server.c.html#21763" , "c2" : "MAJOR" , "c3" : "QC-CPPCWE481[21763] Assigning instead of comparing (see http://cwe.mitre.org/data/definitions/481.html)" }} , { "ligne" : { "c1" : "21775" , "c1link" : "./qc/apps/lib/http_server.c.html#21775" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21775] goto statement jump to fatal" }} , { "ligne" : { "c1" : "21810" , "c1link" : "./qc/apps/lib/http_server.c.html#21810" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[21810] goto statement jump to out" }} ] }; console.log('leListeStr 99 main end'); import {combineReducers} from "redux"; import categoryReducer from "./categoryReducer"; import resourceReducer from "./resourceReducer"; import usefulReducer from "./usefulReducer"; export default combineReducers({ category: categoryReducer, resource: resourceReducer, useful: usefulReducer, } )<reponame>luca3dan/games const keys = []; const speed = 16; var uiController = (function() { var msg = ["Bar to start", "Px Scores!", "Pxwins! Play again? [bar]"]; var el_msg = document.querySelector("#messaggio"); var el_score1 = document.querySelector("#player1score"); var el_score2 = document.querySelector("#player2score"); function updMsg() {} function updScore() {} function updVisibility(visibility) { if (visibility === 0) { el_msg.style.display = "none"; el_score1.style.display = "none"; el_score2.style.display = "none"; } else { el_msg.style.display = "block"; el_score1.style.display = "block"; el_score2.style.display = "block"; } } return { updateScore: function() { updScore(); }, updateMsg: function() { updMsg(); }, updateVisibility: function(visibility) { updVisibility(visibility); } }; })(); /*********************************************/ var elementController = (function() { // Costruttori e definizione dei metodi function Elemento(elemento) { this.elemento = elemento || ""; this.x = 0; this.y = 0; } function Palla(elemento) { Elemento.call(this, elemento); } function Player(elemento) { Elemento.call(this, elemento); this.cmdUp = ""; this.cmdDown = ""; this.score = 0; } Elemento.prototype.setCoord = function(x, y) { this.x = parseInt(x); this.y = parseInt(y); }; Player.prototype = Object.create(Elemento.prototype); Palla.prototype = Object.create(Elemento.prototype); Player.prototype.setComandi = function(cmdUp, cmdDown) { this.cmdUp = cmdUp; this.cmdDown = cmdDown; }; Player.prototype.update = function(speed) { if (keys[this.cmdUp]) { this.y = this.y - speed; this.elemento.style.top = this.y + "px"; } if (keys[this.cmdDown]) { this.y = this.y + speed; this.elemento.style.top = this.y + "px"; } }; Palla.prototype.update = function(speed) { //aggiornamento della posizione della palla }; // Crea gli oggetti var palla = new Palla(document.getElementById("palla")); var p1 = new Player(document.getElementById("player1")); var p2 = new Player(document.getElementById("player2")); //Assegna i comandi per lo spostamento dei giocatori p1.setComandi("65", "90"); // A & S p2.setComandi("83", "88"); // S & X // Spostamento degli elementi player p1.setCoord( window.getComputedStyle(p1.elemento).getPropertyValue("left"), window.getComputedStyle(p1.elemento).getPropertyValue("top") ); p2.setCoord( window.getComputedStyle(p2.elemento).getPropertyValue("left"), window.getComputedStyle(p2.elemento).getPropertyValue("top") ); // Metodi pubblici return { getElements: function() { return { p1: p1, p2: p2, palla: palla }; } }; })(); /*********************************************************************/ var gameController = (function(elementController, uiController) { var gameStatus = 0; var elements = elementController.getElements(); function setListener() { document.body.addEventListener("keydown", function(e) { keys[e.keyCode] = true; if (keys[32]) { setGameStatus(); setUI(); startGame(); } }); document.body.addEventListener("keyup", function(e) { keys[e.keyCode] = false; }); } function setGameStatus() { gameStatus = gameStatus === 1 ? 0 : 1; } function setUI() { let visibility = gameStatus === 1 ? 0 : 1; uiController.updateVisibility(visibility); //uiController.updateMsg(); } function startGame() { if (gameStatus === 1) loop(); } function loop() { if (gameStatus === 1) { //Spostamento dei giocatori elements.p1.update(speed); elements.p2.update(speed); // loop window.requestAnimationFrame(loop); } else if (gameStatus === 0) { return; } } return { init: function() { setListener(); }, startLoop() { loop(); } }; })(elementController, uiController); gameController.init(); import React, { Component } from 'react'; import PropTypes from 'prop-types'; // import Axios from 'axios'; // import { API_ERRORS_SCANR } from '../../../config/config'; import Errors from '../Errors/Errors'; class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError() { // Mettez à jour l'état, de façon à montrer l'UI de repli au prochain rendu. return { hasError: true }; } // componentDidCatch(error, info) { // // Vous pouvez aussi enregistrer l'erreur au sein d'un service de rapport. // const errorJSON = { // type: 'React boundary', // url: window.location.href.toString(), // agent: window.navigator.userAgent.toString(), // msg: error.toString(), // info: info.componentStack, // }; // Axios.post(API_ERRORS_SCANR, errorJSON); // } render() { if (this.state.hasError) { return <Errors error={500} />; } return this.props.children; } } export default ErrorBoundary; ErrorBoundary.propTypes = { children: PropTypes.node.isRequired, }; <filename>src/helper/tokenTransfer.js const { SYSVAR_RENT_PUBKEY, Transaction, TransactionInstruction, PublicKey, SystemProgram } = require('@solana/web3.js'); const { solana_program_id: { TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, SYSTEM_PROGRAM_ID } } = require('../config/index') const { transferChecked, assertOwner, memoInstruction } = require("./bufferInstructions") async function _createAssociatedTokenAccountIx( fundingAddress, walletAddress, splTokenMintAddress, ) { const associatedTokenAddress = await _findAssociatedTokenAddress( walletAddress, splTokenMintAddress, ); const systemProgramId = SYSTEM_PROGRAM_ID; const keys = [ { pubkey: fundingAddress, isSigner: true, isWritable: true, }, { pubkey: associatedTokenAddress, isSigner: false, isWritable: true, }, { pubkey: walletAddress, isSigner: false, isWritable: false, }, { pubkey: splTokenMintAddress, isSigner: false, isWritable: false, }, { pubkey: systemProgramId, isSigner: false, isWritable: false, }, { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false, }, { pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false, }, ]; const ix = new TransactionInstruction({ keys, programId: ASSOCIATED_TOKEN_PROGRAM_ID, data: Buffer.from([]), }); return [ix, associatedTokenAddress]; } async function _findAssociatedTokenAddress( walletAddress, tokenMintAddress, ) { return ( await PublicKey.findProgramAddress( [ walletAddress.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), tokenMintAddress.toBuffer(), ], ASSOCIATED_TOKEN_PROGRAM_ID, ) )[0]; } async function transferTokens({ connection, owner, sourcePublicKey, destinationPublicKey, amount, memo, mint, decimals, overrideDestinationCheck }, isMainnet) { let destinationAccountInfo = await connection.getAccountInfo(destinationPublicKey); if ( !!destinationAccountInfo && destinationAccountInfo.owner.equals(TOKEN_PROGRAM_ID) ) { return await _transferBetweenSplTokenAccounts({ connection, owner, mint, decimals, sourcePublicKey, destinationPublicKey, amount, memo, }); } if ( (!destinationAccountInfo || destinationAccountInfo.lamports === 0) && !overrideDestinationCheck ) { throw new Error('Cannot send to address with zero SOL balances'); } const destinationAssociatedTokenAddress = await _findAssociatedTokenAddress( destinationPublicKey, mint, ); destinationAccountInfo = await connection.getAccountInfo( destinationAssociatedTokenAddress, ); if ( !!destinationAccountInfo && destinationAccountInfo.owner.equals(TOKEN_PROGRAM_ID) ) { return await _transferBetweenSplTokenAccounts({ connection, owner, mint, decimals, sourcePublicKey, destinationPublicKey: destinationAssociatedTokenAddress, amount, memo, }); } return await _createAndTransferToAccount({ connection, owner, sourcePublicKey, destinationPublicKey, amount, memo, mint, decimals, }, isMainnet); } function _createTransferBetweenSplTokenAccountsInstruction({ ownerPublicKey, mint, decimals, sourcePublicKey, destinationPublicKey, amount, memo, }) { let transaction = new Transaction().add( transferChecked({ source: sourcePublicKey, mint, decimals, destination: destinationPublicKey, owner: ownerPublicKey, amount, }), ); if (memo) { transaction.add(memoInstruction(memo)); } return transaction; } async function _transferBetweenSplTokenAccounts({ connection, owner, mint, decimals, sourcePublicKey, destinationPublicKey, amount, memo, }) { const transaction = _createTransferBetweenSplTokenAccountsInstruction({ ownerPublicKey: owner.publicKey, mint, decimals, sourcePublicKey, destinationPublicKey, amount, memo, }); return transaction } async function _createAndTransferToAccount({ connection, owner, sourcePublicKey, destinationPublicKey, amount, memo, mint, decimals, }, isMainnet) { const [ createAccountInstruction, newAddress, ] = await _createAssociatedTokenAccountIx( owner.publicKey, destinationPublicKey, mint, ); let transaction = new Transaction(); if (isMainnet) transaction.add( assertOwner({ account: destinationPublicKey, owner: SYSTEM_PROGRAM_ID, }), ); transaction.add(createAccountInstruction); const transferBetweenAccountsTxn = _createTransferBetweenSplTokenAccountsInstruction( { ownerPublicKey: owner.publicKey, mint, decimals, sourcePublicKey, destinationPublicKey: newAddress, amount, memo, }, ); transaction.add(transferBetweenAccountsTxn); return transaction; } module.exports = transferTokens$(document).ready( function(){ var lineplotSensorObjectID; var yamlDropZone = document.getElementById('drag-and-drop'); yamlDropZone.addEventListener('dragover', handleDragOver, false); yamlDropZone.addEventListener('drop', handleFileSelect, false); } ) $(document).on('click', '#logoutButton', function() { window.location.href = "/logout"; }); $(document).on('click','#btnLineplotClose', function() { hideLineplot(); }); $(document).on('click', '.widget-feature', function() { showLineplot(); var featureID = this.id; var focus = featureID.split("/")[0]; var sensorObjectID = featureID.split("/")[1]; lineplotSensorObjectID = sensorObjectID; // var endtime = 1507216072; var endtime = moment().format('X'); // use 12h window as default var starttime = endtime - 43200; getChartData(sensorObjectID, starttime, endtime, function(response){ var csv = response.docs; updateLinePlot(csv,focus,'24h'); }); }); $(document).on('click','#btn24h', function(){ if ($("#lineplot").is(":hidden")){ }else{ var sensorObjectID = lineplotSensorObjectID; var endtime = moment().format('X'); var starttime = endtime - 86400; getChartData(sensorObjectID, starttime, endtime, function(response){ var csv = response.docs; updateLinePlot(csv,focus,'24h'); }); } }); $(document).on('click','#btn48h', function(){ if ($("#lineplot").is(":hidden")){ }else{ var sensorObjectID = lineplotSensorObjectID; var endtime = moment().format('X'); var starttime = endtime - 172800; getChartData(sensorObjectID, starttime, endtime, function(response){ var csv = response.docs; updateLinePlot(csv,focus,'48h'); }); } }); $(document).on('click','#btn1w', function(){ if ($("#lineplot").is(":hidden")){ }else{ var sensorObjectID = lineplotSensorObjectID; var endtime = moment().format('X'); var starttime = endtime - 604800; getChartData(sensorObjectID, starttime, endtime, function(response){ var csv = response.docs; updateLinePlot(csv,focus,'1w'); }); } }); $(document).on('click','#btn1m', function(){ if ($("#lineplot").is(":hidden")){ }else{ var sensorObjectID = lineplotSensorObjectID; var endtime = moment().format('X'); var starttime = endtime - 2419200; getChartData(sensorObjectID, starttime, endtime, function(response){ var csv = response.docs; updateLinePlot(csv,focus,'1m'); }); } }); function handleFileSelect(evt) { evt.stopPropagation(); evt.preventDefault(); var files = evt.dataTransfer.files; for (var i = 0, f; f = files[i]; i++) { var output = []; output.push('<strong>', escape(f.name),); var reader = new FileReader(); reader.onload = function(){ var yaml = reader.result; try { var docs_yaml = jsyaml.loadAll(yaml, 'utf8'); var doc_yaml = docs_yaml[0]; var starttime = parseYamlTime(doc_yaml['Micro-Manager Metadata']['receivedTime']); //calculate imaging time using number of frames and exposure time per frame var endtime = parseInt(starttime) + (parseInt(doc_yaml['Frames'] * (doc_yaml['Micro-Manager Metadata']['Exposure-ms'])/1000)); getSensorID(doc_yaml["Micro-Manager Metadata"]["Microscope-Label"], function(sensorObjectID, err){ if(err){ window.alert("No sensor found.") }else if(sensorObjectID){ getChartData(sensorObjectID, starttime, endtime, function(response){ var csv = response.docs; updateLinePlot(csv,focus,'yaml'); }); } }) } catch (e) { console.log(e); } }; var doc = reader.readAsText(f); } document.getElementById('yaml-list').innerHTML = 'yaml file: ' + output.join(''); } function parseYamlTime(time){ // prepare Micromanager Timestamp for moment.js formatting var times = time.split(" "); var timestamp = moment(times[0]+"T"+times[1]+times[2]).format('X'); return(timestamp) } function handleDragOver(evt) { evt.stopPropagation(); evt.preventDefault(); evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy. } function showLineplot(){ if ($( "#container-lineplot" ).is( ":hidden" )){ $( "#container-lineplot" ).slideDown(); } } function hideLineplot(){ if($("#container-lineplot").not(":hidden")){ $("#container-lineplot").slideUp(); } } function getSensorID(sensorLocation, callback){ if(sensors[sensorLocation] == undefined){ callback(null,true); }else{ callback(sensors[sensorLocation], null); } } function getChartData(sensorObjectID, starttime, endtime, callback){ if ($( "#lineplot" ).is( ":hidden" )){ showLineplot() } var url = '/get/ChartData/' + sensorObjectID + '/'+starttime+'-'+endtime; $.get(url, function( response ) { if(response.status == 'ok'){ callback(response); } }); } function updateLinePlot(csv, focus, timespan){ if(focus=="t"){ var visTemp = true; var visPres = false; var visHum = false; }else if(focus =="p"){ var visTemp = false; var visPres = true; var visHum = false; }else if(focus =="h"){ var visTemp = false; var visPres = false; var visHum = true; }else{ var visTemp = true; var visPres = true; var visHum = true; } var temp = []; var pres = []; var hum = []; var time = []; // Split the lines var lines = csv.split('\n'); // Iterate over the lines and add categories or series $.each(lines, function(lineNo, line) { var items = line.split(','); // header line containes categories if (lineNo == 0) { } // the rest of the lines contain data with their name in the first // position else { $.each(items, function(itemNo, item) { if (itemNo == 0) { if (timespan == '24h' || timespan == '48h' || timespan == 'yaml'){ time.push(moment(item,'X').format("HH:mm")); }else if (timespan == '1w'){ time.push(moment(item,'X').format("dd, HH:mm")); }else if(timespan == '1m'){ time.push(moment(item,'X').format("dd, D MMM, HH:mm")); } } if (itemNo == 1){ // temperature temp.push(parseFloat(item)); } if (itemNo == 2){ // pressure pres.push(parseFloat(item)); } if (itemNo == 3){ // humidity hum.push(parseFloat(item)); } }); } }); var options = { chart: { renderTo: 'lineplot', zoomType: 'x' }, title: { text: '' }, credits: { enabled: false }, colors: ['#B25644', '#60708C', '#A18D76'], xAxis: [{ categories: time }], yAxis: [{ // Primary yAxis labels: { format: '{value}°C', }, title: { text: 'Temperature', }, opposite: false }, { // Secondary yAxis gridLineWidth: 1, title: { text: 'Pressure' }, labels: { format: '{value} mb' }, opposite: true }, { // Tertiary yAxis gridLineWidth: 1, opposite: true, title: { text: 'Humidity' }, labels: { format: '{value} %' } }], tooltip: { shared: true }, plotOptions: { areaspline: { fillOpacity: 0.1 } }, series: [ { name: 'Temp', type: 'areaspline', label: { enabled: false }, yAxis: 0, description: '', visible: visTemp, marker: { enabled: false }, data: temp, tooltip: { valueSuffix: ' °C' } }, { name: 'Pressure', type: 'spline', yAxis: 1, visible: visPres, data: pres, marker: { enabled: false }, tooltip: { valueSuffix: ' mb' } }, { name: 'Humidity', type: 'spline', yAxis: 2, visible: visHum, data: hum, marker: { enabled: false }, tooltip: { valueSuffix: ' %' } } ] }; // Create the chart var chart = new Highcharts.chart(options); } function initialize(){ }module.exports = function weather(controller, request, OpenweatherToken, http){ controller.hears(['weather in (.*)', 'weather of (.*)','(.*)\'s weather'], 'direct_message,direct_mention,mention', function(bot,message) { var city = message.match[1]; if(undefined === city || '' === city || null === city) { bot.reply(message,"Didn't you forgot the city name? I am really sorry, currently I can't guess your city."); } else{ var options = { protocol : 'http:', host : 'api.openweathermap.org', path : `/data/2.5/weather?q=${city.replace(" ","+")}&appid=${OpenweatherToken}`, port : 80, method : 'GET' }; var request = http.request(options, function(response){ response.on('data', function(data) { var weather = JSON.parse(data); var Temp= Math.round(weather.main.temp - 273.15) + '°C '; var msg="The Temp is "+ Temp + "and In " + city; switch(weather.weather[0].main) { case "Clear": bot.reply(message,`${msg} it's Clear Sky`); bot.reply(message,":mostly_sunny:"); bot.reply(message,"Its good idea to wear sunglasses before going out"); break; case "Clouds": case "Cloud": bot.reply(message,`${msg} it's Raining`); bot.reply(message,":cloud:"); bot.reply(message,"Better to carry an Umbrella"); break; case "Smoke": bot.reply(message,`${msg} it's Foggy`); bot.reply(message,":smoking:"); bot.reply("Wear Proper Face Mask before leaving home"); break; case "Rain": bot.reply(message,`${msg} It's Raining`); bot.reply(message,":rain_cloud:"); bot.reply(message,`Please carry umbrella if you are in ${city}`); break; case "Thunderstorm": bot.reply(message,`${msg} It's gonna Slackbe Thunderous Rain`); bot.reply(message,":thunder_cloud_and_rain:"); bot.reply(message,`Please don't go out if you are in ${city}`); break; case "Drizzle": bot.reply(message,`${msg} It's Drizzling`); bot.reply(message,":partly_sunny_rain:"); bot.reply(message,`Carry Umbrella it should be fine in ${city}`); break; case "Haze": bot.reply(message,`The Temp is ${Temp}`); bot.reply(message,":barely_sunny:"); bot.reply(message,`There would be partly sunny in ${city}`); break; case "Snow": bot.reply(message,`The Temp is ${Temp}`); bot.reply(message,":snow_cloud: :snowman:"); bot.reply(message,`Please wear Warm clothes those living in ${city}`); break; } }); response.on('end', function() { /*res.send(JSON.parse(body)) */ }); }); request.on('error', function(e) { console.log('Problem with request: ' + e.message); bot.reply(message, `sorry, couldn't find weather info for city ${city}`); }); request.end(); } }); controller.hears(['climate in (.*)','climate of (.*)','(.*)\'s climate'], 'direct_message,direct_mention,mention', function(bot,message) { var city = message.match[1]; if(undefined === city || '' === city || null === city) { bot.reply(message,"Didn't you forgot the city name? I am really sorry, currently I can't guess your city."); } else{ var options = { protocol: 'http:', host: 'api.openweathermap.org', path: '/data/2.5/weather?q=' + city.replace(" ", "+") + '&appid=' + OpenweatherToken, port: 80, method: 'GET' }; var request = http.request(options, function (response) { var bodycontent = ""; response.on('data', function (data) { bodycontent += data; var weather = JSON.parse(bodycontent); function LongLatcheck(a, status) { var n = a > 0 ? status === 'lat' ? a + "°N" : a + "°E" : status === 'lon' ? Math.abs(a) + "°W" : Math.abs(a) + "°S"; return n; } bot.reply(message, `Quick Fact: ${city} is located at ${LongLatcheck(weather.coord.lat, 'lat')} and ${LongLatcheck(weather.coord.lon, 'lon')}`); bot.reply(message, `Temperature Varies from ${Math.round(weather.main.temp_min - 273.15)}°C to ${Math.round(weather.main.temp_max - 273.15)} °C at this place`); }); response.on('end', function () { /*res.send(JSON.parse(body)) */ }); }); request.on('error', function (e) { console.log('Problem with request: ' + e.message); bot.reply(message, "sorry, couldn't find Temperature info for city " + timeloc); }); request.end(); } }); }import { useStateValue } from 'src/services/context' // TODO: Move this functionality elsewhere. ~ RM // TODO: Full CRUD UI for annotations, perhaps as seperate panel in addition to // map-based UI. Some way of browsing annotations would be helpful for // temporarily disabling, deleting ("WHERE on the map is it?"), and so on. ~ RM // TODO: Users may subscribe to sets of annotations from users and groups (ex: // "Here's the route I took to get around the counter-protests", "OrgX is pretty // good about indicating which Hong Kong subways are currently operational // and/or occupied by police, I'll subscribe to them as an individual and/or // have my group admin add them to the group subscriptions"). ~ RM const AnnotationMenu = () => { const [{ draw }] = useStateValue() return ( <Buttons> <Button className='fas fa-map-marker-alt' onClick={() => draw.changeMode('draw_point')} /> <Button className='fas fa-route' onClick={() => draw.changeMode('draw_line_string')} /> <Button className='fas fa-draw-polygon' onClick={() => draw.changeMode('draw_polygon')} /> </Buttons> ) } const Buttons = styled.div` bottom: 2rem; display: flex; justify-content: space-around; left: calc(50% - 5rem); position: absolute; width: 10rem; ` const Button = styled.button` background-color: black; border-radius: 50%; cursor: pointer; height: 2.5rem; width: 2.5rem; ` export default AnnotationMenu <filename>commands/ping.js<gh_stars>1-10 module.exports = { name: "ping", aliases: [], description: "ping pong", run: async (client, message) => { await message.channel.send("Pinging...") .then(m => m.edit(`Pong! Latency is ${m.createdTimestamp - message.createdTimestamp}ms`)); } }describe('Help command', () => { it('help()', () => { }); }); import React from 'react'; import Link from 'next/link'; const Page = () => ( <div> <span>hello page</span> <br /> <Link href="/hello"> <a>go /hello</a> </Link> <br /> <Link href="/hi"> <a>go /hi tsx</a> </Link> <br /> <Link href="/"> <a>go home</a> </Link> </div> ); export default Page; "use strict"; /* * @author electricessence / https://github.com/electricessence/ * @license MIT */ Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const aggregate_1 = tslib_1.__importDefault(require("./aggregate")); const a = aggregate_1.default((p) => p + 1, 0); /** * Returns the number of entries in a sequence. * @param {Iterable<T>} sequence * @return {number} */ function count(sequence) { if (sequence instanceof Array) return sequence.length; return sequence ? a(sequence) : 0; } exports.default = count; //# sourceMappingURL=count.js.mapimport {ADD_TO_CART, REMOVE_ITEM, SUB_QUANTITY, ADD_QUANTITY, EMPTY_CART} from "./cartActionsTypes" //add cart action export const addToCart = (item) => { return { type: ADD_TO_CART, item } } //remove item action export const removeItem = (item) => { return { type: REMOVE_ITEM, item } } //subtract qt action export const subtractQuantity = (item) => { return { type: SUB_QUANTITY, item } } //add qt action export const addQuantity = (item) => { return { type: ADD_QUANTITY, item } } //empty cart when leaving page export const emptyCart = () => { return { type: EMPTY_CART, } }const express = require('express'); const router = express.Router(); const Asset = require('../models/asset'); const mongoose = require('mongoose'); //Read router.get('/assets', (req, res) => { Asset.find() .then((allAssetsfromDB) => { res.status(200).json(allAssetsfromDB); }) .catch((error) => { res.status(500).json(`Error occurred ${error}`); }); }); //Create router.post('/assets', (req, res) => { const { name } = req.body; if (!name) { res.status(400).json('Missing fields'); } Asset.create({ name, owner: req.user._id }) .then((response) => { res.status(200).json(response); }) .catch((error) => { res.status(500).json(`Error occurred ${error}`); }); }); module.exports = router; import _ from 'lodash'; /** * Decorator that mixes any number of mixins together into the target. * * @param {...*} mixins The mixins * @returns {Function} */ export default function mixin(...mixins) { return function(target) { let a = _.assign(target.prototype, ...mixins); return a.prototype; } }<gh_stars>0 // @flow import { add } from 'biggystring' import { assert, expect } from 'chai' import { describe, it } from 'mocha' import { createStore } from 'redux' import { fakeUser, makeFakeContexts } from '../../../../src/edge-core-index.js' import { awaitState } from '../../../../src/util/redux/reaction.js' import { makeAssertLog } from '../../../assert-log.js' import { makeFakeCurrency, makeFakeCurrencyStore } from '../../../fake-plugins/fake-currency.js' import { fakeExchangePlugin } from '../../../fake-plugins/fake-exchange.js' function snooze (ms: number) { return new Promise(resolve => setTimeout(resolve, ms)) } async function makeFakeCurrencyWallet (store, callbacks) { const plugin = makeFakeCurrency(store) // Use `onKeyListChanged` to trigger checking for wallets: const trigger = createStore(state => null) callbacks = { ...callbacks, onKeyListChanged () { trigger.dispatch({ type: 'DUMMY' }) } } const [context] = makeFakeContexts({ localFakeUser: true, plugins: [plugin, fakeExchangePlugin] }) const account = await context.loginWithPIN(fakeUser.username, fakeUser.pin, { callbacks }) // Wait for the wallet to load: const walletInfo = account.getFirstWalletInfo('wallet:fakecoin') if (!walletInfo) throw new Error('Broken test account') return awaitState(trigger, state => account.currencyWallets[walletInfo.id]) } describe('currency wallets', function () { it('can be created', function () { return makeFakeCurrencyWallet().then(wallet => assert.equal(wallet.name, 'Fake Wallet') ) }) it('can be renamed', function () { return makeFakeCurrencyWallet().then(wallet => wallet .renameWallet('Another Name') .then(() => assert.equal(wallet.name, 'Another Name')) ) }) it('triggers callbacks', async function () { const log = makeAssertLog(true) const store = makeFakeCurrencyStore() const callbacks = { onAddressesChecked (walletId, progress) { log('progress', progress) }, onBalanceChanged (walletId, currencyCode, balance) { log('balance', currencyCode, balance) }, onBlockHeightChanged (walletId, blockHeight) { log('blockHeight', blockHeight) }, onNewTransactions (walletId, txs) { txs.map(tx => log('new', tx.txid)) }, onTransactionsChanged (walletId, txs) { txs.map(tx => log('changed', tx.txid)) } } const wallet = await makeFakeCurrencyWallet(store, callbacks) let txState = [] log.assert(['balance TEST 0', 'blockHeight 0', 'progress 0']) const snoozeTimeMs = 251 await snooze(snoozeTimeMs) log.assert(['balance TOKEN 0']) await snooze(snoozeTimeMs) store.dispatch({ type: 'SET_TOKEN_BALANCE', payload: 30 }) log.assert(['balance TOKEN 30']) store.dispatch({ type: 'SET_BLOCK_HEIGHT', payload: 200 }) log.assert(['blockHeight 200']) assert.equal(wallet.getBlockHeight(), 200) await snooze(snoozeTimeMs) store.dispatch({ type: 'SET_PROGRESS', payload: 0.123456789 }) log.assert(['progress 0.123456789']) store.dispatch({ type: 'SET_BALANCE', payload: 1234567890 }) log.assert(['balance TEST 1234567890']) // New transactions: txState = [ { txid: 'a', amountSatoshi: 1 }, { txid: 'b', nativeAmount: '100' } ] store.dispatch({ type: 'SET_TXS', payload: txState }) log.assert(['new a', 'new b']) await snooze(snoozeTimeMs) // Should not trigger: store.dispatch({ type: 'SET_TXS', payload: txState }) log.assert([]) await snooze(snoozeTimeMs) // Changed transactions: txState = [ ...txState, { txid: 'a', nativeAmount: '2' }, { txid: 'c', nativeAmount: '200' } ] store.dispatch({ type: 'SET_TXS', payload: txState }) log.assert(['changed a', 'new c']) await snooze(snoozeTimeMs) txState = [{ txid: 'd', nativeAmount: '200' }] store.dispatch({ type: 'SET_TXS', payload: txState }) log.assert(['new d']) // Make several changes in a row which should get batched into one call due to throttling txState = [{ txid: 'e', nativeAmount: '200' }] store.dispatch({ type: 'SET_TXS', payload: txState }) txState = [{ txid: 'f', nativeAmount: '200' }] store.dispatch({ type: 'SET_TXS', payload: txState }) txState = [{ txid: 'g', nativeAmount: '200' }] store.dispatch({ type: 'SET_TXS', payload: txState }) await snooze(snoozeTimeMs) log.assert(['new e', 'new f', 'new g']) }) it('handles tokens', function () { const store = makeFakeCurrencyStore() return makeFakeCurrencyWallet(store).then(wallet => { const txs = [ { txid: 'a', currencyCode: 'TEST', nativeAmount: '2' }, { txid: 'b', currencyCode: 'TOKEN', nativeAmount: '200' } ] store.dispatch({ type: 'SET_TXS', payload: txs }) return Promise.resolve() .then(() => wallet.getTransactions({}).then(txs => { assert.equal(txs.length, 1) assert.equal(txs[0].txid, 'a') assert.strictEqual(txs[0].nativeAmount, '2') assert.strictEqual(txs[0].amountSatoshi, 2) return null }) ) .then(() => wallet.getTransactions({ currencyCode: 'TOKEN' }).then(txs => { assert.equal(txs.length, 1) assert.equal(txs[0].txid, 'b') assert.strictEqual(txs[0].nativeAmount, '200') assert.strictEqual(txs[0].amountSatoshi, 200) return null }) ) }) }) it('get max spendable', async function () { const store = makeFakeCurrencyStore() store.dispatch({ type: 'SET_BALANCE', payload: 50 }) const wallet = await makeFakeCurrencyWallet(store) const maxSpendable = await wallet.getMaxSpendable({ currencyCode: 'TEST', spendTargets: [{}] }) expect(maxSpendable).to.equal('50') const fulfill = () => 'FULFILL' const reject = () => 'REJECT' const fulfilResult = await wallet .makeSpend({ currencyCode: 'TEST', spendTargets: [{ nativeAmount: maxSpendable }] }) .then(fulfill, reject) expect(fulfilResult).to.equal('FULFILL') const rejectResult = await wallet .makeSpend({ currencyCode: 'TEST', spendTargets: [{ nativeAmount: add(maxSpendable, '1') }] }) .then(fulfill, reject) expect(rejectResult).to.equal('REJECT') }) // it('can have metadata', function () { // const store = makeFakeCurrencyStore() // // return makeFakeCurrencyWallet(store).then(wallet => { // const tx = { txid: 'a', metadata: { name: 'me' } } // store.dispatch({ // type: 'SET_TXS', // payload: [{ txid: 'a', nativeAmount: '25' }] // }) // return wallet.saveTx(tx).then(() => // wallet.getTransactions({}).then(txs => { // assert.equal(txs.length, 1) // assert.strictEqual(txs[0].metadata.name, tx.metadata.name) // assert.strictEqual(txs[0].metadata.amountFiat, 0.75) // assert.strictEqual(txs[0].amountSatoshi, 25) // assert.strictEqual(txs[0].nativeAmount, '25') // return null // }) // ) // }) // }) }) import { getCommonCard, getCommonTitle, getTextField, getSelectField, getCommonContainer, getCommonParagraph, getPattern, getDateField, getLabel } from "egov-ui-framework/ui-config/screens/specs/utils"; import { handleScreenConfigurationFieldChange as handleField } from "egov-ui-framework/ui-redux/screen-configuration/actions"; import { searchApiCall } from "./searchFunctions"; import get from "lodash/get"; import { displayCustomErr, displayDefaultErr } from "../../utils"; const searchBy = { uiFramework: "custom-containers", componentPath: "RadioGroupContainer", gridDefination: { xs: 12, sm: 12, }, props: { label: { name: "Search By", key: "ES_SEARCH_BY_LABEL" }, buttons: [{ labelName: "File No.", labelKey: "ES_FILE_NUMBER_LABEL", value: "File Number" }, { label: "Site No.", labelKey: "ES_SITE_NUMBER_LABEL", value: "Site Number" } ], value: "File Number", jsonPath: "citizenSearchScreen.searchBy", required: true }, required: true, jsonPath: "citizenSearchScreen.searchBy", beforeFieldChange: (action, state, dispatch) => { if (action.value) { if (action.value == "File Number") { let siteNumberContainerItems = ["category", "subCategory", "siteNumber", "sectorNumber"]; dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.fileNumberContainer", "visible", true ) ) siteNumberContainerItems.map(item => { dispatch( handleField( "estate-branch-property-search", `components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.siteNumberContainer.children.${item}`, "visible", false ) ) }) } else { let siteNumberContainerItems = ["category", "siteNumber", "sectorNumber"]; dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.fileNumberContainer", "visible", false ) ) siteNumberContainerItems.map(item => { dispatch( handleField( "estate-branch-property-search", `components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.siteNumberContainer.children.${item}`, "visible", true ) ) }) } } } }; export const estateApplication = getCommonCard({ subHeader: getCommonTitle({ labelName: "Search Estate", labelKey: "ES_HOME_SEARCH_RESULTS_HEADING" }), subParagraph: getCommonParagraph({ labelName: "Provide at least one parameter to search for a property", labelKey: "ES_HOME_SEARCH_RESULTS_DESC" }), searchBoxContainer: getCommonContainer({ searchBy: searchBy, fileNumberContainer: getCommonContainer({ fileNumber: getTextField({ label: { labelName: "File No.", labelKey: "ES_FILE_NUMBER_LABEL" }, placeholder: { labelName: "Enter File No.", labelKey: "ES_FILE_NUMBER_PLACEHOLDER" }, gridDefination: { xs: 12, sm: 4 }, required: true, // pattern: /^[a-zA-Z0-9-]*$/i, minLength: 1, maxLength: 50, errorMessage: "ES_ERR_INVALID_FILE_NO", jsonPath: "searchScreenFileNo.fileNumber", afterFieldChange: (action, state, dispatch) => { if (action.value.length > 50) { displayCustomErr(action.componentJsonpath, dispatch, "ES_ERR_MAXLENGTH_50", "estate-branch-property-search"); } else { displayDefaultErr(action.componentJsonpath, dispatch, "estate-branch-property-search"); } } }) }), siteNumberContainer: getCommonContainer({ category: getSelectField({ label: { labelName: "Category", labelKey: "ES_CATEGORY_LABEL" }, placeholder: { labelName: "Select Category", labelKey: "ES_CATEGORY_PLACEHOLDER" }, visible: false, required: true, jsonPath: "searchScreenSiteNo.category", sourceJsonPath: "searchScreenMdmsData.EstateServices.categories", gridDefination: { xs: 12, sm: 6 }, beforeFieldChange: (action, state, dispatch) => { if (action.value == "CAT.RESIDENTIAL" || action.value == "CAT.COMMERCIAL") { dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.siteNumberContainer.children.subCategory", "visible", true ) ); const categories = get( state.screenConfiguration.preparedFinalObject, "searchScreenMdmsData.EstateServices.categories" ) const filteredCategory = categories.filter(item => item.code === action.value) dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.siteNumberContainer.children.subCategory", "props.data", filteredCategory[0].SubCategory ) ) } else { dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.siteNumberContainer.children.subCategory", "visible", false ) ); } } }), subCategory: getSelectField({ label: { labelName: "Sub Category", labelKey: "ES_SUBCATEGORY_LABEL" }, placeholder: { labelName: "Select Sub Category", labelKey: "ES_SUBCATEGORY_PLACEHOLDER" }, required: true, jsonPath: "searchScreenSiteNo.subCategory", visible: false, gridDefination: { xs: 12, sm: 6 } }), siteNumber: getTextField({ label: { labelName: "Site Number", labelKey: "ES_SITE_NUMBER_LABEL" }, errorMessage: "ES_ERR_MAXLENGTH_50", placeholder: { labelName: "Enter Site Number", labelKey: "ES_SITE_NUMBER_PLACEHOLDER" }, gridDefination: { xs: 12, sm: 6 }, required: true, visible: false, minLength: 1, maxLength: 50, jsonPath: "searchScreenSiteNo.siteNumber" }), sectorNumber: getSelectField({ label: { labelName: "Sector Number", labelKey: "ES_SECTOR_NUMBER_LABEL" }, placeholder: { labelName: "Select Sector Number", labelKey: "ES_SECTOR_NUMBER_PLACEHOLDER" }, // required: true, visible: false, jsonPath: "searchScreenSiteNo.sectorNumber", sourceJsonPath: "searchScreenMdmsData.EstateServices.sector", gridDefination: { xs: 12, sm: 6 } }), }) }), button: getCommonContainer({ buttonContainer: getCommonContainer({ resetButton: { componentPath: "Button", gridDefination: { xs: 6, sm: 6 }, props: { variant: "outlined", style: { color: "rgba(0, 0, 0, 0.6000000238418579)", borderColor: "rgba(0, 0, 0, 0.6000000238418579)", width: "70%", height: "48px", margin: "8px", float: "right" } }, children: { buttonLabel: getLabel({ labelName: "Reset", labelKey: "ES_HOME_SEARCH_RESULTS_BUTTON_RESET" }) }, onClickDefination: { action: "condition", callBack: resetFields } }, searchButton: { componentPath: "Button", gridDefination: { xs: 6, sm: 6 }, props: { variant: "contained", style: { color: "white", margin: "8px", backgroundColor: "rgba(0, 0, 0, 0.6000000238418579)", borderRadius: "2px", width: "70%", height: "48px" } }, children: { buttonLabel: getLabel({ labelName: "Search", labelKey: "ES_HOME_SEARCH_RESULTS_BUTTON_SEARCH" }) }, onClickDefination: { action: "condition", callBack: searchApiCall } } }) }) }); function resetFields(state, dispatch) { let fileNumber = get(state.screenConfiguration.preparedFinalObject, "searchScreenFileNo.fileNumber", ""); let category = get(state.screenConfiguration.preparedFinalObject, "searchScreenSiteNo.category", ""); let subCategory = get(state.screenConfiguration.preparedFinalObject, "searchScreenSiteNo.subCategory", ""); let siteNumber = get(state.screenConfiguration.preparedFinalObject, "searchScreenSiteNo.siteNumber", ""); let sectorNumber = get(state.screenConfiguration.preparedFinalObject, "searchScreenSiteNo.sectorNumber", ""); if (fileNumber) { dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.fileNumberContainer.children.fileNumber", "props.value", "" ) ) } if (category) { dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.siteNumberContainer.children.category", "props.value", "" ) ) } if (subCategory) { dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.siteNumberContainer.children.subCategory", "props.value", "" ) ) } if (siteNumber) { dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.siteNumberContainer.children.siteNumber", "props.value", "" ) ) } if (sectorNumber) { dispatch( handleField( "estate-branch-property-search", "components.div.children.estateApplication.children.cardContent.children.searchBoxContainer.children.siteNumberContainer.children.sectorNumber", "props.value", "" ) ) } }import ObservableList from '../../src/ObservableList'; describe('ObservableList', () => { it('is initially empty', () => { expect(new ObservableList().items).toEqual([]); }); it('gets set items', () => { let list = new ObservableList(); list.items = [1,2,3]; expect(list.items).toEqual([1,2,3]); }); it('emits event when set', () => { let list = new ObservableList(); let spy = {observer: () => false}; spyOn(spy, 'observer'); list.on('change', spy.observer); list.items = [1,2,3]; expect(spy.observer).toHaveBeenCalled(); }); it('supports moving items before other items', () => { let list = new ObservableList(); list.items = [0, 1, 2, 3, 4, 5]; list.moveBefore(4, 2); expect(list.items).toEqual([0, 1, 4, 2, 3, 5]); }); it('supports moving items forwards', () => { let list = new ObservableList(); list.items = [0, 1, 2, 3, 4, 5]; list.moveBefore(1, 4); expect(list.items).toEqual([0, 2, 3, 1, 4, 5]); }); it('does nothing when moveBefore gets two neighbors as parameters', () => { let list = new ObservableList(); list.items = [0, 1, 2, 3, 4, 5]; list.moveBefore(2, 3); expect(list.items).toEqual([0, 1, 2, 3, 4, 5]); }); it('supports moving items to the end', () => { let list = new ObservableList(); list.items = [0, 1, 2, 3, 4, 5]; list.moveToEnd(2); expect(list.items).toEqual([0, 1, 3, 4, 5, 2]); }); it('supports adding and removing items preserving their original order', () => { let list = new ObservableList(); list.items = [ 'first', 'second', 'third', 'fourth' ]; list.selectItemsPreserveOrder( [ 'fourth', 'second', 'fifth' ]); expect(list.items).toEqual([ 'second', 'fourth', 'fifth' ]); }); }); <filename>lib/async.js /** * Created by kayslay on 6/25/17. */ const fs = require('fs'); const {basename, extname, join, resolve} = require('path'); /** * @description The main export by async.js. * * This function handles imports asynchronously. * It can return a Promise Object or handle a callback depending on if the callback argument passed * is a string, or a function. * * If callback is a string, a Promise is returned. If it is a function, it will handle the function when it ] * is done. * * @param folder * @param options * @param callback * @return {Promise} */ module.exports = function (folder, options = {}, callback) { const option = configOptions(options); let count = 0; let Obj = {}; let __callback; return callbackOrPromise(typeof callback); /** * @description loops through the folder and imports all the js and json files * @param {String|String[]} folder */ function transverse(folder) { count++; fs.readdir(folder, function (err, files) { count--; if (err) return done(err); files.forEach((file) => { "use strict"; if (option.filters.test(file) && !option.exclude.test(file)) { if (!Obj[basename(folder)]) { Obj[basename(folder)] = {}; } Obj[basename(folder)][basename(file, extname(file))] = require(join(folder, file)); } else { const isDir = fs.statSync(join(folder, file)); if (isDir.isDirectory() && option.depth && !option.excludeDir.test(file)) { transverse(join(folder, file)); } } }); return done(null) }) } /** * @description this is called after the whole files has been gotten * @param {Error} err * @return {*} */ function done(err) { if (err) { return __callback(err); } "use strict"; if (count == 0) { return __callback(null, Obj) } } /** * @description decides if it should return a Promise or should call folderStringOrArray * @param {String} callbackType * @return {Promise} */ function callbackOrPromise(callbackType) { if (callbackType == 'function') { __callback = callback; return folderStringOrArray(folder) } else { return new Promise((resolve, reject) => { "use strict"; __callback = (err, obj) => err ? reject(err) : resolve(obj); return folderStringOrArray(folder) }) } } /** * @description how it will call transverse if folder is either a string or an an Array * @param {String|String[]} folder */ function folderStringOrArray(folder) { if (typeof folder == "string") { transverse(resolve(folder)); } else { folder.forEach(f => transverse(resolve(f))) } } }; function configOptions(options) { return Object.assign({ filters: /(\.js|\.json)$/, exclude: /^\.\.?$/, depth: false, excludeDir: /^\.\.$/ }, options) }var dir_2427228f9b0744d1c58f918c9ac2dfd0 = [ [ "Factory", "dir_5d499acfc7547694260f927ec9156b1e.html", "dir_5d499acfc7547694260f927ec9156b1e" ], [ "Formatter", "dir_9fe753c651ed678e5cb81cf7b39c2e24.html", "dir_9fe753c651ed678e5cb81cf7b39c2e24" ], [ "Reference", "dir_3966cbd4dfc25cd6ca1f2538dd901223.html", "dir_3966cbd4dfc25cd6ca1f2538dd901223" ], [ "Author.php", "phpdocumentor_2reflection-docblock_2src_2_doc_block_2_tags_2_author_8php.html", [ [ "Author", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_author.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_author" ] ] ], [ "BaseTag.php", "_base_tag_8php.html", [ [ "BaseTag", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_base_tag.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_base_tag" ] ] ], [ "Covers.php", "_covers_8php.html", [ [ "Covers", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_covers.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_covers" ] ] ], [ "Deprecated.php", "phpdocumentor_2reflection-docblock_2src_2_doc_block_2_tags_2_deprecated_8php.html", [ [ "Deprecated", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_deprecated.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_deprecated" ] ] ], [ "Example.php", "phpdocumentor_2reflection-docblock_2src_2_doc_block_2_tags_2_example_8php.html", [ [ "Example", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_example.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_example" ] ] ], [ "Formatter.php", "_formatter_8php.html", [ [ "Formatter", "interfacephp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_formatter.html", "interfacephp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_formatter" ] ] ], [ "Generic.php", "_generic_8php.html", [ [ "Generic", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_generic.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_generic" ] ] ], [ "Link.php", "_link_8php.html", [ [ "Link", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_link.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_link" ] ] ], [ "Method.php", "phpdocumentor_2reflection-docblock_2src_2_doc_block_2_tags_2_method_8php.html", [ [ "Method", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_method.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_method" ] ] ], [ "Param.php", "_param_8php.html", [ [ "Param", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_param.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_param" ] ] ], [ "Property.php", "_property_8php.html", [ [ "Property", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_property.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_property" ] ] ], [ "PropertyRead.php", "_property_read_8php.html", [ [ "PropertyRead", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_property_read.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_property_read" ] ] ], [ "PropertyWrite.php", "_property_write_8php.html", [ [ "PropertyWrite", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_property_write.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_property_write" ] ] ], [ "Return_.php", "_return___8php.html", [ [ "Return_", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_return__.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_return__" ] ] ], [ "See.php", "_see_8php.html", [ [ "See", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_see.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_see" ] ] ], [ "Since.php", "_since_8php.html", [ [ "Since", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_since.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_since" ] ] ], [ "Source.php", "phpdocumentor_2reflection-docblock_2src_2_doc_block_2_tags_2_source_8php.html", [ [ "Source", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_source.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_source" ] ] ], [ "Throws.php", "_throws_8php.html", [ [ "Throws", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_throws.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_throws" ] ] ], [ "Uses.php", "_uses_8php.html", [ [ "Uses", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_uses.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_uses" ] ] ], [ "Var_.php", "_var___8php.html", [ [ "Var_", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_var__.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_var__" ] ] ], [ "Version.php", "phpdocumentor_2reflection-docblock_2src_2_doc_block_2_tags_2_version_8php.html", [ [ "Version", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_version.html", "classphp_documentor_1_1_reflection_1_1_doc_block_1_1_tags_1_1_version" ] ] ] ];import Vue from "vue"; Vue.filter("chf", function(value) { if (!value) return ""; return ( new Number(value).toLocaleString("de-CH", { minimumFractionDigits: 2, }) + " CHF" ); }); Vue.filter("medium", function(value) { if (!value) return ""; var count = 35; return value.slice(0, count) + (value.length > count ? "..." : ""); }); Vue.filter("long", function(value) { if (!value) return ""; var count = 250; return value.slice(0, count) + (value.length > count ? "..." : ""); }); Vue.filter("capitalize", function(value) { if (!value) return ""; return value.toUpperCase(); }); /* Copyright 2016-2020 Nuxeo 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. */ const { Given, Then, When } = require('cucumber'); const After = require('./support/hooks.js').After; function toggleTraces(button, page) { if (page === 'Popup extension') { const selector = button.replace(/\s+/g, '-').toLowerCase(); browser.$(`#${selector}-button`).waitForDisplayed(); browser.$(`#${selector}-button`).click(); } else { browser.$('//a[@href="/nuxeo/site/automation/doc/toggleTraces"]').waitForDisplayed(); browser.$('//a[@href="/nuxeo/site/automation/doc/toggleTraces"]').click(); } } function tracesEnabled(button, page) { if (page === 'Popup extension') { browser.pause(500); const selector = button.replace(/\s+/g, '-').toLowerCase(); browser.$(`#${selector}-button`).waitForDisplayed(); const elementClass = browser.$(`#${selector}-button`).getAttribute('class'); const enabled = elementClass.indexOf('enabled') > -1; if (enabled === true) { return true; } else { return false; } } else if (browser.$('a.button').getText() === 'Disable') { return true; } else if (browser.$('a.button').getText() === 'Enable') { return false; } else { return undefined; } } Then(/^I can see that (.+) (is|are) (enabled|disabled) on the (Automation Documentation|Popup extension) page/, (button, verb, mode, page) => { if (mode === 'enabled') { browser.waitUntil(() => tracesEnabled(button, page), 5000); return tracesEnabled(button, page).should.be.true; } else { browser.waitUntil(() => tracesEnabled(button, page) === false, 5000); return tracesEnabled(button, page).should.be.false; } }); Then(/I click on the (.+) operation/, (operation) => { const tabIds = browser.getWindowHandles(); browser.switchToWindow(tabIds[2]); browser.$(`//a[text()="${operation}"]`).waitForDisplayed; browser.$(`//a[text()="${operation}"]`).click(); }); When(/^(.+) (is|are) (enabled|disabled) from the (Automation Documentation|Popup extension) page$/, (button, verb, mode, page) => { if (mode === 'disabled') { if (tracesEnabled(button, page)) { return toggleTraces(button, page); } browser.waitUntil(() => tracesEnabled(button, page) === false, 5000); return tracesEnabled(button, page).should.be.false; } else { if (!tracesEnabled(button, page)) { return toggleTraces(button, page); } browser.waitUntil(() => tracesEnabled(button, page), 5000); return tracesEnabled(button, page).should.be.true; } }); <reponame>wellingtonn96/CoursesAndTuturialsNodejs //new feature ES6 const people={ name:'Ana', age:5, adress:{ street: 'Rua ABC', number:1000 } } const { name, age} = people console.log(name, age) const {name: n, age: i}= people console.log(n, i) //console.log(lastname, goodhumor) const {adress : {street, number, cep}} = people console.log(street, number, cep) //const {cont: {ag, num}} = people import es6Promise from 'es6-promise' import fetch from 'isomorphic-fetch' import R from 'ramda' import { API_URL } from '../../../config/conf' import { getAuthToken } from './auth' es6Promise.polyfill() // activate polyfill const errorStatus = [400, 401, 403, 404, 409, 500, 503] const _serializeParams = (params) => { return Object.keys(params).map((key) => { return key + '=' + encodeURIComponent(params[key]) }).join('&') } const buildHeaders = () => { const header = { 'Accept': 'application/json', 'Content-Type': 'application/json' } // Try to retrieve token const token = getAuthToken() if (token) { header['Authorization'] = 'Bearer ' + token } return header } const Api = { get (url, params) { const strParams = _serializeParams(params) return fetch(API_URL + url, { method: 'get', body: strParams, headers: buildHeaders() }).then((response) => { if (R.contains(response.status, errorStatus)) { throw { status: response.status, message: response.body } } else { return response.json() } }) }, post (url, params) { const strParams = JSON.stringify(params) return fetch(API_URL + url, { method: 'post', headers: buildHeaders(), body: strParams }).then((response) => { if (R.contains(response.status, errorStatus)) { throw { status: response.status, message: response.body } } else { return response.json() } }) } } export default Api <reponame>michaelbnd/react-native-ionicons-5<gh_stars>1-10 import * as React from "react"; import Svg, { Path } from "react-native-svg"; function SvgLogoGoogle(props) { return <Svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 512 512" {...props}><Path d="M473.16 221.48l-2.26-9.59H262.46v88.22H387c-12.93 61.4-72.93 93.72-121.94 93.72-35.66 0-73.25-15-98.13-39.11a140.08 140.08 0 01-41.8-98.88c0-37.16 16.7-74.33 41-98.78s61-38.13 97.49-38.13c41.79 0 71.74 22.19 82.94 32.31l62.69-62.36C390.86 72.72 340.34 32 261.6 32c-60.75 0-119 23.27-161.58 65.71C58 139.5 36.25 199.93 36.25 256s20.58 113.48 61.3 155.6c43.51 44.92 105.13 68.4 168.58 68.4 57.73 0 112.45-22.62 151.45-63.66 38.34-40.4 58.17-96.3 58.17-154.9 0-24.67-2.48-39.32-2.59-39.96z" /></Svg>; } export default SvgLogoGoogle;<gh_stars>0 import React, { useState } from 'react'; import classes from './InputPassword.module.scss'; const InputPassword = (props) => { const [visible, setVisible] = useState(false); const clickHandler = () => { setVisible(!visible); } return ( <div className={`${classes.wrapper} ${props.customClass || ''}`}> <input className={classes.input} onChange={props.onChange} type={visible ? 'text' : 'password'} placeholder={props.placeholder} autoComplete="off" autoCorrect="off" spellCheck="false" value={props.value} /> <i className={`fa ${visible ? 'fa-eye-slash' :'fa-eye'} ${classes.iconEye}`} onClick={clickHandler} ></i> </div> ); } export default InputPassword; // THIS FILE IS AUTO GENERATED var GenIcon = require('../lib').GenIcon module.exports.MdMicNone = function MdMicNone (props) { return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 24 24"},"child":[{"tag":"path","attr":{"d":"M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1.2-9.1c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2l-.01 6.2c0 .66-.53 1.2-1.19 1.2-.66 0-1.2-.54-1.2-1.2V4.9zm6.5 6.1c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"}}]})(props); }; <reponame>themud2001/eCommerce<filename>frontend/src/components/User/index.js import React from "react"; import { Link } from "react-router-dom"; import { FiUser } from "react-icons/fi"; import "./styles.scss"; class User extends React.Component { render() { return ( <Link to="/login" className="item user"><FiUser size={22} /></Link> ); } } export default User;<gh_stars>1-10 import { redirectToStaticPage } from '../app/actions'; import { CONFERENCE_JOINED } from '../base/conference/actionTypes'; import { CONNECTION_FAILED } from '../base/connection'; import { JitsiConnectionErrors } from '../base/lib-jitsi-meet'; import { MiddlewareRegistry } from '../base/redux'; import { SET_DETAILS } from './actionTypes'; import { getCustomerDetails } from './actions'; import { STATUSES } from './constants'; import { isVpaasMeeting } from './functions'; /** * The redux middleware for jaas. * * @param {Store} store - The redux store. * @returns {Function} */ MiddlewareRegistry.register(store => next => async action => { switch (action.type) { case CONFERENCE_JOINED: { store.dispatch(getCustomerDetails()); break; } case CONNECTION_FAILED: { const { error } = action; if (!isVpaasMeeting(store.getState()) || !error) { break; } if (error.name === JitsiConnectionErrors.PASSWORD_REQUIRED) { if (error.message !== 'could not obtain public key') { break; } store.dispatch(redirectToStaticPage('/static/planLimit.html')); } break; } case SET_DETAILS: { const { status } = action.payload; if (status === STATUSES.BLOCKED) { store.dispatch(redirectToStaticPage('/static/planLimit.html')); } } } return next(action); }); <reponame>yama24/alifaqiqahcatering /* Template Name: Upzet - Responsive Bootstrap 4 Admin Dashboard Author: Themesdesign Website: https://themesdesign.in/ File: Bootstrap Toasts Js */ // Bootstrap Toast var toastTrigger = document.getElementById('liveToastBtn') var toastLiveExample = document.getElementById('liveToast') if (toastTrigger) { toastTrigger.addEventListener('click', function () { var toast = new bootstrap.Toast(toastLiveExample) toast.show() }) } /* eslint-env node */ const path = require('path'); const bodyParser = require('body-parser'); const compression = require('compression'); const { registerExpressAPI } = require('../packages/@pollyjs/node-server'); const DB = {}; module.exports = function attachMiddleware(app) { registerExpressAPI(app, { recordingsDir: path.join(__dirname, 'recordings') }); app.get('/assets/:name', (req, res) => { res.sendFile(path.join(__dirname, 'assets', req.params.name)); }); app.use(bodyParser.json()); app.get('/echo', (req, res) => { res.sendStatus(req.query.status); }); app.post('/compress', compression({ filter: () => true }), (req, res) => { res.write(JSON.stringify(req.body)); res.end(); }); app.get('/api', (req, res) => { res.sendStatus(200); }); app.get('/api/db/:id', (req, res) => { const { id } = req.params; if (DB[id]) { res.status(200).json(DB[id]); } else { res.status(404).end(); } }); app.post('/api/db/:id', (req, res) => { const { id } = req.params; DB[id] = req.body; res.status(200).json(DB[id]); }); app.delete('/api/db/:id', (req, res) => { const { id } = req.params; delete DB[id]; res.status(200).end(); }); }; <reponame>Winchestro/aljabr define ( [ "../utilities/PropertyDescriptors", "../webgl/Context", "../webgl/VertexBuffer", "../material/Material", "../kernel/InterleavedArray", "../mesh/Attribute", "../mesh/Drawable" ], function module ( def, gl, VertexBuffer, Material, InterleavedArray, Attribute, Drawable ) { "use strict"; class ElementAttribute extends Attribute { constructor( geometry, data ) { super( VertexBuffer.Index(), data ); def.Property( this, "geometry", geometry, def.CONFIGURABLE ); if ( data ) this.allocate( data.byteLength, data.constructor ).update( data ); } setGeometry ( geometry ) { def.Property( this, "geometry", geometry, def.CONFIGURABLE ); return this; } draw ( material, offset, count ) { if ( offset === undefined ) offset = 0; if ( count === undefined ) count = this.length; this.geometry.use(); this.buffer.bind(); gl.drawElements( this.drawType, count, this.dataType, offset ); return this; } get length ( ) { if ( this.data ) return this.data.length else return 0; } get dataType ( ) { let length = this.data.length; let dataType = length < ( 1 << 8 ) ? gl.UNSIGNED_BYTE : length < ( 1 << 16 ) ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; return dataType; } get dataTypeString ( ) { return gl.strings[ this.dataType ]; } } def.Properties( ElementAttribute.prototype, { drawType : gl.TRIANLES }, def.CONFIGURABLE ); def.Mixin( ElementAttribute.prototype, Drawable.prototype ); return ElementAttribute; });import {useState} from "react" import {footer, meta} from "../config" import {generateURL, generateURLwithPass} from "../utils/urlUtils" import Footer from "../components/Footer/Footer"; import WelcomeComponent from "../components/WelcomeComponent"; import MainHOC from "../hoc/MainHOC"; import BasicHeader from "../hoc/BasicHeader"; import ClipboardButton from "../components/ClipboardButton"; import BasicWrapper from "../hoc/BasicWrapper"; import ButtonWrapper from "../hoc/ButtonWrapper"; import Input from "../components/Input" export default function Page() { const [origin, setOrigin] = useState("") if (typeof window !== 'undefined' && !origin) { setOrigin(window.location.origin) } const [value, setValue] = useState("") const [password, setPassword] = useState("") const onChange = (e, setFunc) => { const value = e.target.value setFunc(value) } return ( <BasicWrapper> <BasicHeader {...meta}/> <MainHOC> <WelcomeComponent/> <Input className="text-center" placeholder="Link" value={value} onChangeHandler={e => onChange(e, setValue)}/> <Input className="text-center" placeholder="Password (optional)" value={password} onChangeHandler={e => onChange(e, setPassword)}/> {value ? <ButtonWrapper> <a onClick={() => alert("URL copied to clipboard")}> <ClipboardButton text="Generate and copy URL" clipboardData={`${origin}/${password ? generateURLwithPass(value, password) : generateURL(value)}`}/> </a> </ButtonWrapper> : ""} </MainHOC> <Footer {...footer}/> </BasicWrapper> ) } <reponame>aliyun/alibabacloud-redis-training-demo var time = function () { $("#content").html(''); $("#content").append(showtime()); const container = createBox(['user', 'position', 'code', 'news', 'rank']); $("#content").append(container); fn(); }; time(); var timer = setInterval(time, 300000); function fn() { $.get("http://127.0.0.1:8080/users/0", function (res) { const content = `<div class="demo-item"><b>您的姓名</b>:${res.name}</div>` $(".user").append(content); }); $.get("http://127.0.0.1:8080/position/0", function (res) { const content = `<div class="demo-item"><b>您所在的位置</b>:${res.city}</div>` $(".position").append(content); }); $.get("http://127.0.0.1:8080/position/code/0", function (res) { var color; if (res.status == 0) { color = `<font color="#00ff00">否</font>` } else if (res.status == 1) { color = `<font color="#FF0000">是</font>` } const content = `<div class="demo-item"><b>您是否经过热门春运地域</b>:${color} </div>` $(".code").append(content); }); $.get("http://127.0.0.1:8080/news", function (res) { const fragment = document.createDocumentFragment(); for (let i = 0; i < res.length; i++) { const li = document.createElement('li'); li.innerHTML = res[i].content; fragment.appendChild(li); } const title = `<div class="demo-item"><b>新闻通知</b>:</div>`; $(".news").append(title); $(".news").append(fragment); }); $.get("http://127.0.0.1:8080/rank", function (res) { //创建table表格 const table = document.createElement("table"); table.style.border = '1px solid gray'; const thead = document.createElement('thead'); table.appendChild(thead); const tr = document.createElement('tr'); thead.appendChild(tr); const tbody = document.createElement('tbody'); table.appendChild(tbody); const headDates = ['热力值', '省份']; for (let i = 0; i < headDates.length; i++) { const td = document.createElement('td'); td.style.textAlign = 'center'; td.style.border = '1px solid gray'; td.style.height = '10px'; td.style.width = '120px'; td.innerHTML = headDates[i]; tr.appendChild(td); } for (let i = 0; i < res.length; i++) { const item = res[i]; //创建表体数据的行与表体绑定 const tr = document.createElement('tr'); tbody.appendChild(tr); for (let key in item) { //创建表体行中的列 const td = document.createElement('td'); td.style.border = '1px solid gray'; td.style.textAlign = 'center'; td.innerHTML = item[key]; tr.appendChild(td); } } const title = `<div class="demo-item"><b>迁入迁出排名</b>:</div>` $(".rank").append(title); $(".rank").append(table); }); } function judge(a) { var b; return a < 10 ? b = '0' + a : b = '' + a; } function showtime() { var mytime = new Date(); var str = ''; str += mytime.getFullYear() + '-' + judge(mytime.getMonth() + 1) + '-' + judge(mytime.getDate()) + ' ' + judge(mytime.getHours()) + ':' + judge(mytime.getMinutes()) + ':' + judge(mytime.getSeconds()); return `<div class="demo-date">${str}</div>`; } function createBox(boxs) { const fragment = document.createDocumentFragment(); for (let i = 0; i < boxs.length; i++) { const div = document.createElement('div'); div.setAttribute('class', boxs[i]) fragment.appendChild(div); } return fragment; } import React, { Component } from 'react'; import { Badge, Card, CardBody, CardHeader, Col,Modal, ModalBody, ModalFooter, ModalHeader, Pagination, PaginationItem, PaginationLink, Row, Table ,Button,Input} from 'reactstrap'; import axios from "axios"; class BacklogProject extends Component { constructor(props) { super(props); this.onSubmit = this.onSubmit.bind(this); this.onChange = this.onChange.bind(this); this.state = { modal: false, danger: false, idDel:'', ID:'', userStories:[{ _id:'', userStory:'', priority:'', timeestimation:'' }] } this.toggleDanger = this.toggleDanger.bind(this); } toggleDanger() { this.setState({ danger: !this.state.danger, }); } onChange = idx => e => { const { name, value } = e.target; const userStories = [...this.state.userStories]; userStories[idx] = { [name]: value }; this.setState({ userStories }); } onSubmit(p) { p.preventDefault() const data = this.state console.log(p) this.setState({ }) } handleUpdateSpecificRow = (id,idx) => () => { console.log("iii "+idx) console.log( this.state.userStories[idx].timeestimation) this.setState({ userStories: [...this.state.userStories] }); axios.put("http://localhost:3000/backlogProject/updateUserStory/5c96402f20a9240ec8f5c590/5cc242919d7ae11fe8722c84",{ priority: this.state.userStories[idx].priority}) .then((response) => { console.log("updated"); alert('User story updated') }) .catch(error => { console.log(error); }); } handleRemoveSpecificRow = (idx) => () => { console.log("iii"+idx) const userStories = [...this.state.userStories] this.setState({ userStories }) console.log("aaaaaa"+idx) userStories.splice(idx, 1) axios.put("http://localhost:3000/backlogProject/delete/5c96402f20a9240ec8f5c590/"+idx) .then((response) => { console.log("deleted"); this.setState({ danger: !this.state.danger, }); }) .catch(error => { console.log(error); }); } componentDidMount(e) { var self = this; axios.get("http://localhost:3000/project/getBacklog/5cc23892b8a2c809c0998415") .then((response) => { console.log(response.data[0].userstories.length); self.setState({ userStories:response.data[0].userstories, ID:response.data[0]._id,}) console.log(this.state.userStories); }) .catch(error => { console.log(error); }); } render() { return ( <div className="animated fadeIn"> <Row> <Col> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Backlog Project </CardHeader> <CardBody> <Table hover bordered striped responsive size="sm"> <thead> <tr> <th>User Story</th> <th>Priority</th> <th>Time Estimation</th> <th></th> <th></th> </tr> </thead> <tbody> { this.state.userStories.map((userstory,idx) => { return ( <tr key={idx}> <td hidden> <Input type="text" id="_id" name="_id" value={this.state.userStories[idx]._id} placeholder={userstory._id} onChange={this.onChange(idx)}/></td> <td><Input type="text" id="userStory" name="userStory" value={this.state.userStories[idx].userStory} placeholder={userstory.userStory} onChange={this.onChange(idx)}/></td> <td><Input type="text" id="priority" name="priority" value={this.state.userStories[idx].priority} placeholder={userstory.priority} onChange={this.onChange(idx)}/> </td> <td><Input type="text" id="timeestimation" name="timeestimation" value={this.state.userStories[idx].timeestimation} placeholder={userstory.timeestimation} onChange={this.onChange(idx)}/></td> <td> <Button block color="primary" onClick={this.handleUpdateSpecificRow(userstory._id,idx)}>Edit</Button></td> <td><Button block color="danger" onClick={this.toggleDanger} >Delete</Button></td> <Modal isOpen={this.state.danger} toggle={this.toggleDanger} className={'modal-danger ' + this.props.className}> <ModalHeader toggle={this.toggleDanger}>Delete user story</ModalHeader> <ModalBody> Are you sure ? </ModalBody> <ModalFooter> <Button color="danger" onClick={this.handleRemoveSpecificRow(userstory._id,idx)}>Delete</Button>{' '} <Button color="secondary" onClick={this.toggleDanger}>Cancel</Button> </ModalFooter> </Modal> </tr> ); }) } </tbody> </Table> <nav> <Pagination> <PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem> <PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem> </Pagination> </nav> </CardBody> </Card> </Col> </Row> </div> ); } } export default BacklogProject; <reponame>hardylake8020/youka-server /** * Created by Wayne on 15/5/10. */ 'use strict'; var mongoose = require('mongoose'), appDb = require('../../../../libraries/mongoose').appDb, should = require('should'), superagent = require('superagent'), agent = superagent.agent(), config = require('../../../../config/config'), orderError = require('../../../errors/order'), userError = require('../../../errors/user'), groupError = require('../../../errors/group'), Order = appDb.model('Order'), OrderDetail = appDb.model('OrderDetail'), Contact = appDb.model('Contact'), User = appDb.model('User'), UserGroup = appDb.model('UserGroup'), Company = appDb.model('Company'), Group = appDb.model('Group'), CustomerContact = appDb.model('CustomerContact'), InviteDriver = appDb.model('InviteDriver'), Driver = appDb.model('Driver'), DriverCompany = appDb.model('DriverCompany'); var OrderWebAPI = require('../../common_function/core_business_logic/company'); //开放注册 function userSignup(username, password, callback) { agent.post(config.serverAddress + 'user/signup') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ username: username, password: password }) .end(function (err, res) { res.body.username.should.equal(username); should.not.exist(res.body.company); callback(res.body); }); } //用户激活 function userActivate(user_id, callback) { agent.get(config.serverAddress + 'user/activate/' + user_id) .set('Content-Type', 'application/x-www-form-urlencoded') .end(function (err, res) { User.findOne({_id: user_id}, function (err, user) { user.email_verified.should.equal(true); callback(res.body); }); }); } //用户登录,返回用户和access_token function userSignin(username, password, callback) { agent.post(config.serverAddress + 'user/signin') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ username: username, password: password }) .end(function (err, res) { res.body.user.email_verified.should.equal(true); callback(res.body); }); } //创建公司返回公司 function createComany(name, address, photo, emplyees, access_token, callback) { agent.post(config.serverAddress + 'company') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ name: name, address: address, photo: photo, employes: emplyees, access_token: access_token }) .end(function (err, res) { callback(res.body); }); } //创建单个订单 function createOrder(orderInfo, groupId, access_token, callback) { agent.post(config.serverAddress + 'order') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ order: orderInfo, group_id: groupId, access_token: access_token }) .end(function (err, res) { callback(res.body); }); } //获取用户订单 function getUserOrders(access_token, callback) { agent.get(config.serverAddress + 'order') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ access_token: access_token }) .end(function (err, res) { if (err) callback(err, null); else callback(null, res.body); }); } //根据订单Id获取订单 function getOrderById(access_token, orderId, callback) { agent.get(config.serverAddress + 'order/getorderbyid') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ access_token: access_token, order_id: orderId }) .end(function (err, res) { if (err) callback(err, null); else callback(null, res.body); }); } //获取用户未分配订单 function getUserUnassignedOrders(access_token, callback) { agent.get(config.serverAddress + 'order/unassigned') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ access_token: access_token }) .end(function (err, res) { if (err) callback(err, null); else callback(null, res.body); }); } //根据订单ID获取订单分配的详细信息 function getOrderAssignedDetailById(access_token, orderId, callback) { agent.get(config.serverAddress + 'order/assignedOrderDetail') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ access_token: access_token, order_id: orderId }) .end(function (err, res) { if (err) callback(err, null); else callback(null, res.body); }); } //根据订单ID获取订单分配的详细信息 function getChildrenOrdersById(access_token, orderId, callback) { agent.get(config.serverAddress + 'order/childrenOrders') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ access_token: access_token, order_id: orderId }) .end(function (err, res) { if (err) callback(err, null); else callback(null, res.body); }); } //分配订单 function assignOrder(access_token, orderId, assignInfos, callback) { agent.post(config.serverAddress + 'order/multiassign') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ access_token: access_token, order_id: orderId, assign_infos: assignInfos }) .end(function (err, res) { callback(err, res.body); }); } //继续分配订单 function continueAssign(access_token, orderId, assignInfos, callback) { agent.post(config.serverAddress + 'order/continueassign') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ access_token: access_token, order_id: orderId, assign_infos: assignInfos }) .end(function (err, res) { callback(err, res.body); }); } describe('Order Assign Module Unit Tests', function () { var userTestInfo, groupTestInfo, companyTestInfo, orderTestInfo; before(function (done) { userTestInfo = { username: '<EMAIL>', password: '<PASSWORD>' }; groupTestInfo = { name: 'test', display_name: 'test' }; companyTestInfo = { name: 'testCompany', address: 'test address', photo: 'test photo', employees: 'test employees' }; orderTestInfo = { order_number: '123456789', goods_name: 'books' }; UserGroup.remove(function () { User.remove(function () { Company.remove(function () { Group.remove(function () { Contact.remove(function () { OrderDetail.remove(function () { Order.remove(function () { CustomerContact.remove(function () { Driver.remove(done); }); }); }); }); }); }); }); }); }); describe('user sign in to assign order::', function () { // user sign up var new_user, sub_user; it('user should create success', function (done) { userSignup(userTestInfo.username, userTestInfo.password, function (userEntity){ userEntity.username.should.equal(userTestInfo.username); new_user = userEntity; done(); }); }); it('sub-user should create success', function (done) { userSignup('<EMAIL>', '111111', function (userEntity){ userEntity.username.should.equal('<EMAIL>'); sub_user = userEntity; done(); }); }); // user activate it('user should activate success', function (done) { userActivate(new_user._id, function (result) { done(); }); }); it('sub-user should activate success', function (done) { userActivate(sub_user._id, function (result) { done(); }); }); // user sign in var access_token, sub_access_token; it('user should login success', function (done) { userSignin(userTestInfo.username, userTestInfo.password, function (result) { result.user.username.should.equal(userTestInfo.username); access_token = result.access_token; done(); }); }); it('sub-user should login success', function (done) { userSignin(sub_user.username, '<PASSWORD>', function (result) { result.user.username.should.equal(sub_user.username); sub_access_token = result.access_token; done(); }); }); // create company var new_company, default_group, sub_company, sud_default_group; it('company should create success', function (done) { createComany(companyTestInfo.name, companyTestInfo.address, companyTestInfo.photo, companyTestInfo.employees, access_token, function (companyEntity) { companyEntity.name.should.equal(companyTestInfo.name); should.exist(companyEntity.groups[0]._id); new_company = companyEntity; default_group = companyEntity.groups[0]; done(); }); }); it('sub-company should create success', function (done) { createComany('subCompany', 'sub-address', 'sub-photo', 'sub-employees', sub_access_token, function (companyEntity) { companyEntity.name.should.equal('subCompany'); should.exist(companyEntity.groups[0]._id); sub_company = companyEntity; sud_default_group = companyEntity.groups[0]; done(); }); }); var password = '<PASSWORD>'; var driverName = '18321740710'; var driver, driver_access_token; //这个司机进行注册登录并返回司机access_token it('should return a driver access_token', function (done) { //获取验证码 agent.post(config.serverAddress + 'driver/getsmsverifycode') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ username: driverName }) .end(function (err, res) { if (err) console.log(err); var smsVerify = res.body; //注册 agent.post(config.serverAddress + 'driver/signup') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ username: driverName, password: password, sms_verify_id: smsVerify._id, sms_verify_code: smsVerify.code }) .end(function (err, res) { if (err) console.log(err); //登录 agent.post(config.serverAddress + 'driver/signin') .set('Content-Type', 'application/x-www-form-urlencoded') .send({ username: driverName, password: password }) .end(function (err, res) { res.body.driver.username.should.equal(driverName); res.body.access_token.should.not.equal(undefined); Driver.findOne({username: res.body.driver.username}, function (err, driverEntity) { driver = driverEntity; driver_access_token = res.body.access_token; done(); }); }); }); }); }); // multi assign it('should be error when assign a order where order id is empty', function (done) { var assignInfo = [{ type: 'company', company_id: sub_company._id, is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token, '', assignInfo, function (err, result) { should.exist(result.err); result.err.type.should.equal(orderError.internal_system_error.type); done(); }); }); it('should be error when assign a order where order id is not exist', function (done) { var assignInfo = [{ type: 'company', company_id: sub_company._id, is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token, new_user._id.toString(), assignInfo, function (err, result) { should.exist(result.err); result.err.type.should.equal(orderError.order_not_exist.type); done(); }); }); var order_assign; it('should be success when create a order', function (done) { var orderObject = { order_number: '123456789*0788', goods_name: 'macs' }; createOrder(orderObject, default_group._id, access_token, function (result) { should.not.exist(result.err); result.detail.order_number.should.equal(orderObject.order_number); result.status.should.equal('unAssigned'); order_assign = result; done(); }); }); it('should be error when assign a order where assign info is empty', function (done) { assignOrder(access_token,order_assign._id,null, function (err, result) { should.exist(result.err); result.err.type.should.equal(orderError.assign_infos_null.type); done(); }); }); it('should be success when assign a order to company', function (done) { var assignInfo = [{ type: 'company', company_id: sub_company._id, is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token,order_assign._id,assignInfo, function (err, result) { result.assignedOrderList.length.should.equal(1); result.assignedInfos[0].is_assigned.should.equal(true); done(); }); }); it('should be error when assign a order twice', function (done) { var assignInfo = [{ type: 'company', company_id: sub_company._id, is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token, order_assign._id, assignInfo, function (err, result) { should.exist(result.err); result.err.type.should.equal(orderError.order_has_assigned.type); done(); }); }); /// order assign to company var order_zero; it('should be success when create a order', function (done) { var orderObject = { order_number: '123456789*0', goods_name: 'macs' }; createOrder(orderObject, default_group._id, access_token, function (result) { should.not.exist(result.err); result.detail.order_number.should.equal(orderObject.order_number); order_zero = result; done(); }); }); it('should be error when assign a order to company where company id is empty', function (done) { var assignInfo = [{ type: 'company', company_id: '', is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token, order_zero._id.toString(), assignInfo, function (err, result) { result.assignedOrderList.length.should.equal(0); done(); }); }); var order_one; it('should be success when create a order', function (done) { var orderObject = { order_number: '1234**56789*0', goods_name: 'macs' }; createOrder(orderObject, default_group._id, access_token, function (result) { should.not.exist(result.err); result.detail.order_number.should.equal(orderObject.order_number); order_one = result; done(); }); }); it('should be error when assign a order to company where company id is not exist', function (done) { var assignInfo = [{ type: 'company', company_id: new_user._id.toString(), is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token, order_one._id.toString(), assignInfo, function (err, result) { result.assignedOrderList.length.should.equal(0); done(); }); }); var order_two, order_two_sub; it('should be success when create a order', function (done) { var orderObject = { order_number: '1234**56789*0', goods_name: 'macs' }; createOrder(orderObject, default_group._id, access_token, function (result) { should.not.exist(result.err); result.detail.order_number.should.equal(orderObject.order_number); order_two = result; done(); }); }); it('should be success when assign a order to company', function (done) { var assignInfo = [{ type: 'company', company_id: sub_company._id, is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token, order_two._id.toString(), assignInfo, function (err, result) { result.assignedOrderList.length.should.equal(1); result.assignedInfos[0].is_assigned.should.equal(true); order_two_sub = result.assignedOrderList[0]; done(); }); }); it('should be success when get children orders by parent order id', function (done) { getChildrenOrdersById(access_token, order_two._id.toString(), function (err, result) { should.not.exist(result.err); result.children[0]._id.should.equal(order_two_sub._id); done(); }); }); /// order assign to driver var order_driver_one; it('should be success when create a order', function (done) { var orderObject = { order_number: '123456789*0123', goods_name: 'macos' }; createOrder(orderObject, default_group._id, access_token, function (result) { should.not.exist(result.err); result.detail.order_number.should.equal(orderObject.order_number); order_driver_one = result; done(); }); }); it('should be error when assign a order to driver where driver id is empty', function (done) { var assignInfo = [{ type: 'driver', driver_id: '', is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token, order_driver_one._id.toString(), assignInfo, function (err, result) { result.assignedOrderList.length.should.equal(0); done(); }); }); //公司2邀请合作司机driver2 it('should be success when company invite driver', function (done) { OrderWebAPI.inviteDriver(access_token, driver.username, function (err, result) { done(); }); }); var order_driver_two; it('should be success when create a order', function (done) { var orderObject = { order_number: '123456789*0123', goods_name: 'macos' }; createOrder(orderObject, default_group._id, access_token, function (result) { should.not.exist(result.err); result.detail.order_number.should.equal(orderObject.order_number); order_driver_two = result; done(); }); }); it('should be error when assign a order to driver where driver id is not exist', function (done) { var assignInfo = [{ type: 'driver', driver_id: new_user._id.toString(), is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token, order_driver_two._id.toString(), assignInfo, function (err, result) { result.assignedOrderList.length.should.equal(0); done(); }); }); var order_driver_three; it('should be success when create a order', function (done) { var orderObject = { order_number: '123456789*0123', goods_name: 'macos' }; createOrder(orderObject, default_group._id, access_token, function (result) { should.not.exist(result.err); result.detail.order_number.should.equal(orderObject.order_number); order_driver_three = result; done(); }); }); it('should be success when assign a order to driver', function (done) { var assignInfo = [{ type: 'driver', driver_id: driver._id.toString(), is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; assignOrder(access_token, order_driver_three._id.toString(), assignInfo, function (err, result) { result.assignedOrderList.length.should.equal(1); result.assignedInfos[0].is_assigned.should.equal(true); done(); }); }); /// continue assign var order_continue; it('should be success when create a order', function (done) { var orderObject = { order_number: '1234588789*0788', goods_name: 'macs' }; createOrder(orderObject, default_group._id, access_token, function (result) { should.not.exist(result.err); result.detail.order_number.should.equal(orderObject.order_number); result.status.should.equal('unAssigned'); order_continue = result; done(); }); }); it('should be error when continue assign order where assign info is null', function (done) { continueAssign(access_token, order_continue._id.toString(), null, function (err, result) { result.err.type.should.equal(orderError.assign_infos_null.type); done(); }); }); it('should be error when continue assign order where order id is empty', function (done) { var assignInfo = [{ type: 'company', company_id: new_user._id.toString(), is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; continueAssign(access_token, '', assignInfo, function (err, result) { result.err.type.should.equal(orderError.internal_system_error.type); done(); }); }); it('should be error when continue assign order where order id is not exist', function (done) { var assignInfo = [{ type: 'company', company_id: new_user._id.toString(), is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; continueAssign(access_token, new_user._id.toString(), assignInfo, function (err, result) { result.err.type.should.equal(orderError.order_not_exist.type); done(); }); }); it('should be error when continue assign order where order is not assign', function (done) { var assignInfo = [{ type: 'company', company_id: new_user._id.toString(), is_assigned: false, pickup_contact_name: 'elina', pickup_contact_phone: '01032147895', pickup_contact_mobile_phone: '18321740710', pickup_contact_email: '', delivery_contact_name: 'hardy', delivery_contact_phone: '', delivery_contact_mobile_phone: '', delivery_contact_address: '', delivery_contact_email: '' }]; continueAssign(access_token, order_continue._id.toString(), assignInfo, function (err, result) { result.err.type.should.equal(orderError.order_not_assigning.type); done(); }); }); }); after(function (done) { UserGroup.remove(function () { User.remove(function () { Company.remove(function () { Group.remove(function () { Contact.remove(function () { OrderDetail.remove(function () { Order.remove(function () { CustomerContact.remove(function () { Driver.remove(done); }); }); }); }); }); }); }); }); }); }); import styled from "styled-components"; const StyledContainer = styled.div` max-width: 320px; width: 100%; padding: 25px 12px 18px; border: 1px solid #000000; border-radius: 10px; margin-top: 40px; flex-direction: column-reverse; justify-content: center; display: flex; margin-bottom: 30px; `; const StyledPhoto = styled.img` width: 100%; height: 100%; border-radius: 50px 50px; object-fit: cover; `; const Title = styled.h2` color: #2680eb; font-weight: 300; font-size: 1rem; @media (max-width: 500px) { font-size: 1rem; } `; // const Date = styled.div` // color: #2680eb; // font-weight: 300; // margin: 6px 0; // @media (max-width: 500px) { // font-size: 0.8rem; // } // `; const Review = styled.p` color: #000000; font-weight: 300; @media (max-width: 500px) { font-size: 0.75rem; } `; export { Title, Review, StyledContainer, StyledPhoto }; <filename>lib/Sidebar.js 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _season = require('season'); var _season2 = _interopRequireDefault(_season); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _Projects = require('./Projects'); var _Projects2 = _interopRequireDefault(_Projects); 'use strict'; var Sidebar = _react2['default'].createClass({ displayName: 'Sidebar', getInitialState: function getInitialState() { return { projects: this.getProjects(), activeProjects: this.getActiveProjects() }; }, componentDidMount: function componentDidMount() { var _this = this; this.projectSubscription = atom.project.onDidChangePaths(function () { return _this.setState({ activeProjects: _this.getActiveProjects() }); }); }, componentWillUnmount: function componentWillUnmount() { this.projectSubscription.dispose(); }, render: function render() { return _react2['default'].createElement( 'div', { className: 'project-sidebar padded' }, _react2['default'].createElement(_Projects2['default'], { projects: this.state.projects, activeProjects: this.state.activeProjects, onSelect: this.onSelect }) ); }, getProjects: function getProjects() { var confPath = _path2['default'].join(atom.getConfigDirPath(), 'projects.cson'); try { return _season2['default'].readFileSync(confPath); } catch (e) { atom.notifications.addError('Failed to open the project sidebar', { detail: 'The project-sidebar package requires a configured ' + 'installation of the project-manager plugin. project-sidebar ' + 'loads a list of projects by inspecting the ' + '~/.atom/projects.cson` file which is managed by project-manager.' }); // fall back to an empty object, which is basically the same as saying // that no projects have been configured. return {}; } }, getActiveProjects: function getActiveProjects() { var paths = atom.project.getPaths().slice().sort(); return _lodash2['default'].values(this.getProjects()).filter(function (project) { return _lodash2['default'].isEqual(project.paths.slice().sort(), paths); }).map(function (project) { return project.title; }); }, onSelect: function onSelect(project) { // remove all current directories that do not belong to the // selected project. atom.project.getDirectories().filter(function (directory) { return project.paths.indexOf(directory.path) === -1; }).forEach(function (directory) { atom.project.removePath(directory.path); }); // next add all remaining project directories project.paths.forEach(function (eachPath) { if (!atom.project.contains(eachPath)) { atom.project.addPath(eachPath); } }); }, onShow: function onShow() { this.setState({ projects: this.getProjects(), activeProjects: this.getActiveProjects() }); } }); exports['default'] = Sidebar; module.exports = exports['default'];<reponame>beegee-tokyo/VNCL4020C-Arduino<gh_stars>0 var searchData= [ ['negativeedge_219',['negativeEdge',['../class_h_e_a_r_t___r_a_t_e.html#a1b79069001b814be50a42fdb627baf50',1,'HEART_RATE']]] ]; <filename>commands/Command Template.js const {Client,MessageEmbed,Attachment} = require("discord.js") module.exports = function(message,args) { const {RequestAPIJSON,RequestAPINormal,AxiosRequestAPIJSON} = require("../bot_modules/FetchService.js") const StartType = require("../bot_modules/TypingService.js") const getRandomInt = require("../bot_modules/RandomService.js") }module.exports = { target: { options: { questions: [ { config: 'marketingDistName', // set the tag to whatever is typed for this question type: 'input', default: 'website-stable', // default value if nothing is entered message: 'Name of release tag:' }, { config: 'github-release.options.auth.user', // set the user to whatever is typed for this question type: 'input', message: 'GitHub username:' }, { config: 'github-release.options.auth.password', // set the password to whatever is typed for this question type: 'password', message: 'GitHub password (or API/auth key password):' } ] } } };<reponame>mrange/randomcodegenerator.lol export { default as Contributors } from "./contributors"; export { default as Languages } from "./languages"; export { default as logs } from "./logs"; export { default as nouns } from "./nouns"; export { default as singleCharacters } from "./singleCharacters"; export { default as suffixes } from "./suffixes"; export { default as verbs } from "./verbs"; <gh_stars>1-10 import { initializeApp } from 'firebase/app'; import { getDatabase, ref, child, get } from "firebase/database"; import { getAuth, onAuthStateChanged, createUserWithEmailAndPassword, signInWithEmailAndPassword } from "firebase/auth"; // Set the configuration for your app // TODO: Replace with your project's config object const firebaseConfig = { apiKey: ".....", authDomain: ".....firebaseapp.com", databaseURL: "https://<YOUR FIREBASE>.firebaseio.com ", projectId: "......", storageBucket: "......appspot.com", messagingSenderId: ".....", appId: "1:.....:web:......" }; const app = initializeApp(firebaseConfig); // FIREBASE DATABASE const dbRef = ref(getDatabase(app)); get(child(dbRef, `/`)).then((snapshot) => { if (snapshot.exists()) { console.log(snapshot.val()); } else { console.log("No data available"); } }).catch((error) => { console.error(error); }); //FREBASE AUTH const auth = getAuth(); onAuthStateChanged(auth, (user) => { if (user) { // User is signed in, see docs for a list of available properties // https://firebase.google.com/docs/reference/js/firebase.User const uid = user.uid; console.log('User logged in uid - ', uid) } else { // User is signed out console.log('User is not logged in') } }); console.log('background script logic here...') <gh_stars>0 const fn = function(filename, fn = () => {}){ fn(null, filename); return new Promise((res, rej) => { res(filename); }); } fn('hello') .then((data) => { console.log(data); }) fn('hello', (err, data) => { console.log(data); });<reponame>learnsleek/nodejs-architect-sample<gh_stars>0 const Id = '../Id' module.exports = function makeCategoryDb ({ makeDb }) { return Object.freeze({ insert, findByHash }) async function insert ({ id: _id = Id.makeId(), ...categoryInfo }) { const db = await makeDb() const result = await db .collection('category') .insertOne({ _id, ...categoryInfo }) const { _id: id, ...insertedInfo } = result.ops[0] return { id, ...insertedInfo } } async function findByHash (category) { const db = await makeDb() const result = await db.collection('category').find({ hash: category.hash }) const found = await result.toArray() if (found.length === 0) { return null } const { _id: id, ...insertedInfo } = found[0] return { id, ...insertedInfo } } }<reponame>JoshSmithTX/CodeBreakerProject<filename>src/assets/main.js let answer = document.getElementById('answer'); let attempt = document.getElementById('attempt'); function guess() { let input = document.getElementById('user-guess'); //add functionality to guess function here // #08 if (answer.value == '' || attempt.value == '') { setHiddenFields(); } // #11 if (validateInput(input.value) === false) { return false; } // #14 if (getResults(input.value)) { setMessage("You win! :)"); showAnswer(true); showReplay(); answer.value = ''; attempt.value = ''; } else if (attempt.value >= 10) { // #15 setMessage("You Lose! :("); showAnswer(false); showReplay(); answer.value = ''; attempt.value = ''; } else { // #16 setMessage("Incorrect, try again."); attempt.value++; } } //implement new functions here // #05 function setHiddenFields() { answer.value = "" + Math.floor(Math.random() * 9999); // #06 while (answer.value.length < 4) { answer = '0' + answer; } // #07 attempt.value = 1; } // #09 function setMessage(msg) { document.getElementById("message").innerHTML = msg; } // #10 function validateInput(text) { if (text.toString().length === 4) { return true; } setMessage("Guesses must be exactly 4 characters long."); return false; } // #12 function getResults(guess) { let div = document.getElementById("results").innerHTML; div += '<div class="row"><span class="col-md-6">' + guess + '</span><div class="col-md-6">'; let result = ''; let correct = '<span class="glyphicon glyphicon-ok"></span>'; let kinda = '<span class="glyphicon glyphicon-transfer"></span>'; let incorrect = '<span class="glyphicon glyphicon-remove"></span>'; let charResult = ''; let numCorrect = 0; for (let i = 0; i < guess.length; i++) { charResult = ''; for (let j = 0; j < answer.value.length; j++) { if (i === j && guess.charAt(i) === answer.value.charAt(j)) { charResult = correct; numCorrect += 1; break; } else if (guess.charAt(i) === answer.value.charAt(j)) { if (guess.charAt(i) === answer.value.charAt(j)) { charResult = kinda; break; } } else if (j === answer.value.length-1 && charResult.length === 0) { charResult = incorrect; } } result = result + charResult; } div = div + result + "</span></div>"; document.getElementById("results").innerHTML = div; // #13 return numCorrect === 4; } // #17 function showAnswer(win) { document.getElementById("code").innerHTML = answer.value; if(win) { document.getElementById("code").className = document.getElementById("code").className + " success"; } else { document.getElementById("code").className = document.getElementById("code").className + " failure"; } } // #18 function showReplay() { document.getElementById('guessing-div').style.display = 'none'; document.getElementById('replay-div').style.display = 'block'; }import React, { useState, useRef, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { setResevationGuest, setChangeInitialGuests, } from '../../Modules/reservation'; import DetailGuestPopup from '../../Components/Detail/DetailGuestPopup'; const DeatailGuestPopupContainer = ({ displayName, ...rest }) => { const { adult: searchAdult, child: searchChild, infant: searchInfant, } = useSelector(state => state.searchForm.guests); const { adult: reserveAdult, child: reserveChild, infant: reserveInfant, } = useSelector(state => state.reservation.guests); const { changeInitialGuests } = useSelector(state => state.reservation); const { capacity } = useSelector(state => state.home.homeState.home); const dispatch = useDispatch(); const [popupState, SetPopupState] = useState(false); const popup = useRef(); const newAdult = (changeInitialGuests ? reserveAdult : searchAdult) || 1; const newChild = changeInitialGuests ? reserveChild : searchChild; const newInfant = changeInitialGuests ? reserveInfant : searchInfant; const changeGuestData = (adult, child, infant) => { const data = { adult, child, infant }; dispatch(setResevationGuest(data)); if (!changeInitialGuests) dispatch(setChangeInitialGuests()); }; const isFullCapacity = newAdult + newChild >= capacity; const increaseGuestCount = guestType => { if ((guestType === 'adult' || !newAdult) && !isFullCapacity) { changeGuestData(newAdult + 1, newChild, newInfant); } else if (guestType === 'child' && !isFullCapacity) { changeGuestData(newAdult, newChild + 1, newInfant); } else if (guestType === 'infant' && newInfant < 5) { changeGuestData(newAdult, newChild, newInfant + 1); } }; const decreaseGuestCount = guestType => { if (guestType === 'adult' && newAdult > 1) { changeGuestData(newAdult - 1, newChild, newInfant); } else if (guestType === 'child' && newChild > 0) { changeGuestData(newAdult, newChild - 1, newInfant); } else if (guestType === 'infant' && newInfant > 0) { changeGuestData(newAdult, newChild, newInfant - 1); } }; const onClosePopup = ({ target }) => { if ( (!popupState || popup.current.contains(target)) && target.textContent !== '닫기' ) return; SetPopupState(false); }; useEffect(() => { document.addEventListener('click', onClosePopup); return () => { document.removeEventListener('click', onClosePopup); }; }, [onClosePopup]); const onOpenPopup = () => SetPopupState(true); return ( <DetailGuestPopup adult={newAdult} child={newChild} infant={newInfant} popup={popup} onOpenPopup={onOpenPopup} popupState={popupState} onClosePopup={onClosePopup} increaseGuestCount={increaseGuestCount} decreaseGuestCount={decreaseGuestCount} capacity={capacity} isFullCapacity={isFullCapacity} displayName={displayName} {...rest} /> ); }; export default DeatailGuestPopupContainer; <reponame>takagotch/o5517 /** * Post entry class */ export default class Post { // post constructor constructor() { this.isnew = true; this.service = ''; this.title = ''; this.description = ''; this.author = ''; this.time = Date.now(); this.date = ''; this.url = ''; } // set the post title setService( str ) { this.service = String( str || '' ).trim(); } // set the post title setTitle( str ) { str = String( str || '' ); this.title = this._collapse( str, '' ); } // set the post description setDescription( str ) { str = String( str || '' ); this.description = this._collapse( str, 'No description provided.' ); } // set the post author setAuthor( str ) { str = String( str || '' ); this.author = this._collapse( str, 'No author' ); } // set the post date/time setTime( time ) { const now = Date.now(); const date = new Date( time || now ); this.time = date.getTime() || now; this.date = date.toString(); } // set the post url setUrl( str ) { str = String( str || '' ); this.url = str; } // build post entry text getText() { return [ this.title, this.description, this.url ].join( "\n\n" ); } // build post entry html getHtml() { return ` <div style="${this._css()}"> <p><big><b>${this.title}</b></big></p> <p><a href="${this.url}"><b>${this.url}</b></a></p> <p><small style="opacity: .5"><b>${this.service}, Posted</b> ${this.date}</small></p> </div>`; } // check if post title matches a regex pattern testMatch( regex ) { if ( regex && this.title ) { return regex.test( this.title ); } return false; } // remove unwanted whitespace from string _collapse( str, fallback ) { str = str.replace( /[\s\t\r\n\ ]+/g, ' ' ); str = str.replace( /\s\s+/g, ' ' ); str = str.trim(); return str || fallback || ''; } // css style used for each post in html output _css() { return [ 'font-family: Monaco, Consolas, monospace', 'margin: 0 0 1rem 0', 'padding: 1rem 2rem', 'background-color: rgba(0,0,0,.05)', 'border-radius: 6px', ].join( '; ' ); } } /* React is a basically just javascript wrap around synthetic sugar call JSX For example: basic creation of HTML element with basic JavaScript. <body> <div id="root"></div> <script type="module"> const rootElement = document.getElementById('root') const element = document.createElement('div') element.textContent = '<NAME>' element.className = 'container' rootElement.append(element) </script> </body> I can also just create the root element and then append it to the body too <body> <div id="root"></div> <script type="module"> const rootElement = document.createElement('root') rootElement.id = 'root' document.body.append(rootElement) const element = document.createElement('div') element.textContent = '<NAME>' element.className = 'container' rootElement.append(element) </script> </body> Now let's use React library to create the same HTML element. One important thing to know about React is that it supports multiple platforms (for example, native and web). Each of these platforms has its own code necessary for interacting with that platform, and then there's shared code between the platforms. With that in mind, you need two JavaScript files to write React applications for the web: React: responsible for creating React elements (kinda like document.createElement()) ReactDOM: responsible for rendering React elements to the DOM (kinda like rootElement.append()) // global react api <script src="https://unpkg.com/react@17.0.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17.0.0/umd/react-dom.development.js"></script> // first params is the html element, second is the props, third is the children const element = React.createElement('div', {className: 'container', children: 'Hello World'}, 'Hello World') ReactDOM.render(element, document.getElementById('root')) note: you can't put statement inside template string, but you can put expression inside template string statement: if(true) {} expression: name ? 'Hello' : 'World' spread props - How can you spread props? const children = 'Hello World' const className = 'container' const props = {children, className} const element = <div />? Looking how jsx is form underneath will help const element = react.createElement('div', props) or react.createElement('div', {...props}) so therefore we can do this: const element = <div {...props} /> we can also add more props to the element const element = <div id="default" {...props} className="contain" /> React Form function UsernameForm({onSubmitUsername}) { // access value of input function handleSubmit(event) { event.preventDefault() const username = event.target.username.value // ref access the value of input const username = inputRef.current.value onSubmitUsername(username) } // access individual input function handleChange(event) { const {value} = event.target } // using ref to access individual input const inputRef = React.useRef() function handleChange(event) { const {value} = event.target } return ( <form onSubmit={handleSubmit}> <div> <label>Username:</label> <input type="text" id="username" onChange={handleChange} ref={inputRef} /> </div> <button type="submit">Submit</button> </form> ) } // default initial value to something especially when you are using it for a useState initial value because it can be undefined function Greeting({initialValue = ''}) { const [name, setName] = useState(initialValue) // IN this case input value doesn't accept undefined as value so it will throw an error. // providing default value is best here return ( <input value={name} /> ) } // Each of the hooks has a unique API. Some return a value (like React.useRef and React.useContext), others return a pair of values (like React.useState and React.useReducer), and others return nothing at all (like React.useEffect). // Lazy state initialization if the initial state is a call that might be slow or async it will make more sense to use a lazy state initialization. the useState allows you to pass a function as params. The good thing about this is prevent the function from being called every time the component re-renders. From this React.useState(someExpensiveComputation()) To this: React.useState(() => someExpensiveComputation()) // Note: child component re-render when 1. a state changes within the component 2. When the parent state changes with dependencies you can detect when your side-effects in child component should re-render. Allowing only state that actually change to trigger and not the entirety of the child component. // Custom hooks: are just hooks that uses other hooks inside of it. e.g it is just using useState and useEffect useLocalStorage({key, defaultValue = ''}) { const [state, setState] = useState(defaultValue) useEffect(() => { window.localStorage.setItem(key, state) }, []) } Lesson 1: Don't mutate state directly e.g const [squares, setSquares] = useState([1,2,3,4,5,6,7,8,9]) function handleSquareClick(square) { // copy the array before mutating it const newSquares = [...squares] newSquares[square] = 'X' setSquares(newSquares) } // Lesson 2: Clean after yourself - e.g In a useEffect, you can't return anything except a cleanup function that will be called when the component unmounts. NOTE: In case of working with async/await, you have to be careful because async/await function returns a promise. (whether you're not returning anything at all, or explicitly returning a function). // this does not work, don't do this: React.useEffect(async () => { const result = await doSomeAsyncThing() // do something with the result }) // this does work, do this: React.useEffect(() => { async function effect() { const result = await doSomeAsyncThing() // do something with the result } effect() }) // or just extract the async code into a utility function which I call and then use the promise-based // .then method instead of using async/await syntax: React.useEffect(() => { doSomeAsyncThing().then(result => { // do something with the result }) }) // Lesson 2: Key prop in react the key prop is used to identify a specific element in the DOM. It is used to update the DOM efficiently and rerender only the changed elements or trigger rerendering. // a change in count will trigger a rerendering of the User component function Child({key}) { const [count, setCount] = useState(0) return <User key={count}>Hello World</User> } // Lesson 3: useReducer useReducer is just like useState with different api. It takes a reducer function (which is just normal function) as a first parameter and an initial state as a second parameter. This two works the same way. const [count, setCount] = useState(initialState) const [count, setCount] = useReducer( (currentState, whatEverIsPassedIntoTheSetCount) => {}, initialState ) The good thing is that we can extract the reducer function into a separate file and import it. const countReducer = (count, step) => count + step function Counter({initialCount = 0, step = 1}) { const [count, changeCount] = React.useReducer(countReducer, initialCount) const increment = () => changeCount(step) return <button onClick={increment}>{count}</button> } We can also pass object into our setState and as our initial state. const countReducer = (state, action) => ({...state, ...action}) function Counter({initialCount = 0, step = 1}) { const [state, setState] = React.useReducer(countReducer, { count: initialCount, }) const {count} = state // here we doing all the count logic and pass the value to setState const increment = () => setState({count: count + step}) return <button onClick={increment}>{count}</button> } We can refactor our reducer function action to be either an object or a function. const countReducer = (state, action) => ({ ...state, ...(typeof action === 'function' ? action(state) : action), }) function Counter({initialCount = 0, step = 1}) { const [state, setState] = React.useReducer(countReducer, { count: initialCount, }) const {count} = state // here we are just passing a function to setState const increment = () => setState(currentState => ({count: currentState.count + step})) return <button onClick={increment}>{count}</button> } We make our reducer API to look like the traditional way reducers looks like in React. function countReducer(state, action) { const {type, step} = action switch (type) { case 'increment': { return { ...state, count: state.count + step, } } default: { throw new Error(`Unsupported action type: ${type}`) } } } function Counter({initialCount = 0, step = 1}) { // we just change the name from setState to dispatch const [state, dispatch] = React.useReducer(countReducer, { count: initialCount, }) const {count} = state // here we are just passing an object with type and step (which is our value) // we can call step "payload" in our action const increment = () => dispatch({type: 'increment', step}) return <button onClick={increment}>{count}</button> } lazy initialization with useReducer function init(initialStateFromProps) { return { pokemon: null, loading: false, error: null, } } // ... const [state, dispatch] = React.useReducer(reducer, props.initialState, init) So, if you pass a third function argument to useReducer, it passes the second argument to that function and uses the return value for the initial state. This could be useful if our init function read into localStorage or something else that we wouldn't want happening every re-render. */<gh_stars>1-10 describe('Tests account related functionality', function() { it('Checks whether student login is possible', function() { cy.visit('./introPage.html'); cy.get('#studentLogin').click(); cy.get('#email_address').type('<EMAIL>'); cy.get('#password').type('<PASSWORD>'); cy.get('#login').click(); cy.url().should('include', '/studentGame.html') }); });<filename>mission-control-client/src/components/user-settings/UserPromotionModal.js import React, { useState } from 'react' import Popup from "reactjs-popup"; import { connect } from 'react-redux' import { updateMCRoles } from '../../actions' const UserModal = props => { const { user, roles } = props const [selected, setSelected] = useState(user) const [formUsed, setFormUsed] = useState(false) const [err, setErr] = useState('Please Select An Option') //iterates over an array of roles const findRoleName = (rolesArr, roleId) => { const roleObj = rolesArr.find(arr => arr.id === roleId) //returns name of role when matching id's are found return roleObj.name } const handleChange = (e) => { //setting form used to true to prevent error from occuring setFormUsed(true) //finding roleName for use in confirmation message if(e.target.value !== 'Select Your Role'){ let roleName = findRoleName(roles, e.target.value) setSelected({...selected, roleId: e.target.value, role: roleName }) setErr('') }else if(e.target.value === 'Select Your Role'){ //a confirmation message is trying to run before any change occurs setErr('Please Select An Option') } } const handleSubmit = (e) => { e.preventDefault(); if(formUsed){ const packet = { id: selected.userId, firstName: selected.firstName, lastName: selected.lastName, email: selected.email, roleId: selected.roleId, } props.updateMCRoles(packet) } } return( <div> <Popup trigger={<button className={`button`}>Update {user.firstName}'s Role</button>} modal> {close => ( <div className="modal"> <a className="close" onClick={close}> × </a> <div className="header"> Update {`${user.firstName} ${user.lastName}'s`} Role </div> <div className="content"> <p className="modal-text">Current Role: <span className = 'current-role'>{user.role.charAt(0).toUpperCase() + user.role.substring(1)}</span></p> <form onSubmit = {handleSubmit}> <p className="modal-text">New Role: <select onChange={handleChange}> <option defaultValue=''>Select Your Role</option> { roles.map(role => { return ( <option name = 'roleId' value = {role.id} onChange={handleChange} key={role.id}>{role.name.charAt(0).toUpperCase() + role.name.substring(1)} </option> ) }) } </select> </p> <div className="actions"> <button type = 'button' className="button close-btn" onClick={() => { close(); }} > Cancel </button> {!err ? '' : err} {/* waiting until form has been used so that selected.role is a valid property */} { formUsed && !err ? <Popup trigger={<button className={`button confirm-btn`} type = 'button'>Confirm Changes</button>} modal> <p className = 'confirmation-message'> Are you sure you want to update {user.firstName} {user.lastName}'s Role To {selected.role.charAt(0).toUpperCase() + selected.role.substring(1)} </p> <button type='submit' className="button confirm-btn" onClick={handleSubmit} > Confirm </button> <button className="button close-btn" onClick={() => close()}> Cancel </button> </Popup> : null} </div> </form> </div> </div> )} </Popup> </div> ) } const mapStateToProps = state => { return state } export default connect(mapStateToProps, { updateMCRoles })(UserModal)<gh_stars>1-10 import React from "react"; import { connect } from "react-redux"; import { CalculatorReducer } from "../store/CalculatorReducer"; import CalculatorList from "./CalculatorList"; import { Link } from "react-router-dom"; export const User = (props) => { const { username } = props; ///const { CalculatorList } = props; return ( <div> <h3>Welcome, {username}</h3> <h3> <Link to={"/list"} className="btn btn-primary"> Go to lists page </Link> </h3> </div> ); }; const mapState = (state) => { return { username: state.auth.username, }; }; export default connect(mapState)(User); 'use strict'; var base = require('../_base'); module.exports = function(warp){ return base.defineModel(warp, 'SnippetRefer', [ base.column_id('snippet_id', {index:true}), base.column_id('user_id', {index:true}) ], { table: 'snippet_refer' }); };<filename>geekHome-backend/src/main/resources/static/js/labelConfig.js /** * 标签管理 */ function labelConfig(){ var self=this; this.init=function(){ $('#addLabelBtn').bind('click',function(){ self.clearFrom(); $("#menu_title").text("添加标签"); $("#addLabelDialog").modal("show"); }); $('#saveLabelBtn').bind('click',function(){ self.saveLabel(); }); self.listLabel(); } this.listLabel=function(){ $.post("/label/labelList",{},function(data){ if(data.success){ var result = data.data; var htmlContent=""; htmlContent+="<tr><th>名称</th><th>类型</th><th>排序</th><th>状态</th><th>创建时间</th><th>操作</th></tr>"; $.each(result, function(index, itemobj) { var id=result[index].id; var name=result[index].lableName; var type=result[index].type; var createTime=result[index].createTime; var parentId=result[index].parentId; var sort=result[index].sort; var status=result[index].status; if(parentId == 0){ htmlContent += "<tr class=\"treegrid-"+id+"\" id="+id+">"; htmlContent += "<td>"+name+"</td>"; if(type == 1){ htmlContent += "<td><span class=\"label label-primary radius\">标签</span></td>"; } else if(type == 2){ htmlContent += "<td><span class=\"label label-secondary radius\">开源</span></td>"; } else if(type == 3){ htmlContent += "<td><span class=\"label label-success radius\">问与答</span></td>"; } htmlContent += "<td><input class=\"input-text\" type=\"text\" onclick=\"label_config.updateSort()\" data-id="+id+" name=\"sort\" value="+sort+" /></td>"; if(status == 1){ htmlContent += "<td><span class=\"label label-primary radius\">正常</span></td>"; } else if(status == 0){ htmlContent += "<td><span class=\"label label-warning radius\">冻结</span></td>"; } htmlContent += "<td>"+createTime+"</td>"; htmlContent +="<td>" + "<input class=\"btn btn-primary-outline radius\" type=\"button\" onclick=\"label_config.addChildLabel("+id+")\" value=\"添加子标签\">  " + "<input class=\"btn btn-secondary-outline radius\" type=\"button\" onclick=\"label_config.updateLabel("+id+")\" value=\"修改\">  " + "<input class=\"btn btn-success-outline radius\" type=\"button\" onclick=\"label_config.deleteLabel("+id+")\" value=\"删除\">" + "</td>"; htmlContent += "</tr>"; }else{ htmlContent += "<tr class=\"treegrid-"+id+" treegrid-parent-"+parentId+"\" id="+id+">"; htmlContent += "<td>"+name+"</td>"; if(type == 1){ htmlContent += "<td><span class=\"label label-primary radius\">标签</span></td>"; } else if(type == 2){ htmlContent += "<td><span class=\"label label-secondary radius\">开源</span></td>"; } else if(type == 3){ htmlContent += "<td><span class=\"label label-success radius\">问与答</span></td>"; } htmlContent += "<td><input class=\"input-text\" type=\"text\" onclick=\"label_config.updateSort()\" data-id="+id+" name=\"sort\" value="+sort+" /></td>"; if(status == 1){ htmlContent += "<td><span class=\"label label-primary radius\">正常</span></td>"; } else if(status == 0){ htmlContent += "<td><span class=\"label label-warning radius\">冻结</span></td>"; } htmlContent += "<td>"+createTime+"</td>"; htmlContent +="<td>" + "<input class=\"btn btn-primary-outline radius\" type=\"button\" onclick=\"label_config.addChildLabel("+id+")\" value=\"添加子标签\">  " + "<input class=\"btn btn-secondary-outline radius updateMenuBtn\" type=\"button\" onclick=\"label_config.updateLabel("+id+")\" value=\"修改\">  " + "<input class=\"btn btn-success-outline radius\" type=\"button\" onclick=\"label_config.deleteLabel("+id+")\" value=\"删除\">" + "</td>"; htmlContent += "</tr>"; } }); $("#labelGrid").html(htmlContent); $("#labelGrid").treegrid({ expanderExpandedClass: 'Hui-iconfont Hui-iconfont-add', expanderCollapsedClass: 'Hui-iconfont Hui-iconfont-jianhao' }); } }); } this.saveLabel=function(){ var id = $("#labelId").val(); var parentId = $("#parentId").val(); var type = $("#type").val(); var name = $.trim($("#name").val()); if(name==null || name==""){ layer.msg('名称不能为空!', {icon: 7}); return; } debugger var label={}; label.id = id; label.parentId = parentId; label.type = type; label.lableName = name; $.ajax({ url:'/label/saveLabel', type: "POST", dataType: "json",//跨域ajax请求,返回数据格式为json cache: false, timeout: 10000,//请求超时时间,单位为毫秒 async: true, global: false,//禁用Jquery全局事件 scriptCharset: 'UTF-8', //processData : false, // 告诉jQuery不要去处理发送的数据 contentType: 'application/json;charset=UTF-8',//请求内容的MIMEType data:JSON.stringify(label), success:function(responseData, status){ if(responseData.data==1){ self.listLabel(); $("#addLabelDialog").modal("hide"); layer.msg('操作成功!', {icon: 1}); }else if(responseData.data==-1){ layer.msg('相同类型下不能有相同名称,请修改!', {icon: 7}); }else{ layer.msg('操作失败!', {icon: 5}); } } }); } this.updateLabel=function(id){ self.clearFrom(); $.post("/label/getLabel",{"id":id},function(data){ if(data.success){ var result = data.data; $("#menu_title").text("修改标签"); $("#addLabelDialog").modal("show"); $("#labelId").val(result.id); $("#type").val(result.type); $("#name").val(result.lableName); $("#parentId").val(result.id); } }); } this.addChildLabel=function(id){ self.clearFrom(); $.post("/label/getLabel",{"id":id},function(data){ if(data.success){ var result = data.data; $("#addLabelDialog").modal("show"); $("#menu_title").text("【"+result.lableName+"】添加标签"); $("#parentId").val(result.id); } }); } this.deleteLabel=function(id){ self.clearFrom(); layer.confirm('确定删除吗?', { btn: ['确认','取消'] //按钮 }, function(){ $.post("/label/delLabel",{"id":id},function(data){ if(data.success){ layer.msg('操作成功!', {icon: 1}); self.listLabel(); } else{ layer.msg('操作失败!', {icon: 5}); } }); }, function(){ }); } //更新排序 this.updateSort=function(){ $("input[name=sort]").bind('keyup',function(event){ event=document.all?window.event:event; if((event.keyCode || event.which)==13){ var id = $(this).data('id') var sort = $(this).val(); if(!isNaN(sort)){ $.post('/label/updateOrder',{'id': id,'sort':sort},function (data) { if(data.success){ layer.msg('操作成功!', {icon: 1}); self.listLabel(); } }); } } }); } //清空表单 this.clearFrom=function(){ $("#labelId").val(""); $("#name").val(""); $("#parentId").val("0"); } self.init(); } const mongoose = require('mongoose') require('./restaurant') const restaurantSchema = require('mongoose').model('Restaurant').schema mongoose.set('useFindAndModify', false) const suggestionSchema = new mongoose.Schema({ type: { type: String, required: true, enum: ['ADD', 'REMOVE', 'EDIT'], }, data: { type: restaurantSchema, required: true, } }) suggestionSchema.set('toJSON', { transform: (document, returnedObject) => { returnedObject.id = returnedObject._id.toString() delete returnedObject._id delete returnedObject.__v } }) module.exports = mongoose.model('Suggestion', suggestionSchema) <reponame>emwsc/writive const utils = require("../../common/utils"); const randomColor = require("randomcolor"); const names = require("../names"); const process = require("process"); const roomConnections = {}; /** * Store connection info into global object * @param {string} room * @param {string} name * @param {string} socketId */ function pushConnection(room, name, socketId) { console.log(`${new Date().toLocaleString()} pushConnection ${socketId}`); if (!roomConnections[room]) roomConnections[room] = { clients: {}, count: 0 }; if (!roomConnections[room].clients[socketId]) { const pokemonIndex = utils.getRandomInt(1, 50); roomConnections[room].count++; roomConnections[room].clients[socketId] = { color: randomColor({ luminosity: "dark" }), name: "", socketId, imgSrc: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png` }; } roomConnections[room].clients[socketId].name = name; } /** * Handle user disconnect * @param {string} room * @param {string} socketId */ function popConnection(room, socketId) { console.log(`${new Date().toLocaleString()} popConnection ${socketId}`); if (roomConnections[room] && roomConnections[room].clients[socketId]) { roomConnections[room].count--; delete roomConnections[room].clients[socketId]; } } /** * Handle room events * @param {object} io Socket.io object * @param {object} socket */ function handleRoom(io, socket) { socket.on("join", function(room) { socket.join(room); names.getRandomName().then(name => { pushConnection(room, name, socket.id); io.to(room).emit("connectionsCountChanges"); }); socket.on("disconnect", function() { popConnection(room, socket.id); socket.to(room).emit("connectionsCountChanges"); }); socket.on("sendCurrentEditorState", function(data) { console.log(`${new Date().toLocaleString()} sendCurrentEditorState`); socket.broadcast .to(data.to) .emit("setCurrentEditorState", data.editorJson); }); io.in(room).clients((err, clients) => { if (clients.length > 0) socket.broadcast .to(clients[0]) .emit("getCurrentEditorState", socket.id); }); socket.on("emitTextEditorChanges", function(editorChanges) { console.log( `${new Date().toLocaleString()} emitTextEditorChanges ${ editorChanges.command }` ); socket.broadcast.to(room).emit("recieveTextEditorChanges", editorChanges); }); }); } function getConnectionsCountInRoom(room) { if (!roomConnections[room]) return 0; return roomConnections[room].count; } function getConnectionsInRoom(room) { if (!roomConnections[room]) return null; return roomConnections[room]; } module.exports = { handleRoom, getConnectionsCountInRoom, getConnectionsInRoom }; export { default as GlassCocktailOutlined } from './GlassCocktailOutlined'"use strict"; const app = require('../app'); const PORT = 8000; app.listen(PORT, () => { console.log(`Server Running on PORT: ${PORT}`); }); var config = require('./config'); var busywait = require('./busywait'); var express = require('express'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var jsbn = require('jsbn'); var app = express(); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.get('/primes/:number', (req, res, next) => { var bi = new jsbn.BigInteger(req.params.number); if (config.get('JPRIMER_SLOWDOWN')) { busywait( Math.floor((Math.random() * (config.get('JPRIMER_SLOWDOWN_CEIL') - config.get('JPRIMER_SLOWDOWN_FLOOR'))) + config.get('JPRIMER_SLOWDOWN_FLOOR')) ); } res.json({ number: bi.toString(), result: bi.isProbablePrime() }); next(); }); module.exports = app; <filename>src/components/Settings.js import React, { useEffect, useState } from "react"; import useThemes from "../contexts/themes/useThemes"; import DarkTheme from "../themes/DarkTheme"; import LightTheme from "../themes/LightTheme"; import "../css/Settings.css"; import ScreenTypes from "../helpers/ScreenTypes"; const Settings = ({ show }) => { let showClassName = "Settings"; let hideClassName = showClassName + " display-none"; let initialClassName = show === ScreenTypes.Settings ? showClassName : hideClassName; const [displayClassName, setDisplayClassName] = useState(initialClassName); const [darkTheme, setDarkTheme] = useState(false); const { state: {theme}, actions: {setTheme} } = useThemes(); useEffect(() => { let newDisplayClassName = show === ScreenTypes.Settings ? showClassName : hideClassName; setDisplayClassName(newDisplayClassName); }, [show]); return ( <div className={displayClassName} style={theme.menuScreen}> <div className="Settings-inner"> <button style={theme.button} onClick={() => { setTheme(!darkTheme ? DarkTheme : LightTheme); setDarkTheme(!darkTheme); }} > Dark Theme: {darkTheme ? "On" : "Off"} </button> </div> </div> ); }; export default Settings;<reponame>Dexus/node-compiler<filename>current/test/parallel/test-nodeeventtarget.js // Flags: --expose-internals --no-warnings 'use strict'; const common = require('../common'); const { Event, NodeEventTarget, } = require('internal/event_target'); const { deepStrictEqual, ok, strictEqual, } = require('assert'); const { on } = require('events'); { const eventTarget = new NodeEventTarget(); strictEqual(eventTarget.listenerCount('foo'), 0); deepStrictEqual(eventTarget.eventNames(), []); const ev1 = common.mustCall(function(event) { strictEqual(event.type, 'foo'); strictEqual(this, eventTarget); }, 2); const ev2 = { handleEvent: common.mustCall(function(event) { strictEqual(event.type, 'foo'); strictEqual(this, ev2); }) }; eventTarget.addEventListener('foo', ev1); eventTarget.addEventListener('foo', ev2, { once: true }); strictEqual(eventTarget.listenerCount('foo'), 2); ok(eventTarget.dispatchEvent(new Event('foo'))); strictEqual(eventTarget.listenerCount('foo'), 1); eventTarget.dispatchEvent(new Event('foo')); eventTarget.removeEventListener('foo', ev1); strictEqual(eventTarget.listenerCount('foo'), 0); eventTarget.dispatchEvent(new Event('foo')); } { const eventTarget = new NodeEventTarget(); strictEqual(eventTarget.listenerCount('foo'), 0); deepStrictEqual(eventTarget.eventNames(), []); const ev1 = common.mustCall((event) => { strictEqual(event.type, 'foo'); }, 2); const ev2 = { handleEvent: common.mustCall((event) => { strictEqual(event.type, 'foo'); }) }; strictEqual(eventTarget.on('foo', ev1), eventTarget); strictEqual(eventTarget.once('foo', ev2, { once: true }), eventTarget); strictEqual(eventTarget.listenerCount('foo'), 2); eventTarget.dispatchEvent(new Event('foo')); strictEqual(eventTarget.listenerCount('foo'), 1); eventTarget.dispatchEvent(new Event('foo')); strictEqual(eventTarget.off('foo', ev1), eventTarget); strictEqual(eventTarget.listenerCount('foo'), 0); eventTarget.dispatchEvent(new Event('foo')); } { const eventTarget = new NodeEventTarget(); strictEqual(eventTarget.listenerCount('foo'), 0); deepStrictEqual(eventTarget.eventNames(), []); const ev1 = common.mustCall((event) => { strictEqual(event.type, 'foo'); }, 2); const ev2 = { handleEvent: common.mustCall((event) => { strictEqual(event.type, 'foo'); }) }; eventTarget.addListener('foo', ev1); eventTarget.once('foo', ev2, { once: true }); strictEqual(eventTarget.listenerCount('foo'), 2); eventTarget.dispatchEvent(new Event('foo')); strictEqual(eventTarget.listenerCount('foo'), 1); eventTarget.dispatchEvent(new Event('foo')); eventTarget.removeListener('foo', ev1); strictEqual(eventTarget.listenerCount('foo'), 0); eventTarget.dispatchEvent(new Event('foo')); } { const eventTarget = new NodeEventTarget(); strictEqual(eventTarget.listenerCount('foo'), 0); deepStrictEqual(eventTarget.eventNames(), []); // Won't actually be called. const ev1 = () => {}; // Won't actually be called. const ev2 = { handleEvent() {} }; eventTarget.addListener('foo', ev1); eventTarget.addEventListener('foo', ev1); eventTarget.once('foo', ev2, { once: true }); eventTarget.once('foo', ev2, { once: false }); eventTarget.on('bar', ev1); strictEqual(eventTarget.listenerCount('foo'), 2); strictEqual(eventTarget.listenerCount('bar'), 1); deepStrictEqual(eventTarget.eventNames(), ['foo', 'bar']); eventTarget.removeAllListeners('foo'); strictEqual(eventTarget.listenerCount('foo'), 0); strictEqual(eventTarget.listenerCount('bar'), 1); deepStrictEqual(eventTarget.eventNames(), ['bar']); eventTarget.removeAllListeners(); strictEqual(eventTarget.listenerCount('foo'), 0); strictEqual(eventTarget.listenerCount('bar'), 0); deepStrictEqual(eventTarget.eventNames(), []); } { const target = new NodeEventTarget(); process.on('warning', common.mustCall((warning) => { ok(warning instanceof Error); strictEqual(warning.name, 'MaxListenersExceededWarning'); strictEqual(warning.target, target); strictEqual(warning.count, 2); strictEqual(warning.type, 'foo'); ok(warning.message.includes( '2 foo listeners added to NodeEventTarget')); })); strictEqual(target.getMaxListeners(), NodeEventTarget.defaultMaxListeners); target.setMaxListeners(1); target.on('foo', () => {}); target.on('foo', () => {}); } (async () => { // test NodeEventTarget async-iterability const emitter = new NodeEventTarget(); const interval = setInterval(() => { emitter.dispatchEvent(new Event('foo')); }, 0); let count = 0; for await (const [ item ] of on(emitter, 'foo')) { count++; strictEqual(item.type, 'foo'); if (count > 5) { break; } } clearInterval(interval); })().then(common.mustCall()); <gh_stars>0 /* davclient.umd.js rewrite davclient.js as umd mode. edit by editcue */ /* davclient.js - Low-level JavaScript WebDAV client implementation Supports following methods: MKCOL, MOVE, GET, DELETE, COPY, PUT, PROPFIND Copyright (C) <NAME> email <EMAIL> Inspired by implementation of <NAME> http://debris.demon.nl/projects/davclient.js/ 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ (function(root, factory) { if (typeof module === 'object' && typeof module.exports === 'object') { //commonjs module.exports = factory(); } else if (typeof define === 'function' && define.amd) { //AMD like require.js define(factory) } else if (typeof define === 'function' && define.cmd) { //CMD like sea.js' define(function(require, exports, module) { module.exports = factory() }) } else { //with no module root.umdModule = factory(); } }(this, function() { let string = new function() { var string = this; this.strip = function strip(s) { /* returns a string with all leading and trailing whitespace removed */ var stripspace = /^\s*([\s\S]*?)\s*$/; return stripspace.exec(s)[1]; }; this.deentitize = function deentitize(s) { /* convert all standard XML entities to the corresponding characters */ // first numbered entities var numberedreg = /&#(x?)([a-f0-9]{2,});/ig; while (true) { var match = numberedreg.exec(s); if (!match) { break; }; var value = match[2]; var base = 10; if (match[1]) { base = 16; }; value = String.fromCharCode(parseInt(value, base)); s = s.replace(new RegExp(match[0], 'g'), value); }; // and standard ones s = s.replace(/>/g, '>'); s = s.replace(/</g, '<'); s = s.replace(/'/g, "'"); s = s.replace(/"/g, '"'); s = s.replace(/&/g, '&'); s = s.replace(/ /g, ""); // remove the xml declaration as E4X cannot parse it s = s.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, ""); return s; }; this.encodeBase64 = function encodeBase64(input) { return base64.encode(input); } var base64 = { // private property _keyStr : "<KEY> // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + base64._keyStr.charAt(enc1) + base64._keyStr.charAt(enc2) + base64._keyStr.charAt(enc3) + base64._keyStr.charAt(enc4); } return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } } }; let davlib = new function() { /* WebDAV for JavaScript This is a library containing a low-level and (if loaded, see 'davfs.js') a high-level API for working with WebDAV capable servers from JavaScript. Quick example of the low-level interface: var client = new davlib.DavClient(); client.initialize(); function alertContent(status, statusstring, content) { if (status != 200) { alert('error: ' + statusstring); return; }; alert('content received: ' + content); }; client.GET('/foo/bar.txt', alertContent); Quick example of the high-level interface: var fs = new davlib.DavFS(); fs.initialize(); function alertContent(error, content) { if (error) { alert('error: ' + error); return; }; alert('content: ' + content); }; fs.read('/foo/bar.txt', alertContent); */ var davlib = this; this.DEBUG = 0; this.STATUS_CODES = { '100': 'Continue', '101': 'Switching Protocols', '102': 'Processing', '200': 'OK', '201': 'Created', '202': 'Accepted', '203': 'None-Authoritive Information', '204': 'No Content', '205': 'Reset Content', '206': 'Partial Content', '207': 'Multi-Status', '300': 'Multiple Choices', '301': 'Moved Permanently', '302': 'Found', '303': 'See Other', '304': 'Not Modified', '305': 'Use Proxy', '307': 'Redirect', '400': 'Bad Request', '401': 'Unauthorized', '402': 'Payment Required', '403': 'Forbidden', '404': 'Not Found', '405': 'Method Not Allowed', '406': 'Not Acceptable', '407': 'Proxy Authentication Required', '408': 'Request Time-out', '409': 'Conflict', '410': 'Gone', '411': 'Length Required', '412': 'Precondition Failed', '413': 'Request Entity Too Large', '414': 'Request-URI Too Large', '415': 'Unsupported Media Type', '416': 'Requested range not satisfiable', '417': 'Expectation Failed', '422': 'Unprocessable Entity', '423': 'Locked', '424': 'Failed Dependency', '500': 'Internal Server Error', '501': 'Not Implemented', '502': 'Bad Gateway', '503': 'Service Unavailable', '504': 'Gateway Time-out', '505': 'HTTP Version not supported', '507': 'Insufficient Storage' }; this.DavClient = function() { /* Low level (subset of) WebDAV client implementation Basically what one would expect from a basic DAV client, it provides a method for every HTTP method used in basic DAV, it parses PROPFIND requests to handy JS structures and accepts similar structures for PROPPATCH. Requests are handled asynchronously, so instead of waiting until the response is sent back from the server and returning the value directly, a handler is registered that is called when the response is available and the method that sent the request is ended. For that reason all request methods accept a 'handler' argument, which will be called (with 3 arguments: statuscode, statusstring and content (the latter only where appropriate)) when the request is handled by the browser. The reason for this choice is that Mozilla sometimes freezes when using XMLHttpRequest for synchronous requests. The only 'public' methods on the class are the 'initialize' method, that needs to be called first thing after instantiating a DavClient object, and the methods that have a name similar to an HTTP method (GET, PUT, etc.). The latter all get at least a 'path' argument, a 'handler' argument and a 'context' argument: 'path' - an absolute path to the target resource 'handler' - a function or method that will be called once the request has finished (see below) 'context' - the context used to call the handler, the 'this' variable inside methods, so usually the object (instance) the handler is bound to (ignore when the handler is a function) All handlers are called with the same 3 arguments: 'status' - the HTTP status code 'statusstring' - a string representation (see STATUS_CODES array above) of the status code 'content' - can be a number of different things: * when there was an error in a method that targets a single resource, this contains the error body * when there was an error in a method that targets a set of resources (multi-status) it contains a Root object instance (see below) that contains the error messages of all the objects * if the method was GET and there was no error, it will contain the contents of the resource * if the method was PROPFIND and there was no error, it will contain a Root object (see below) that contains the properties of all the resources targeted * if there was no error and there is no content to return, it will contain null 'headers' - a mapping (associative array) from lowercase header name to value (string) Basic usage example: function handler(status, statusstring, content, headers) { if (content) { if (status != '200' && status != '204') { if (status == '207') { alert('not going to show multi-status ' + here...'); }; alert('Error: ' + statusstring); } else { alert('Content: ' + content); }; }; }; var dc = new DavClient(); dc.initialize('localhost'); // create a directory dc.MKCOL('/foo', handler); // create a file and save some contents dc.PUT('/foo/bar.txt', 'baz?', handler); // load and alert it (alert happens in the handler) dc.GET('/foo/bar.txt', handler); // delete the dir dc.DELETE('/foo', handler); For detailed information about the HTTP methods and how they can/should be used in a DAV context, see http://www.webdav.org. If you have questions, bug reports, or patches, please file a report on https://github.com/svogler/jsdavclient */ }; this.DavClient.prototype.initialize = function(host, port, protocol, username, password) { /* the 'constructor' (needs to be called explicitly!!) host - the host name or IP port - HTTP port of the host (optional, defaults to 80) protocol - protocol part of URLs (optional, defaults to http) username - the username for authorization (only Basic auth is supported at that time) password - <PASSWORD> */ this.host = host || location.hostname; this.port = port || location.port || 443; this.protocol = (protocol || location.protocol.substr(0, location.protocol.length - 1 ) || 'https'); this.username = username || null; this.password = password || <PASSWORD>; this.request = null; }; this.DavClient.prototype.OPTIONS = function(path, handler, context) { /* perform an OPTIONS request find out which HTTP methods are understood by the server */ // XXX how does this work with * paths? var request = this._getRequest('OPTIONS', path, handler, context); request.send(''); }; this.DavClient.prototype.GET = function(path, handler, context) { /* perform a GET request retrieve the contents of a resource */ var request = this._getRequest('GET', path, handler, context); request.send(''); }; this.DavClient.prototype.PUT = function(path, content, handler, context, locktoken) { /* perform a PUT request save the contents of a resource to the server 'content' - the contents of the resource */ var request = this._getRequest('PUT', path, handler, context); request.setRequestHeader("Content-type", "text/xml,charset=UTF-8"); if (locktoken) { request.setRequestHeader('If', '<' + locktoken + '>'); }; request.send(content); }; this.DavClient.prototype.PROPFIND = function(path, handler, context, depth) { /* perform a PROPFIND request read the metadata of a resource (optionally including its children) 'depth' - control recursion depth, default 0 (only returning the properties for the resource itself) */ var request = this._getRequest('PROPFIND', path, handler, context); depth = depth || 0; request.setRequestHeader('Depth', depth); request.setRequestHeader('Content-type', 'text/xml; charset=UTF-8'); // XXX maybe we want to change this to allow getting selected props var xml = '<?xml version="1.0" encoding="UTF-8" ?>' + '<D:propfind xmlns:D="DAV:">' + '<D:allprop />' + '</D:propfind>'; request.send(xml); }; this.DavClient.prototype.DELETE = function(path, handler, context, locktoken) { /* perform a DELETE request remove a resource (recursively) */ var request = this._getRequest('DELETE', path, handler, context); if (locktoken) { request.setRequestHeader('If', '<' + locktoken + '>'); }; //request.setRequestHeader("Depth", "Infinity"); request.send(''); }; this.DavClient.prototype.MKCOL = function(path, handler, context, locktoken) { /* perform a MKCOL request create a collection */ var request = this._getRequest('MKCOL', path, handler, context); if (locktoken) { request.setRequestHeader('If', '<' + locktoken + '>'); }; request.send(''); }; this.DavClient.prototype.COPY = function(path, topath, handler, context, overwrite, locktoken) { /* perform a COPY request create a copy of a resource 'topath' - the path to copy the resource to 'overwrite' - whether or not to fail when the resource already exists (optional) */ var request = this._getRequest('COPY', path, handler, context); var tourl = this._generateUrl(topath); request.setRequestHeader("Destination", tourl); if (overwrite) { request.setRequestHeader("Overwrite", "F"); }; if (locktoken) { request.setRequestHeader('If', '<' + locktoken + '>'); }; request.send(''); }; this.DavClient.prototype.MOVE = function(path, topath, handler, context, overwrite, locktoken) { /* perform a MOVE request move a resource from location 'topath' - the path to move the resource to 'overwrite' - whether or not to fail when the resource already exists (optional) */ var request = this._getRequest('MOVE', path, handler, context); var tourl = this._generateUrl(topath); request.setRequestHeader("Destination", tourl); if (overwrite) { request.setRequestHeader("Overwrite", "F"); }; if (locktoken) { request.setRequestHeader('If', '<' + locktoken + '>'); }; request.send(''); }; this.DavClient.prototype._getRequest = function(method, path, handler, context) { /* prepare a request */ var request = davlib.getXmlHttpRequest(); request.onreadystatechange = this._wrapHandler(handler, request, context); var url = this._generateUrl(path); request.open(method, url, true); request.setRequestHeader('Accept-Encoding', ' '); request.setRequestHeader('Authorization', this._createBasicAuth(this.username, this.password)); return request }; this.DavClient.prototype._wrapHandler = function(handler, request, context) { /* wrap the handler with a callback The callback handles multi-status parsing and calls the client's handler when done */ var self = this; function HandlerWrapper() { this.execute = function() { console.log(JSON.stringify(request)) if (request.readyState == 4) { var status = request.status.toString(); var headers = self._parseHeaders(request.getAllResponseHeaders()); var content = request.responseText; var statusstring = davlib.STATUS_CODES[status]; handler.call(context, status, statusstring, content, headers); }; }; }; return (new HandlerWrapper().execute); }; this.DavClient.prototype._generateUrl = function(path){ /* convert a url from a path */ var url = this.protocol + '://' + this.host; if (this.port) { url += ':' + this.port; }; url += path; return url; }; this.DavClient.prototype._createBasicAuth = function (user, password) { var tok = user + ':' + password; var hash = string.encodeBase64(tok); return "Basic " + hash; } this.DavClient.prototype._parseHeaders = function(headerstring) { var lines = headerstring.split('\n'); var headers = {}; for (var i=0; i < lines.length; i++) { var line = string.strip(lines[i]); if (!line) { continue; }; var chunks = line.split(':'); var key = string.strip(chunks.shift()); var value = string.strip(chunks.join(':')); var lkey = key.toLowerCase(); if (headers[lkey] !== undefined) { if (!headers[lkey].push) { headers[lkey] = [headers[lkey, value]]; } else { headers[lkey].push(value); }; } else { headers[lkey] = value; }; }; return headers; }; // some helper functions this.getXmlHttpRequest = function() { /* instantiate an XMLHTTPRequest this can be improved by testing the user agent better and, in case of IE, finding out which MSXML is installed and such, but it seems to work just fine for now */ try{ return new XMLHttpRequest(); } catch(e) { // not a Mozilla or Konqueror based browser }; try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) { // not IE either... }; alert('Your browser does not support XMLHttpRequest, required for ' + 'WebDAV access.'); throw('Browser not supported'); }; this.debug = function(text) { /* simple debug function set the DEBUG global to some true value, and messages will appear on the bottom of the document */ if (!davlib.DEBUG) { return; }; var div = document.createElement('div'); var text = document.createTextNode(text); div.appendChild(text); document.getElementsByTagName('body')[0].appendChild(div); }; }(); return davlib })) <filename>cmds/help.js const config = require('../config.json'); module.exports.run = async (bot, message, args) => { if(!args[0]){ let cmds = ""; let array = bot.commands.array(); array.forEach(function(item, index, array) { cmds += config.prefix + item.help.name + " " + item.help.arguments +"\n"; }); message.author.send("```Available commands are:\n[] = optional\n\n"+cmds+"\nType !help <command> for more details```"); } else { var settings = bot.settings.get(message.guild.id); switch(args[0]){ case "avatar": message.author.send("```Type !avatar with no argument to display your own avatar or tag someone else to display their avatar.```"); break; case "grift": message.author.send("```To view the default arguments type \""+settings.prefix+"grift view defaults\".\n\nAdding \"dm\" will send a Direct Message and \"public\" will send the message into the channel typed.\n\nAdd a # to view a single result or \"# to #\" for a range. i.e. \""+settings.prefix+"grift 300\" will display only rank 300 but \""+settings.prefix+"grift 300 to 305\" will display the range of 300 to 305\n\n Available arguments are:\n<dm|public> <#[to #]> <us|eu|kr|tw> <sc|soft|softcore|hc|hard|hardcore> <barb|barbarian|cru|sader|crusader|dh|demon|demonhunter|monk|wd|witch|witchdoctor|wiz|wizard|nec|necro|necromancer|t2|team2|t3|team3|t4|team4> <season|seasonal|ns|era|nonseasonal>```"); break; case "speak": message.author.send("```Stay awhile and listen!```"); break; case "settings": message.author.send("```Default settings can be changed if you have the D3Mod role. To change the default settings type in the desired arguments.\n\nAvailable arguments are:\n<dm|public> <us|eu|kr|tw> <sc|soft|softcore|hc|hard|hardcore> <barb|barbarian|cru|sader|crusader|dh|demon|demonhunter|monk|wd|witch|witchdoctor|wiz|wizard|nec|necro|necromancer|t2|team2|t3|team3|t4|team4> <season|seasonal|ns|era|nonseasonal>```"); break; } } } module.exports.help = { name: "help", arguments: "" } <reponame>samdturner/PartnerSaver import request from 'axios'; import metaTagsManager from './metaTagsManager'; const TASKS_URL = 'api/tasks'; const PARTNERS_URL = 'api/partners'; export default { fetchTasks(params) { return request({ method: 'GET', url: TASKS_URL, params: params, responseType: 'json' }); }, postTask(params) { return request({ method: 'POST', url: TASKS_URL, params: params, responseType: 'json' }); }, updateTask(params) { const taskPutUrl = TASKS_URL + "/" + params.id; return request({ method: 'PUT', url: taskPutUrl, params: params, responseType: 'json' }); }, deleteTask(params) { const taskDeleteUrl = TASKS_URL + "/" + params.id; return request({ method: 'DELETE', url: taskDeleteUrl, params: params, responseType: 'json' }); }, fetchPartners(params) { return request({ method: 'GET', url: PARTNERS_URL, params: params, responseType: 'json' }); }, postPartner(params) { return request({ method: 'POST', url: PARTNERS_URL, params: params, responseType: 'json' }); }, deletePartner(params) { const partnerDeleteUrl = PARTNERS_URL + "/" + params.id; return request({ method: 'DELETE', url: partnerDeleteUrl, params: params, responseType: 'json' }); }, putPartner(params) { const partnerPutUrl = PARTNERS_URL + "/" + params.id; return request({ method: 'PUT', url: partnerPutUrl, params: params, responseType: 'json' }); } }; <reponame>danmihaipatrascu/opentrans myApp.controller('PortofoliuCtrl', function ($scope, $http, $uibModal) { //$scope.masini = []; loadPortofoliu(); function loadPortofoliu() { $http.get("resources/portofoliu.json") .then(function (response) { $scope.pozeBeclean = response.data.beclean; $scope.pozeTRC = response.data.trc; $scope.pozeNovis = response.data.novis; $scope.pozeInstalatiiExterioareTRC = response.data.instalatiiExterioareTRC; $scope.margau = response.data.margau; $scope.bazaTehnica = response.data.bazaTehnica; }); } function setImagesForSlides(lucrare) { var slides = []; switch (lucrare) { case 'beclean': angular.forEach($scope.pozeBeclean, function (poza) { slides.push({ image: poza.urls[0], text: poza.nume, id: poza.id - 1 }); }); return slides; break; case 'novis': angular.forEach($scope.pozeNovis, function (poza) { slides.push({ image: poza.urls[0], text: poza.nume, id: poza.id - 1 }); }); return slides; break; case 'trc': angular.forEach($scope.pozeTRC, function (poza) { slides.push({ image: poza.urls[0], text: poza.nume, id: poza.id - 1 }); }); return slides; break; case 'instalatii_exterioare_trc': angular.forEach($scope.pozeInstalatiiExterioareTRC, function (poza) { slides.push({ image: poza.urls[0], text: poza.nume, id: poza.id - 1 }); }); return slides; break; case 'margau': angular.forEach($scope.margau, function (poza) { slides.push({ image: poza.urls[0], text: poza.nume, id: poza.id - 1 }); }); return slides; break; case 'bazaTehnica': angular.forEach($scope.bazaTehnica, function (poza) { slides.push({ image: poza.urls[0], text: poza.nume, id: poza.id - 1 }); }); return slides; break; } } $scope.openSlider = function (lucrare) { $uibModal.open({ templateUrl: "/views/modals/sliderModal.html", size: 'lg', controller: [ "$scope", function ($scope) { $scope.slides = setImagesForSlides(lucrare); console.log($scope.items); $scope.myInterval = 5000; $scope.noWrapSlides = false; $scope.active = 0; var currIndex = 0; } ] }); }; $scope.myInterval = 5000; $scope.noWrapSlides = false; $scope.active = 0; var currIndex = 0; });import React from "react"; import "./styles/Navbar.css"; import vacalogo from "../images/logovaca.svg" class Navbar extends React.Component{ render() { return ( <div className="Navbar"> <div className="container-fluid"> <a className="Navbar__brand" href="/"> <img className="Navbar__brand-logo" src={vacalogo} alt="logo"></img> <span className="font-weight-light" >Cow</span> <span className="font-weight-bold" >List</span> </a> </div> </div> ) } } export default Navbar;<gh_stars>100-1000 import React from 'react'; import PropTypes from 'prop-types'; import { action } from '@storybook/addon-actions'; import { Actions } from '@talend/react-components'; import { UIForm } from '../src/UIForm'; function CustomArrayTemplate(props) { const { canReorder, id, onAdd, onRemove, onReorder, renderItem, schema, value } = props; return ( <div> <style> {` ol { list-style: none; } .icon-up svg { transform: rotate(180deg); } `} </style> <legend>This is a custom array template</legend> <ol id={id} style={{ listStyle: 'none' }}> {value.map((itemValue, index) => { const actions = [ { label: 'Remove', icon: 'talend-trash', onClick: event => onRemove(event, index), bsStyle: 'primary', }, ]; if (canReorder) { actions.push( { label: 'Move Up', icon: 'talend-caret-down', className: 'icon-up', onClick: event => onReorder(event, { previousIndex: index, nextIndex: index - 1, }), }, { label: 'Move Down', icon: 'talend-caret-down', onClick: event => onReorder(event, { previousIndex: index, nextIndex: index + 1, }), }, ); } return ( <li key={index}> <Actions actions={actions} hideLabel /> {renderItem(index)} </li> ); })} </ol> <div> <button type="button" className="btn btn-info" onClick={onAdd}> New Element </button> </div> </div> ); } CustomArrayTemplate.propTypes = { canReorder: PropTypes.bool, id: PropTypes.string, onAdd: PropTypes.func.isRequired, onRemove: PropTypes.func.isRequired, onReorder: PropTypes.func.isRequired, renderItem: PropTypes.func.isRequired, schema: PropTypes.object.isRequired, value: PropTypes.arrayOf(PropTypes.object).isRequired, }; function story() { const templates = { array: CustomArrayTemplate }; const schema = { jsonSchema: { title: 'Custom array', type: 'object', properties: { list: { type: 'array', items: { type: 'string', }, }, }, }, properties: { list: ['one', 'two'], }, uiSchema: ['list'], }; return ( <div> <UIForm templates={templates} data={schema} onChange={action('Change')} onSubmit={action('onSubmit')} /> </div> ); } export default { name: 'Core Custom template', story, }; const keyWelcome = "Welcome" class WelcomeManager { constructor(s) { this.storage = s this.prefix = keyWelcome } async getMessage() { return await this.storage.getValue(this.prefix) } async getEnabled() { return await this.storage.getValueEnabled(this.prefix) } async setEnabled(val) { return await this.storage.setValueEnabled(this.prefix, val) } async setMessage(text) { return await this.storage.setValue(this.prefix, text) } async checkIsFirst(id) { let k = 'w/' + id let firstMsg = await this.storage.getValueEnabled(k) if (firstMsg != undefined) { return false } await this.storage.setValueEnabled(k, true) return true } async handleNewMsg(id) { if (!await this.getEnabled() || !window.waAPI) { return } let msg = await this.getMessage() if (msg == undefined) { return } window.waAPI.sendTextMessage(id, msg) return true } } export default WelcomeManager<gh_stars>0 import EncountersList from './components/EncountersList'; export { EncountersList }; /*global define*/ define(function () { 'use strict'; var LoginController = function ($scope, $state, AuthenticationService, progression) { this.$scope = $scope; this.$state = $state; this.progression = progression; $scope.credentials = { username: 'admin', password: '<PASSWORD>' }; $scope.$on('event:auth-login-failed', function(even, data) { progression.done(); $scope.errorMessage = data.message ? 'status.'+ data.code : 'Bad credentials'; }); $scope.$on('event:auth-login-complete', function() { $state.go($state.get('dashboard')); progression.done(); }); $scope.submit = function(credentials) { progression.start(); AuthenticationService.login(credentials); }; $scope.cancel = function () { AuthenticationService.cancel(); }; $scope.$on('$destroy', this.destroy.bind(this)); }; LoginController.prototype.destroy = function () { this.$scope = undefined; this.$state = undefined; }; LoginController.$inject = ['$scope', '$state', 'AuthenticationService', 'progression']; return LoginController; });<gh_stars>1-10 (function(){ function BoardController($scope, $location, $transitions, ForumService){ var vm = this; vm.getBoard = function(){ var boardId = $location.search().boardId; ForumService.getBoard(vm, boardId, $scope); }; vm.deregisterTransition = $transitions.onStart({}, function(transition) { /*vm.usersViewingSub.unsubscribe(); vm.usersViewingSub = null; vm.deregisterTransition();*/ }); vm.threadChecked = function(){ vm.checked = false for(var i = 0; i < vm.board.threads.length; i++){ if(vm.board.threads[i].isChecked){ vm.checked = true; return; } } if(vm.checked === false){ for(var i = 0; i < vm.board.stickyThreads.length; i++){ if(vm.board.stickyThreads[i].isChecked){ vm.checked = true; break; } } } }; function getCheckedThreads(threads){ var threadIds = threads.map(function(x){ if(x.isChecked === true){ return x.threadId; } }); return threadIds; } vm.stickyUnstickyThreads = function(){ var threadIds = getCheckedThreads(vm.board.threads); var stickyThreadIds = getCheckedThreads(vm.board.stickyThreads); threadIds = threadIds.concat(stickyThreadIds); ForumService.stickyUnstickyThreads(vm, vm.board.forumId, threadIds); }; vm.lockUnlockThreads = function(){ var threadIds = getCheckedThreads(vm.board.threads); var stickyThreadIds = getCheckedThreads(vm.board.stickyThreads); threadIds = threadIds.concat(stickyThreadIds); ForumService.lockUnlockThreads(vm, vm.board.forumId, threadIds); }; vm.goToThreadMove = function(){ ForumService.goToThreadMove(vm); }; vm.getBoard(); vm.checkedThreads = {}; } angular.module('zfgc.forum') .controller("BoardCtrl",['$scope', '$location', '$transitions', 'ForumService', BoardController]); })();import React from 'react'; import { Card } from 'react-bootstrap'; import './SearchResults.css'; import NominateBtn from '../NominateBtn/NominateBtn'; function SearchResults(props) { return ( <div className="d-flex"> {!props.movies.length ? <Card className="noResultsCard"> <Card.Title className="noResults"> No search results to display yet. </Card.Title> </Card> : <div /> } {props.movies.map((movie, index) => <div className="image-container justify-content-start m-3"> <img src={movie.Poster} alt="moviePoster"/> <div className="d-flex align-items-center overlay justify-content-center"><NominateBtn movie={movie} title={movie.Title} year={movie.Year} nominateMovie={props.nominateMovie} disabled={props.disabled}/></div> </div> )} </div> ) } export default SearchResults;<gh_stars>0 'use strict' const TestRunner = require('test-runner') const jsdocParse = require('../') const fs = require('fs') const a = require('assert') const runner = new TestRunner() runner.test('api: valid json out', function () { const jsdocOutput = JSON.parse(fs.readFileSync('./test/fixture/jsdoc-input.json', 'utf8')) const data = jsdocParse(jsdocOutput) a.strictEqual(data[0].name, 'Chainable') }) require('./bootstrap'); $.trumbowyg.svgPath = '/svg/wyswig-icons.svg'; $(document).ready(function () { $('.textarea-wysiwyg').trumbowyg(); $('.carousel.carousel-slider').carousel({ fullWidth: true, indicators: true }); $('.sidenav').sidenav(); $('.collapsible').collapsible(); $('select').formSelect(); }); <reponame>vczero/mast<gh_stars>0 /* * 整个框架的配置文件 * * * */ define(function () { var dir = Speed.dir; require.config({ waitSeconds : 20, shim : {}, paths : { /*3lib*/ $ : dir + '3lib/zepto', FastClick : dir + '3lib/fastclick', text : dir + '3lib/require.text', Class : dir + '3lib/class', /*common*/ UA : dir + 'common/ua', /*core*/ appInit : dir + 'core/app.init', container : dir + 'core/container' } }); });const getLegend = (components) => { const Lg = {}; const legend = $('#legend'); let year = 2015; let tempLayers; Lg.hasViews = true; let layers; let plans; function initEvents() { const { dispatch } = components; $('.legend-toggle').click(() => { toggleSidebar(); }); $('.legend-contents').on('change', function onChange() { // checkbox clicks dispatch.call('setlayers', this, Lg.layers()); }); } function toggleSidebar() { legend.toggleClass('collapsed').addClass('subsequent'); resizeLegendButton(); } function openSidebar() { if (legend.hasClass('collapsed')) { toggleSidebar(); } } Lg.closeSidebar = () => { $('#legend').addClass('collapsed'); }; Lg.openSidebar = openSidebar; function drawSidebarContent() { const { init, } = components; const { server, } = init; setCurrentPlans(); resizeLegendButton(); $('.legend-contents').empty(); // get layer data $.getJSON(`${server}layers/${year}`, (layersJson) => { const { dispatch } = components; const { names } = init; // console.log('names', names); layers = layersJson; // console.log('legend layers', layersJson); _.each(layersJson, (category, categoryName) => { const cat = $('<div>') .attr('class', 'legend-category') .attr('data-category', 'feature') .appendTo('.legend-contents'); // console.log('layers', layersJson); // console.log('cat name', categoryName); const title = names[categoryName.toLowerCase()].toUpperCase(); $('<div>') .attr('class', 'category-title') .html(title) .appendTo(cat); _.each(category, (obj, objName) => { // there's an extra level here if (obj.features) addLayerGroup(obj, objName); else _.each(obj, addLayerGroup); }); function addLayerGroup(group, groupName) { const { names } = init; const value = group.id !== undefined ? group.id : [...new Set(Object.keys(group.features).map(d => group.features[d].id))] .join('&'); const gr = $('<div>').attr('class', 'legend-group').attr('data-group', groupName).appendTo(cat); const groupTitle = $('<div>').attr('class', 'group-title').appendTo(gr); $('<label>') // .html(names[groupName.toLowerCase()] || groupName) .prepend(`<input type="checkbox" value="${value}"checked>`) .appendTo(groupTitle); _.each(group.features, (feature, key) => { const layer = $('<div>').attr('class', 'layer').appendTo(gr); addLayerExisting(feature, key, layer); // console.log(feature, key); if (feature.style) { addSwatch(feature.style).appendTo(layer); layer.addClass('styled'); } }); // console.log('group', group); addSwatch(group.style).appendTo(groupTitle); $('<div>') .attr('class', 'group-name') .html(names[groupName.toLowerCase()] || groupName) .appendTo(groupTitle); } }); dispatch.call('setlayers', this, Lg.layers()); dispatch.call('statechange', this); if (tempLayers) { Lg.layers(tempLayers); tempLayers = null; dispatch.call('setlayers', this, Lg.layers()); dispatch.call('statechange', this); } if (plans.length > 0) { addPlans(); } }); } function updateYear(y) { if (y === year) return; year = y; } function addPlans() { const { dispatch, translations, init, } = components; const { language } = init; const cat = $('<div>') .attr('class', 'legend-category') .attr('data-category', 'feature') .prependTo('.legend-contents'); $('<div>') .attr('class', 'category-title') .html(translations.find(d => d.name === 'plans')[language].toUpperCase()) .appendTo(cat); plans.forEach((plan) => { const row = $('<div>').attr('class', 'search-result plan-legend-row') .append('<i class="icon-right-dir"></i>') .append('<i class="icon-down-dir"></i>') .appendTo(cat); $(`<span>${plan.planname}</span>`) .appendTo(row) .on('click', function click() { if (!row.hasClass('selected')) { $('.search-result.selected').removeClass('selected'); row.addClass('selected'); if (!row.hasClass('expanded')) $(this).prev().click(); dispatch.call('drawplanfeature', this, plan); } else { row.removeClass('selected'); if (row.hasClass('expanded')) $(this).prev().click(); dispatch.call('removehighlight', this); } }) .prepend('<i class="icon-binoculars">'); $('i.icon-right-dir, i.icon-down-dir', row).on('click', () => { if (row.hasClass('expanded')) { row.removeClass('expanded'); } else { row.addClass('expanded'); if (!$('.result-details', row).length) { const details = $('<div>') .attr('class', 'result-details') .appendTo(row); details.html(plan.planyear); } } }); }); } function setCurrentPlans() { const { init } = components; // filter to find plans for selected year plans = init.plans.filter((d) => { if (d.years.length === 1) { return d.years[0] === year; } return d.years[0] <= year && d.years[1] >= year; }); } function getPlansForLayer(layer) { if (!plans) return; let planArray; plans.forEach((plan) => { if (plan.features.indexOf(layer) !== -1) { if (!planArray) planArray = []; planArray.push(plan); } }); return planArray; } function addLayerExisting(feature, key, container, notpresent) { const { init } = components; const { names } = init; const name = feature.id ? key : feature; // console.log(names[name.toLowerCase()]); const l = $('<div>') .attr('class', 'layer-existing') .attr('data-name', name) .data('name', name) .html(names[name.toLowerCase()]) .appendTo(container) .prepend('<i class="icon-binoculars">') .click(layerClick); } function layerClick() { const { dispatch, init } = components; const { mobile } = init; if (!$(this).hasClass('highlighted')) { highlightFeature($(this).data('name')); $(this).toggleClass('highlighted'); if (mobile) legend.addClass('collapsed'); } else { dispatch.call('removehighlight', this); } } function highlightFeature(feature) { const { dispatch, init } = components; const { server } = init; dispatch.call('removehighlight', this); dispatch.call('removeprobe', this); $.getJSON(server + 'feature/' + year + '/' + encodeURIComponent(feature), function highlight(json) { dispatch.call('highlightfeature', this, json); }); } function addSwatch(style) { if (!style || !style.shape) { return $('<div>'); } // console.log(style); const swatch = $('<div>') .addClass('swatch') .css({ float: 'right' }) .addClass(style.shape.slice(0, style.shape.indexOf('.'))); if (style.shape.match(/svg$/)) { swatch.load(`img/legend/${style.shape}`); } else { swatch .append($('<img>').attr('src', `img/legend/${style.shape}`)); } if (style.fill || style.stroke) { swatch.css(style); } return swatch; } Lg.addSwatch = addSwatch; Lg.addViews = () => { const { dispatch, init } = components; const { language } = init; $('.legend-category[data-category="views"]').remove(); const cat = $('<div>') .attr('class', 'legend-category') .attr('data-category', 'views') .prependTo('.legend-contents'); const title = language === 'en' ? 'VIEWS' : 'VISTAS'; $('<div>') .attr('class', 'category-title') .html(title) .appendTo(cat); const gr = $('<div>') .attr('class', 'legend-group') .attr('data-group', 'views') .appendTo(cat); const groupTitle = $('<div>') .attr('class', 'group-title') .appendTo(gr); const label = $('<label>') .html('Cones of vision') .appendTo(groupTitle); $('<input type="checkbox" value="views">') .attr('checked', Lg.hasViews ? 'checked' : null) .on('change', function onChange() { if ($(this).is(':checked')) dispatch.call('showviews', this); else dispatch.call('hideviews', this); Lg.hasViews = $(this).is(':checked'); dispatch.call('statechange', this); }) .prependTo(label); addSwatch({ shape: 'viewshed2.png' }) .appendTo(groupTitle); $('img', groupTitle).addClass('viewshed-icon'); // Lg.addSearch(); }; Lg.layers = function lgLayers(list) { // if no list is provided if (!list) { let layers = []; $('.legend-contents input').each(function checked() { if (!$(this).is(':checked') && $(this).attr('value') !== 'views' && $(this).attr('class') !== 'search-input') { $(this).attr('value') .split('&') .forEach((layer) => { layers.push(layer); }); // layers.push($(this).attr('value')); } }); if (!layers.length) layers = ['all']; return layers; } if (!$('.legend-contents input').length) { // loaded in from URL before checkboxes exist tempLayers = list; return Lg; } if (list[0] === 'all') { $('.legend-contents input').attr('checked', 'checked'); if (!Lg.hasViews) $('input[value="views"]').attr('checked', null); } else { list.forEach((l) => { $('.legend-group[data-group="' + l + '"] input').attr('checked', null); }); } return Lg; }; Lg.getLayersData = () => layers; function resizeLegendButton() { const { init } = components; const { language, mobile } = init; const legendButton = $('#legend .legend-toggle'); if (mobile) return; if (!$('#legend').hasClass('subsequent')) { const width = language === 'pr' ? '170px' : '160px'; legendButton.css({ width }); } else { legendButton.css({ width: '10px' }); } } Lg.initialize = () => { initEvents(); return Lg; }; Lg.setYear = (newYear) => { updateYear(newYear); drawSidebarContent(); return Lg; }; Lg.updateLanguage = () => { drawSidebarContent(); return Lg; }; return Lg; }; export default getLegend; // RUN: cd %S && truffle test var config = require("../config.js") var Contract = artifacts.require("./" + config.contractName + ".sol"); var Interface = artifacts.require("./_Interface" + config.contractName + ".sol"); Contract.abi = Interface.abi contract(config.contractName, function(accounts) { it("should be able to register to the bank", async function() { const instance = await Contract.deployed(); let t; await instance.register({from: accounts[0]}); await instance.register({from: accounts[1]}); t = await instance.getBalance.call({from: accounts[0]}); assert.equal(t.valueOf(), 0); }); it("should be possible to deposit money", async function() { const instance = await Contract.deployed(); let t; await instance.deposit({from: accounts[0], value: 20}); t = await instance.getBalance.call({from: accounts[0]}); await instance.register({from: accounts[0]}); assert.equal(t.valueOf(), 20); await instance.deposit({from: accounts[0], value: 30}); t = await instance.getBalance.call({from: accounts[0]}); assert.equal(t.valueOf(), 50); t = await instance.getBalance.call({from: accounts[1]}); assert.equal(t.valueOf(), 0); await instance.deposit({from: accounts[1], value: 18}); t = await instance.getBalance.call({from: accounts[1]}); assert.equal(t.valueOf(), 18); }); it("should not possible to deposit money if the account is not registered", async function() { const instance = await Contract.deployed(); try { await instance.deposit({from: accounts[2], value: 20}); } catch (e) { return; } assert.fail(); }); it("it should be possible to transfer money from one account to another", async function() { const instance = await Contract.deployed(); let t; t = await instance.getBalance.call({from: accounts[0]}); const previousBalance0 = t.toNumber(); t = await instance.getBalance.call({from: accounts[1]}); const previousBalance1 = t.toNumber(); await instance.transfer(5, accounts[1], {from: accounts[0]}); t = await instance.getBalance.call({from: accounts[0]}); assert.equal(t.valueOf(), previousBalance0 - 5); t = await instance.getBalance.call({from: accounts[1]}); assert.equal(t.valueOf(), previousBalance1 + 5); }); it("should not be possible to call manager functions from an account", async function() { const instance = await Contract.deployed(); let t; try { await instance.clear(accounts[1], {from: accounts[0]}); } catch (e) { return; } assert.fail(); }); it("should be possible for the manager to clear an account", async function() { const instance = await Contract.deployed(); let t; await instance.clear(accounts[0], {from: accounts[9]}); t = await instance.getBalance.call({from: accounts[0]}); assert.equal(t.valueOf(), 0); }); it("should be possible to withdraw money", async function() { const instance = await Contract.deployed(); let t; const oldBalance = web3.eth.getBalance(accounts[3]); const registerTxInfo = await instance.register({from: accounts[3]}); const registerTx = await web3.eth.getTransaction(registerTxInfo.tx); const registerGasCost = registerTx.gasPrice.mul(registerTxInfo.receipt.gasUsed); const depositTxInfo = await instance.deposit({from: accounts[3], value: web3.toWei(10, 'ether')}); const depositTx = await web3.eth.getTransaction(depositTxInfo.tx); const depositGasCost = depositTx.gasPrice.mul(depositTxInfo.receipt.gasUsed); t = await instance.getBalance.call({from: accounts[3]}); assert.equal(t.valueOf(), web3.toWei(10, 'ether')); const withdrawTxInfo = await instance.withdraw(web3.toWei(4, 'ether'), {from: accounts[3]}); const withdrawTx = await web3.eth.getTransaction(withdrawTxInfo.tx); const withdrawGasCost = withdrawTx.gasPrice.mul(withdrawTxInfo.receipt.gasUsed); t = await instance.getBalance.call({from: accounts[3]}); assert.equal(t.valueOf(), web3.toWei(6, 'ether')); const newBalance = web3.eth.getBalance(accounts[3]); assert.equal(newBalance.valueOf(), oldBalance.sub(web3.toWei(6, 'ether')).sub(registerGasCost).sub(depositGasCost).sub(withdrawGasCost).valueOf()); }) it("should not be possible to withdraw too much money", async function() { const instance = await Contract.deployed(); let t; const oldBalance = web3.eth.getBalance(accounts[4]); const registerTxInfo = await instance.register({from: accounts[4]}); const registerTx = await web3.eth.getTransaction(registerTxInfo.tx); const registerGasCost = registerTx.gasPrice.mul(registerTxInfo.receipt.gasUsed); const depositTxInfo = await instance.deposit({from: accounts[4], value: web3.toWei(10, 'ether')}); const depositTx = await web3.eth.getTransaction(depositTxInfo.tx); const depositGasCost = depositTx.gasPrice.mul(depositTxInfo.receipt.gasUsed); t = await instance.getBalance.call({from: accounts[4]}); assert.equal(t.valueOf(), 10000000000000000000); try { const withdrawTxInfo = await instance.withdraw(web3.toWei(20, 'ether'), {from: accounts[4]}); } catch (e) { t = await instance.getBalance.call({from: accounts[4]}); assert.equal(t.valueOf(), web3.toWei(10, 'ether')); const newBalance = web3.eth.getBalance(accounts[4]); // Estimate const withdrawGasCost = 0 assert.isTrue(newBalance.lessThan(oldBalance.sub(web3.toWei(10, 'ether')).sub(registerGasCost).sub(depositGasCost).sub(withdrawGasCost))); return } assert.fail(); }) }); <reponame>iofod/IFstruct-parser<filename>scripts/web/_temp.js const { getCloneMark, DIMap, Gesture } = require('../common/helper') const { IF } = require('./_env') const { genActionList } = require('./_genActionList') let tree let customEvent = ['routechange', 'modelchange'] let CE_list = [] // Non-native events function genEventContent(hid, events, cloneMark, jumpCE = true) { let eventMarks = [] let eventMethods = [] let isVue3 = IF.framework == 'Vue3' events.forEach((evo) => { if (jumpCE && customEvent.includes(evo.event)) { evo.hid = hid CE_list.push(evo) return } hid = evo.hid || hid let { event, actions, native } = evo let prefix switch (event) { case 'start': event = 'touchstart' break case 'end': event = 'touchend' break default: break } let isGesture = Gesture.includes(event) if (isGesture) { prefix = `v-GT-${event}` } else { prefix = `@${event}${(native === false || isVue3) ? '' : '.native'}` } ;['passive', 'capture', 'once', 'prevent', 'stop', 'self'].forEach((key) => { if (evo[key]) { prefix += '.' + key } }) let methodName = `${event}_${hid}` let mark = cloneMark === `''` ? '' : `, ${cloneMark}` if (isGesture) { eventMarks.push(`${prefix}="GEV(${methodName}${mark})"`) } else { eventMarks.push(`${prefix}="EV($event, ${methodName}${mark})"`) } let execBody = genActionList(hid, actions) let acStr = JSON.stringify(actions) let use$Response = acStr.includes('$response') || acStr.includes('function') || acStr.includes('service') let methodBody = `async ${methodName}(e) { ${use$Response ? 'let response\n' : ''}${execBody.join('\n')} }` eventMethods.push(methodBody) }) return { eventMarks, eventMethods } } function genTag(hid, tag) { let flag = IF.ctx.HSS[hid].status.filter( (statu) => statu.props.option.IAA || statu.props.option.IAA ).length return flag ? 'A' + tag : tag } function genChildView(hid, IN = '', DI = 0, eventContent) { let target = tree[hid] //|| HSS[hid] let { content, type, model, events, name, remarks } = target let [ui, cname] = content.split('/') let getTag // 内置系统UI的别名 if (ui == 'base') { ui = 'IF' } else { ui = '' } let hasCopy = false if (model.hasOwnProperty('copy')) { hasCopy = true DI += 1 } else { hasCopy = false } let LM = DIMap[DI] // loop mark let CM_arr = getCloneMark(DI) let CM = CM_arr.join(" + '|' + ") CM = DI > 0 ? "'|' + " + CM : "''" let str let isMirror = content == 'base/mirror' let cloneMark = CM != "''" ? ` :clone="${CM}"` : `` const tag = genTag(hid, `${ui}${cname}`) let { eventMarks, eventMethods } = genEventContent(hid, events, CM) eventContent.push(...eventMethods) const EBD = eventMarks.length > 0 ? ' ' + eventMarks.join(' ') : '' //eventBinding let CID = DI > 1 ? `'${hid + "', " + CM_arr.slice(0, CM_arr.length - 1).join(', ')}` : `'${hid}'` if (type == 'unit' && !isMirror) { let unitHead = `${IN}\t<${tag} class="U-unit" hid="${hid}"${EBD}` if (hasCopy) { str = `${unitHead} v-for="(_, ${LM}) in CID(${CID})" :key="'${hid}' + ${CM}"${cloneMark}></${tag}>` } else { str = `${unitHead}${cloneMark}></${tag}>` } } else { // container or mirror IN += '\t' let inject = isMirror ? ' class="U-unit"' : '' let wrapHead = `${IN}<${tag}${inject} hid="${hid}"${EBD}` if (hasCopy) { getTag = (v) => `${wrapHead} v-for="(_, ${LM}) in CID(${CID})" :key="'${hid}' + ${CM}"${cloneMark}>${v}</${tag}>` } else { getTag = (v) => `${wrapHead}${cloneMark}>${v}</${tag}>` } if (isMirror) { let uv = target.model.use.value if (tree[uv]) { str = getTag(`${IN}\n` + genChildView(uv, IN, DI, eventContent) + `\n${IN}`) } else { str = getTag(``) } } else { // container let comment = `` // 去掉默认值 if (name != '容器' && name != 'container') { let rtxt = ` ` if (remarks) { remarks = remarks.split('\n').join(`\n${IN}`) rtxt = ` : \n${IN}${remarks}\n${IN}` } comment = `${IN}<!-- ${name}${rtxt}-->\n` } if (target.children && target.children.length) { str = `${comment}` + getTag( target.children .map((id, index) => `\n` + genChildView(id, IN, DI, eventContent)) .join('') + `\n${IN}` ) } else { str = `${comment}` + getTag(``) } } } return str } function genCreated(lid) { if (!CE_list.length) return `` let { eventMethods } = genEventContent(lid, CE_list, 'clone', false) let str = `` CE_list.forEach((evo, I) => { let { hid, event, mds, target, once } = evo let subscriber = once ? 'FN.PS.subscribeOnce' : 'FN.PS.subscribe' let fn_name = eventMethods[I].replace('async', 'async function') let sub_name = event == 'modelchange' ? `${target || hid}.${mds}.${event}` : event str += ` FN.PS.unsubscribe(FN.PS_ID.${hid}_${event}) FN.PS_ID.${hid}_${event} = ${subscriber}('${sub_name}', this.GEV(${fn_name}))` }) CE_list = [] return ` created() { ${str} },` } exports.genViewContent = (lid, payload) => { tree = payload let eventContent = [] let childview = tree[lid].children .map((cid, index) => genChildView(cid, '\t', 0, eventContent)) .join('\n') let { eventMarks, eventMethods } = genEventContent(lid, tree[lid].events, 'clone') eventContent.push(...eventMethods) const EBD = eventMarks.length > 0 ? ' ' + eventMarks.join(' ') : '' //eventBinding eventContent = [...new Set(eventContent)].join(',') let Lmark = genTag(lid, 'IFlevel') return `<template> <${Lmark} class="wrap" hid="${lid}" :clone="clone" :style="STYLE"${EBD}> <div class="frame" :style="LAYOUT"> ${childview} </div> </${Lmark}> </template> <script> import FA from '../common/FA' import FX from '../common/FX' import MF from '../common/MF' export default {${genCreated(lid)} methods: { ${eventContent} }, mounted() { } } </script> ` } <reponame>anastanei/skilline<filename>gulp-tasks/styles.js const gulp = require('gulp'); const plumber = require('gulp-plumber'); const notifier = require('node-notifier'); const postcss = require('gulp-postcss'); const autoprefixer = require('autoprefixer'); const sprites = require('postcss-sprites'); const assets = require('postcss-assets'); const sass = require('gulp-dart-sass'); const sourcemaps = require('gulp-sourcemaps'); const cssmin = require('gulp-clean-css'); const gulpif = require('gulp-if'); const log = require('fancy-log'); const colors = require('ansi-colors'); const purgecss = require('@fullhuman/postcss-purgecss'); const PATHS = require('../paths'); const { IS_PRODUCTION } = require('../env'); const POSTCSS_PROCESSORS = [ assets({ loadPaths: [PATHS.src.imagesInline], cache: true, }), sprites({ stylesheetPath: './dist/css/', spritePath: './dist/images/', retina: true, padding: 4, filterBy: (image) => /sprites\/.*\.png$/gi.test(image.url) ? Promise.resolve() : Promise.reject(), }), IS_PRODUCTION && purgecss({ content: ['./dist/**/*.{html,js}'], }), autoprefixer(), ].filter((value) => value); module.exports = function styles() { return gulp .src(PATHS.src.styles) .pipe( plumber({ errorHandler: function (err) { log.error(colors.red(err.message)); notifier.notify({ title: 'SASS Compilation Error', message: err.message, }); }, }) ) .pipe(gulpif(!IS_PRODUCTION, sourcemaps.init())) .pipe( sass({ errLogToConsole: true, includePaths: ['./node_modules/'], }) ) .pipe(postcss(POSTCSS_PROCESSORS)) .pipe(gulpif(IS_PRODUCTION, cssmin({ processImport: false }))) .pipe(gulpif(!IS_PRODUCTION, sourcemaps.write())) .pipe(gulp.dest(PATHS.build.styles)); }; <reponame>Em-Ant/fcc-nightzone var Yelp = require('yelp-fusion'); var Bars = require('../models/bars.js'); var Users = require('../models/users.js'); var yelp = Yelp.client(process.env.YELP_API_KEY); function search(req, res, loc) { yelp .search({ term: 'nightlife', location: loc }) .then(function (data) { if (req.user) { // Logged in. Add going count and am I going boolean to yelp data var bars = data.jsonBody.businesses; Bars.find({ yelpId: { $in: bars.map(function (b) { return b.id; }), }, }).exec(function (err, reservedBars) { bars = bars.map(function (b) { var r = reservedBars.find(function (el) { return b.id === el.yelpId; }); if (r) { b.nGoing = r.going.length; b.amIGoing = r.going.indexOf(req.user._id) !== -1; } return b; }); res.json(data.jsonBody); }); } else { res.json(data.jsonBody); } }) .catch(function (err) { console.log('searchAuth: ', err); res.json(err); return; }); } module.exports.search = function (req, res) { yelp .search({ term: 'nightlife', location: req.params.loc }) .then(function (data) { res.json(data.jsonBody); }) .catch(function (err) { console.log('search ', err); res.json(err); return; }); }; module.exports.searchUpdateLoc = function (req, res) { if (req.user) { Users.findOne({ _id: req.user._id }, function (err, user) { if (req.body.location !== 'last' && req.body.location !== user.location) { // update user location user.location = req.body.location; user.save(function (err) { if (err) { console.log('error updating user'); return; } // then search new location search(req, res, req.body.location); }); } else { // search the last known user location search(req, res, user.location); } }); } else { // Unauthenticated. Search w/out adding reservations data. search(req, res, req.body.location); } }; module.exports.addReservation = function (req, res) { Bars.findOne({ yelpId: req.body.barId }, function (err, bar) { if (err) { console.log(err); res.status(500).end(); return; } if (bar) { // bar is in the db if (bar.going.indexOf(req.user._id) === -1) { // user is not going yet bar.going.push(req.user._id); bar.save(function (err, b) { if (err) { console.log('db saving error'); return; } res.json({ barId: b.yelpId, nGoing: b.going.length, amIGoing: true, }); }); } else { // user is already going. Requested by mistake. res.json({ barId: bar.yelpId, nGoing: bar.going.length, amIGoing: true, }); } } else { // Bar is not found. Noone is going yet. // create a new bar and add user. var newBar = new Bars(); newBar.yelpId = req.body.barId; newBar.going = [req.user._id]; newBar.save(function (err, b) { res.json({ barId: b.yelpId, nGoing: b.going.length, amIGoing: true, }); }); } }); }; module.exports.removeReservation = function (req, res) { Bars.findOne({ yelpId: req.body.barId }, function (err, bar) { if (err) { console.log(err); res.status(500).end(); return; } if (bar) { var bIndex = bar.going.indexOf(req.user._id); if (bIndex !== -1) { // user id found in going array bar.going.splice(bIndex, 1); if (bar.going.length > 0) { bar.save(function (err, b) { if (err) { console.log('db saving error'); return; } res.json({ barId: b.yelpId, nGoing: b.going.length, amIGoing: false, }); }); } else { // noone is going. Delete it from db. bar.remove(function (err) { res.json({ barId: bar.yelpId, nGoing: 0, amIGoing: false, }); }); } } else { // user id not found. Requested by mistake (it should not happen) res.json({ barId: bar.yelpId, nGoing: bar.going.length, amIGoing: false, }); } } else { // bar not found. Requested by mistake (it should not happen) res.json({ error: 'not found' }); } }); }; <reponame>kidwen/sample-html "use strict"; function multipleSort(data, sorts) { if (!sorts || sorts.length == 0) { return data; } return data.sort((cur, next) => { for (const sort of sorts) { let key = sort.key; let order = sort.order; if (next[key] == cur[key]) { continue; } if (order == "desc") { return cur[key] > next[key] ? -1 : 1; } else { return cur[key] > next[key] ? 1 : -1; } } }); } let data = [ { a: 1, b: "a", }, { a: 2, b: "d", }, { a: 2, b: "c", c: 10, }, { a: 2, b: "a", }, { a: 2, b: "c", c: 11, }, ]; let sorts = [ { key: "a", order: "desc", }, { key: "b", order: "asc", }, { key: "c", order: "desc", }, ]; console.log(multipleSort(data, sorts)); <reponame>narcotic1998/Chat-App import Vue from 'vue'; import store from "@/mainStore"; import actions from "./UserAction"; let state = { currentUser : {}, isProfileLoaded : false, friends : {}, isFriendsLoaded : false } let mutations = { setUserDetail(state, data) { state.currentUser = data; store.state.chatstore.chatSummary = { totalChats : data.total_chats, unreadChats : data.unread_chats } state.isProfileLoaded = true; }, setFriendsDetails(state, data) { data.forEach(friend => { Vue.set(state.friends, friend._id, friend); }); state.isFriendsLoaded = true; }, setFriendStatus({ friends }, { id, status, last_online }) { if (friends[id]) { friends[id].last_online = last_online friends[id].status = status; return; } Vue.set(friends, id, { status, last_online }); }, resetUserStore(state) { state.currentUser = {}; state.isProfileLoaded = false; state.friends = {}; state.isFriendsLoaded = false; } } let getters = { // Pass the id to get a friend detail getFriendDetail : state => id => { return state.friends[id] || {}; }, getCurrentUser : ({ currentUser }) => { return currentUser; } } store.registerModule('userstore', { namespaced : true, state, mutations, getters, actions })<gh_stars>0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const pea_script_1 = require("./pea-script"); const common_1 = require("./common"); const format_content_1 = require("./format-content"); const firebean = require("@foxzilla/fireblog-sdk/firebean"); const Path = require('path'); const Fs = require('fs'); const xml2js = require('xml2js').parseString; const Gravatar = require('gravatar'); const Readline = require('readline'); async function parse(path) { const StateMap = { publish: 0 /* Publish */, trash: 2 /* Trash */, private: 1 /* Private */, draft: 3 /* Draft */, }; const RawData = await new Promise(r => xml2js(Fs.readFileSync(path), (e, d) => r(d))); const { tag: Tag, category: Category, article: Article, user: User, comment: Comment, attachment: Attachment, } = { tag: [], category: [], article: [], user: [], comment: [], attachment: [] }; const Meta = { front_url: '', api_url: '', author: { names: ['FoXZilla'], mail: '', }, }; const CategoryMap = {}; if (RawData.rss.channel[0]['wp:tag']) RawData.rss.channel[0]['wp:tag'].forEach(function (item) { Tag.push({ name: pea_script_1.doThatOr(item['wp:tag_name'], v => v[0]), alias: pea_script_1.doThatOr(item['wp:tag_slug'], v => v[0]), description: pea_script_1.doThatOr(item['wp:tag_description'], v => v[0], undefined), }); }); if (RawData.rss.channel[0]['wp:category']) RawData.rss.channel[0]['wp:category'].forEach(function (item) { Category.push({ name: pea_script_1.doThatOr(item['wp:cat_name'], v => pea_script_1.doThatOr(v[0], v => v)), alias: pea_script_1.doThatOr(item['wp:category_nicename'], v => v[0]), description: pea_script_1.doThatOr(item['wp:category_description'], v => pea_script_1.doThatOr(v[0], v => v)), parent_alias: pea_script_1.doThatOr(item['wp:category_parent'], v => pea_script_1.doThatOr(v[0], v => v)), }); CategoryMap[item['wp:term_id'][0]] = Category[Category.length - 1]; }); if (RawData.rss.channel[0]['item']) RawData.rss.channel[0]['item'].forEach(function (item) { switch (pea_script_1.doThatOr(item['wp:post_type'], v => v[0])) { case 'post': if (pea_script_1.doThatOr(item['wp:post_date'], v => v[0]) === '0000-00-00 00:00:00') { item['wp:post_date'][0] = new Date().toISOString(); } ; Article.push({ id: pea_script_1.doThatOr(item['wp:post_id'], v => +v[0], 0), title: pea_script_1.doThatOr(item['title'], v => v[0]), description: pea_script_1.doThatOr(item['excerpt:encoded'], v => pea_script_1.doThatOr(v[0], v => v)), state: pea_script_1.doThatOr(item['wp:status'], v => StateMap[v[0]]), tag_list: pea_script_1.doThatOr(item['category'], v => v.filter((i) => i.$.domain === 'post_tag').map((i) => i.$.nicename)), category_list: pea_script_1.doThatOr(item['category'], v => v.filter((i) => i.$.domain === 'category').map((i) => i.$.nicename)), update_time: common_1.toIOSDate(pea_script_1.doThatOr(item['wp:post_date'], v => v[0])), create_time: common_1.toIOSDate(pea_script_1.doThatOr(item['pubDate'], v => v[0])), view_count: pea_script_1.doThatOr(item['wp:postmeta'], v => pea_script_1.doThatOr(v.find((i) => i['wp:meta_key'][0] === 'post_views_count'), i => +i['wp:meta_value'][0], 0), 0), md_content: format_content_1.default(pea_script_1.doThatOr(item['content:encoded'], v => v[0])), meta: { no_comment: pea_script_1.doThatOr(item['content:comment_status'], v => v[0] !== 'open', false), password: <PASSWORD>ThatOr(item['wp:post_password'], v => pea_script_1.doThatOr(v[0], v => v)), }, }); for (let comment of pea_script_1.doThatOr(item['wp:comment'], v => v, [])) { if (pea_script_1.doThatOr(comment['wp:comment_approved'], v => v[0]) !== '1') continue; let userId = User.push({ id: User.length + 1, origin: 'wordpress', open_id: '', nickname: pea_script_1.doThatOr(comment['wp:comment_author'], v => v[0]), mail: pea_script_1.doThatOr(comment['wp:comment_author_email'], v => v[0]), create_date: common_1.toIOSDate(pea_script_1.doThatOr(comment['wp:comment_date'], v => v[0])), }); Comment.push({ id: pea_script_1.doThatOr(comment['wp:comment_id'], v => +v[0], 0), date: common_1.toIOSDate(pea_script_1.doThatOr(comment['wp:comment_date'], v => v[0])), article_id: pea_script_1.doThatOr(item['wp:post_id'], v => +v[0], 0), author_id: userId, md_content: pea_script_1.doThatOr(comment['wp:comment_content'], v => v[0]), }); if (pea_script_1.doThatOr(comment['wp:comment_parent'], v => !!v[0], false)) { var parentCommentId = pea_script_1.doThatOr(comment['wp:comment_parent'], v => +v[0], 0); if (parentCommentId === 0) continue; var parentComment = Comment.find(i => i.id === parentCommentId); if (!parentComment) { console.warn(`Can't found comment #${parentCommentId}`); continue; } ; var replyUserId = +parentComment.author_id; var replyUserInfo = User.find(u => u.id === replyUserId); var currentComment = Comment[Comment.length - 1]; currentComment.reply_to = function (id) { while (true) { let comment = Comment.find(i => i.id === id); if ('reply_to' in comment) { id = comment.reply_to; } else break; } ; return id; }(parentCommentId); currentComment.md_content = `[@${replyUserInfo.nickname}](${firebean.stringify({ _type: "go_user" /* goUser */, id: replyUserInfo.id, })}) ` + currentComment.md_content; } ; } ; break; case 'attachment': Attachment.push(item['wp:attachment_url'][0].trim()); break; } ; }); pea_script_1.doThatOr(RawData.rss.channel[0]['pubDate'], v => Meta.publish_date = new Date(v[0]).toISOString()); pea_script_1.doThatOr(RawData.rss.channel[0]['description'], v => Meta.description = v[0]); pea_script_1.doThatOr(RawData.rss.channel[0]['language'], v => Meta.language = v[0]); pea_script_1.doThatOr(RawData.rss.channel[0]['wp:base_blog_url'], v => Meta.front_url = v[0]); pea_script_1.doThatOr(RawData.rss.channel[0]['wp:author'], author => Meta.author = { names: [ pea_script_1.doThatOr(author[0]['wp:author_display_name'], v => v[0], ''), pea_script_1.doThatOr(author[0]['wp:author_first_name'], v => v[0], ''), pea_script_1.doThatOr(author[0]['wp:author_last_name'], v => v[0], ''), ].filter(v => Boolean(v)), mail: pea_script_1.doThatOr(author[0]['wp:author_email'], v => v[0], 'root@localhost'), }); Meta.nav = await async function () { if (!RawData.rss.channel[0]['item']) return; var Result = []; var allNavItem = RawData.rss.channel[0]['item'] .filter((item) => item['wp:post_type'][0] === 'nav_menu_item') .filter((item) => item['wp:status'][0] !== 'draft') .map(getNavItemInfo); var groups = [...new Set(allNavItem.map(i => i.group))]; if (groups.length > 1) { console.log('Which nav is you want?'); groups.forEach((item, index) => { console.log(`${index}. ${item}`); }); let rl = Readline.createInterface({ input: process.stdin, output: process.stdout }); var input = await new Promise(function (resolve) { rl.question(`Enter [${new Array(groups.length).fill(0).map((item, index) => index).join('/')}]:`, resolve); }); rl.close(); allNavItem = allNavItem.filter((item) => item.group === groups[Number(input)]); } ; for (let postMeta of allNavItem) { switch (postMeta._menu_item_type) { case 'custom': Result.push({ type: 'link', href: postMeta._menu_item_url, text: postMeta.name, }); break; case 'taxonomy': { let category = CategoryMap[postMeta._menu_item_object_id]; Result.push({ type: 'category', alias: category.alias, text: postMeta.name || category.name, }); break; } case 'post_type': Result.push({ type: 'article', id: Number(postMeta._menu_item_object_id), text: postMeta.name, }); break; default: console.warn('skip', postMeta); } ; } ; return Result; }(); return { name: pea_script_1.doThatOr(RawData.rss.channel[0]['title'], v => v[0], 'A FireBlog'), version: require('@foxzilla/fireblog/package.json').version, meta: Meta, data: { tag: Tag, category: Category, article: Article, user: User, comment: Comment, attachment: Attachment, }, }; } exports.default = parse; ; function getNavItemInfo(rawItem) { let postMeta = {}; for (let meta of rawItem['wp:postmeta']) { postMeta[meta['wp:meta_key'][0]] = meta['wp:meta_value'][0]; } ; postMeta.link = rawItem['link'][0]; postMeta.name = rawItem['title'][0]; postMeta.order = Number(rawItem['wp:menu_order'][0]); postMeta.group = rawItem['category'][0]._; return postMeta; } ; <reponame>xyla-io/xylo "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DataVectorStore = void 0; // Importing from 'pouchDB' causes a global is undefined error in Angular 6 and its web workers. See https://github.com/pouchdb/pouchdb/issues/7263 var PouchDB = __importStar(require("pouchdb/dist/pouchdb")); var DataVectorStore = /** @class */ (function () { function DataVectorStore(key) { this.key = key; this.initialize(); } DataVectorStore.prototype.initialize = function () { this.db = new PouchDB(this.key); }; DataVectorStore.prototype.destroy = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.db.destroy()]; case 1: _a.sent(); this.initialize(); return [2 /*return*/]; } }); }); }; DataVectorStore.prototype.save = function (url, dataVectors, time, revision) { return __awaiter(this, void 0, void 0, function () { var docs, putDocs, response, errors; return __generator(this, function (_a) { switch (_a.label) { case 0: // The :time doc will be in a best-effort state subject to race conditions. if (!time) { time = new Date(); } return [4 /*yield*/, this.db.allDocs({ startkey: this.dataID(url), endkey: this.timeID(url), })]; case 1: docs = _a.sent(); if (revision && (!docs.rows[0] || docs.rows[0].value.rev !== revision)) { throw { status: 409, name: 'conflict', message: 'Revision mismatch conflict', error: true, }; } putDocs = [ { _id: this.dataID(url), dataVectors: dataVectors, time: time.getTime(), }, { _id: this.timeID(url), time: time.getTime(), }, ]; docs.rows.forEach(function (r, i) { return putDocs[i]._rev = r.value.rev; }); return [4 /*yield*/, this.db.bulkDocs(putDocs)]; case 2: response = _a.sent(); errors = response.map(function (r, i) { return Object.assign({ id: putDocs[i]._id }, r); }).filter(function (r) { return r.error; }); if (errors.length) { throw { status: 500, name: 'batcherror', message: 'Batch update errors', error: true, errors: errors, }; } return [2 /*return*/, { url: url, revision: response[0].rev, time: time, dataVectors: dataVectors, }]; } }); }); }; DataVectorStore.prototype.loadData = function (url, time) { return __awaiter(this, void 0, void 0, function () { var doc; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.get(this.dataID(url))]; case 1: doc = _a.sent(); if (time && new Date(doc.time) < time) { return [2 /*return*/, null]; } return [2 /*return*/, doc ? doc.dataVectors : null]; } }); }); }; DataVectorStore.prototype.loadTime = function (url) { return __awaiter(this, void 0, void 0, function () { var doc; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.get(this.timeID(url))]; case 1: doc = _a.sent(); return [2 /*return*/, doc ? new Date(doc.time) : null]; } }); }); }; DataVectorStore.prototype.load = function (url, time, revision) { return __awaiter(this, void 0, void 0, function () { var doc, error_1, storedTime; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.db.get(this.dataID(url))]; case 1: doc = _a.sent(); return [3 /*break*/, 3]; case 2: error_1 = _a.sent(); if (error_1.name !== 'not_found') { throw error_1; } return [2 /*return*/, null]; case 3: if (revision && doc._rev !== revision) { return [2 /*return*/, null]; } storedTime = new Date(doc.time); if (time && storedTime < time) { return [2 /*return*/, null]; } return [2 /*return*/, { url: url, revision: doc._rev, dataVectors: doc.dataVectors, time: storedTime, }]; } }); }); }; DataVectorStore.prototype.remove = function (url, revision) { return __awaiter(this, void 0, void 0, function () { var docs, deleteDocs, response, errors; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.db.allDocs({ startkey: this.dataID(url), endkey: this.timeID(url), })]; case 1: docs = _a.sent(); if (!docs.total_rows) { return [2 /*return*/, false]; } if (revision && docs.rows[0].value.rev !== revision) { return [2 /*return*/, false]; } deleteDocs = docs.rows.map(function (r) { return ({ _id: r.id, _rev: r.value.rev, _deleted: true, }); }); return [4 /*yield*/, this.db.bulkDocs(deleteDocs)]; case 2: response = _a.sent(); errors = response.map(function (r, i) { return Object.assign({ id: deleteDocs[i]._id }, r); }).filter(function (r) { return r.error; }); if (errors.length) { throw { status: 500, name: 'batcherror', message: 'Batch remove errors', error: true, errors: errors, }; } return [2 /*return*/, true]; } }); }); }; DataVectorStore.prototype.dataID = function (url) { return url + ' :data'; }; DataVectorStore.prototype.timeID = function (url) { return url + ' :time'; }; DataVectorStore.prototype.get = function (key) { return __awaiter(this, void 0, void 0, function () { var doc, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.db.get(key)]; case 1: doc = _a.sent(); return [2 /*return*/, doc]; case 2: e_1 = _a.sent(); if (e_1.name === 'not_found') { return [2 /*return*/, null]; } else { throw e_1; } return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; return DataVectorStore; }()); exports.DataVectorStore = DataVectorStore; //# sourceMappingURL=data-vector-store.js.mapimport React, { useEffect, useState } from "react"; import { StyleSheet, Modal, FlatList, RefreshControl, View, Text, ScrollView, TouchableOpacity, SafeAreaView, useColorScheme, } from "react-native"; import moment from "moment"; import * as Animatable from "react-native-animatable"; import axios from "axios"; import { useTranslation } from "react-i18next"; import { Feather, MaterialCommunityIcons } from "@expo/vector-icons"; import CategoryItem from "../components/CategoryItem"; import Screen from "../components/Screen"; import ResourceItem from "../components/ResourceItem"; import ViewBookingListItem from "../components/ViewBookingListItem"; import CampusItem from "../components/CampusItem"; import useAuth from "../auth/useAuth"; import colors from "../themes/colors"; import presetStyles, { sizing } from "../themes/presetStyles"; import routes from "../navigations/routes"; import branchesApi from "../api/branches"; import categoriesApi from "../api/categories"; import resourcesApi from "../api/resources"; import bookingsApi from "../api/bookings"; function MainScreen({ navigation }) { const { user } = useAuth(); const { t, i18n } = useTranslation([routes.screens.HOME, "common"]); const colorScheme = useColorScheme(); const [isLoading, setLoading] = useState(false); const [selectedCategory, setSelectedCategory] = useState(1); const [activeBooking, setActiveBooking] = useState(null); const [upcoming, setUpcoming] = useState([]); const [categories, setCategories] = useState([]); const [resources, setResources] = useState([]); const [branches, setBranches] = useState([]); const [isCampusOpen, setCampusOpen] = useState(false); const getBookings = () => bookingsApi .fetchFromUser( user.id, moment().format("YYYY-MM-DD"), moment().format("YYYY-MM-DD") ) .then(({ data }) => { const current = moment(); var upcomingData = []; var activeBooking = null; data.forEach((booking) => { if ( moment().isBetween(booking.start_time, booking.end_time) ) { activeBooking = booking; setActiveBooking(booking); } else if (moment(booking.start_time).isAfter(current)) { upcomingData.push(booking); } if (!Boolean(activeBooking)) setActiveBooking(null); }); upcomingData.sort((a, b) => moment(a.start_time).isAfter(moment(b.start_time)) ); setUpcoming(upcomingData); }) .catch((error) => console.log(error)); const fetchAllData = async () => { setLoading(true); try { const [categoriesData, branchesData] = await axios.all([ categoriesApi.fetchAll(), branchesApi.fetchAll(), ]); //categories setCategories(categoriesData.data); setSelectedCategory(categoriesData.data[0].id); //branches setBranches(branchesData.data); } catch (error) { console.log(error); } finally { setLoading(false); } }; useEffect(() => { fetchAllData(); }, []); useEffect(() => { resourcesApi.fetchFromCategory(selectedCategory).then(({ data }) => { setResources(data); }); }, [selectedCategory]); useEffect(() => { const unsubscribe = navigation.addListener("focus", () => { getBookings(); }); return unsubscribe; }, [navigation]); const styles = StyleSheet.create({ menuContainer: { marginBottom: sizing(2.5), marginLeft: sizing(6), paddingTop: sizing(6), }, drawerToggle: { marginRight: sizing(3), padding: sizing(2), }, username: { fontSize: sizing(5.5), fontWeight: "600", color: colors(colorScheme).textPrimary, }, searchIcon: { margin: sizing(0.5), marginRight: sizing(2), }, searchBar: { flexDirection: "row", alignItems: "center", backgroundColor: colorScheme === "light" ? colors(colorScheme).backgroundPrimary : colors(colorScheme).backgroundSecondary, borderRadius: sizing(2), padding: sizing(3), marginVertical: sizing(2), marginHorizontal: sizing(6), }, categories: { marginTop: sizing(2), color: colors(colorScheme).textPrimary, }, categoriesTitle: { color: colors(colorScheme).textPrimary, marginBottom: sizing(2.5), marginLeft: sizing(6), }, loadingAnimation: { alignItems: "center", justifyContent: "center", flex: 1, }, horizontalSeparator: { width: sizing(0.5), }, resourceHeaderRow: { marginHorizontal: sizing(6), flexDirection: "row", }, resourcesContainer: { marginTop: sizing(4), }, resourcesTitle: { color: colors(colorScheme).textPrimary, flex: 1, }, image: { height: sizing(38), borderRadius: sizing(4), resizeMode: "cover", }, infoContainer: { marginVertical: 10, marginHorizontal: 12, }, number: { fontSize: sizing(5), fontWeight: "600", }, title: { fontSize: sizing(4), fontWeight: "500", }, icon: { marginRight: sizing(1), }, capacity: { flexDirection: "row", alignItems: "center", }, branchTitle: { fontSize: sizing(8), fontWeight: "600", marginTop: sizing(4), marginBottom: sizing(8), color: colors(colorScheme).textPrimary, }, }); return ( <Screen style={styles.container}> <View style={[presetStyles.row, styles.menuContainer]}> <TouchableOpacity style={styles.drawerToggle} onPress={navigation.toggleDrawer} > <Feather name="menu" color={colors(colorScheme).textPrimary} size={sizing(5.5)} /> </TouchableOpacity> <Text style={styles.username}> {t("welcome", { value: { en: user.first_name, hk: user.chinese_name, cn: user.chinese_name, }[i18n.language], })} </Text> </View> <TouchableOpacity style={[styles.searchBar, presetStyles.shadow]} onPress={() => navigation.navigate(routes.screens.SEARCH)} > <Feather name="search" size={16} color={colors(colorScheme).textSecondary} style={styles.searchIcon} /> <Text style={{ color: colors(colorScheme).textSecondary, }} > {t("searchTitle")} </Text> </TouchableOpacity> <ScrollView refreshControl={ <RefreshControl refreshing={isLoading} onRefresh={() => { fetchAllData(); getBookings(); }} title={t("common:pullToRefresh")} /> } > {(upcoming.length !== 0 || activeBooking) && ( <View style={[ presetStyles.marginHorizontal, { marginVertical: sizing(4), }, ]} > {activeBooking && ( <View style={{ marginBottom: sizing(4), }} > <Text style={[ presetStyles.listHeader, { marginBottom: sizing(2), color: colors(colorScheme) .textPrimary, }, ]} > {t("common:now")} </Text> <Animatable.View animation="fadeInRight"> <ViewBookingListItem active // onCheckIn date={moment( activeBooking.start_time ).format( { en: "LL", hk: "YYYY年MM月DD日", cn: "YYYY年MM月DD日", }[i18n.language] )} period={`${moment( activeBooking.start_time ).format("H:mm")} - ${moment( activeBooking.end_time ).format("H:mm")}`} location={ Boolean( { en: activeBooking.resource .title_en, hk: activeBooking.resource .title_hk, cn: activeBooking.resource .title_cn, }[i18n.language] ) ? `${ activeBooking.resource .number } • ${ { en: activeBooking .resource .title_en, hk: activeBooking .resource .title_hk, cn: activeBooking .resource .title_cn, }[i18n.language] }` : activeBooking.resource.number } onPress={() => { navigation.navigate( routes.navigators.BOOKINGS, { screen: routes.screens .BOOKING_DETAILS, initial: false, params: { item: activeBooking, }, } ); }} buttonTitle={ activeBooking.checkin_time == null ? moment().isAfter( moment( activeBooking.start_time ).add(15, "m") ) ? t("common:lateCheckIn", { value: moment().diff( moment( activeBooking.start_time ), "m" ), }) : t("common:checkIn") : t( moment().isAfter( moment( activeBooking.start_time ).add(15, "m") ) ? "common:late" : "common:checkedIn", { value: moment( activeBooking.checkin_time ).format("HH:mm"), } ) } disabled={ activeBooking.checkin_time == null ? false : true } onCheckIn={() => navigation.navigate( routes.navigators.BOOKINGS, { screen: routes.screens .BOOKING_DETAILS, initial: false, params: { item: activeBooking, checkInClicked: true, }, } ) } /> </Animatable.View> </View> )} {upcoming.length !== 0 && ( <View> <View style={presetStyles.row}> <Text style={[ presetStyles.listHeader, { color: colors(colorScheme) .textPrimary, }, ]} > {t("common:today")} </Text> </View> {upcoming.map((item, index) => ( <Animatable.View animation="fadeInRight" delay={index * 100} key={item.id} style={{ marginTop: sizing(3), }} > <ViewBookingListItem date={moment( item.start_time ).format( { en: "LL", hk: "YYYY年MM月DD日", cn: "YYYY年MM月DD日", }[i18n.language] )} period={`${moment( item.start_time ).format("H:mm")} - ${moment( item.end_time ).format("H:mm")}`} location={ Boolean( { en: item.resource .title_en, hk: item.resource .title_hk, cn: item.resource .title_cn, }[i18n.language] ) ? `${ item.resource.number } • ${ { en: item .resource .title_en, hk: item .resource .title_hk, cn: item .resource .title_cn, }[i18n.language] }` : item.resource.number } onPress={() => navigation.navigate( routes.navigators.BOOKINGS, { screen: routes.screens .BOOKING_DETAILS, initial: false, params: { item, }, } ) } /> </Animatable.View> ))} </View> )} </View> )} {!isLoading && ( <View style={styles.categories}> <Text style={[ presetStyles.listHeader, styles.categoriesTitle, ]} > {t("categories")} </Text> <FlatList contentContainerStyle={{ paddingLeft: sizing(6), }} horizontal // alwaysBounceHorizontal={false} showsHorizontalScrollIndicator={false} data={categories} keyExtractor={(item) => `${item.id}`} ItemSeparatorComponent={() => ( <View style={styles.horizontalSeparator} /> )} ListEmptyComponent={() => ( <View> <Text>{t("noResources")}</Text> </View> )} renderItem={({ item, index }) => ( <Animatable.View key={item.id} animation={{ 0: { opacity: 0, scale: 0.7, }, 1: { opacity: 1, scale: 1, }, }} duration={500} delay={400 + index * 125} > <CategoryItem displayCard={false} imageUrl={item.image_url} title={ { en: item.title_en, hk: item.title_hk, cn: item.title_cn, }[i18n.language] } selected={ item.id === selectedCategory ? true : false } onPress={() => { setSelectedCategory(item.id); }} /> </Animatable.View> )} /> </View> )} <View style={styles.resourcesContainer}> <View style={styles.resourceHeaderRow}> <Text style={[ presetStyles.listHeader, styles.resourcesTitle, ]} > {t("resources", { value: resources.length })} </Text> <TouchableOpacity onPress={() => setCampusOpen(true)} style={[presetStyles.row, styles.campusButton]} > <MaterialCommunityIcons name="office-building" size={24} color={colors(colorScheme).textSecondary} /> <Text style={{ fontSize: sizing(3), color: colors(colorScheme).textSecondary, fontWeight: "500", }} > {t("campuses")} </Text> </TouchableOpacity> </View> {resources.map((item, index) => { return ( <Animatable.View key={item.id} animation={{ 0: { opacity: 0, scale: 0.7, }, 1: { opacity: 1, scale: 1, }, }} duration={500} delay={400 + index * 125} > <ResourceItem item={item} key={item.id} onPress={() => { console.log(item); navigation.navigate( routes.screens.DETAILED_RESOURCES, { item } ); }} /> </Animatable.View> ); })} </View> </ScrollView> {!isLoading && ( <Modal visible={isCampusOpen} animationType="slide" presentationStyle="pageSheet" > <SafeAreaView> <ScrollView showsVerticalScrollIndicator={false} style={{ padding: sizing(4), paddingBottom: 0, backgroundColor: colors(colorScheme) .backgroundSecondary, }} > <TouchableOpacity onPress={() => setCampusOpen(false)} > <MaterialCommunityIcons name="close" size={24} color={colors(colorScheme).textSecondary} /> </TouchableOpacity> <View style={presetStyles.marginHorizontal}> <Text style={styles.branchTitle}> {t("campuses")} </Text> {branches.map((branch, index) => ( <Animatable.View key={branch.id} delay={index * 250} animation="fadeInUp" > <CampusItem item={branch} title={ { en: branch.title_en, hk: branch.title_hk, cn: branch.title_cn, }[i18n.language] } imageUrl={branch.image_url} onPress={() => { setCampusOpen(false); navigation.navigate( routes.screens .CAMPUS_RESOURCES, { branch } ); }} /> </Animatable.View> ))} </View> </ScrollView> </SafeAreaView> </Modal> )} </Screen> ); } export default MainScreen; import Multiselect from 'vue-multiselect' var app = new Vue({ el: '#app', components: { Multiselect }, data: { /* * Index View */ all: true, add: false, /* * Edit View */ tabs: { genres: true, details: false, edit: false, albums: false, singles: false } }, methods: { toggleIndex() { this.all = !this.all this.add = !this.add }, toggleTabs(tab) { this.tabs.genres = (tab == "genres" ? true : false) this.tabs.details = (tab == "details" ? true : false) this.tabs.edit = (tab == "edit" ? true : false) this.tabs.albums = (tab == "albums" ? true : false) this.tabs.singles = (tab == "singles" ? true : false) } }, computed: { isFormDirty() { return Object.keys(this.fields).some(key => this.fields[key].dirty); }, isFormInvalid() { return Object.keys(this.fields).some(key => this.fields[key].invalid); } } })var ColorPicker = require('./components/Color') ColorPicker.chrome = require('./components/ChromePicker') ColorPicker.compact = require('./components/CompactPicker') ColorPicker.material = require('./components/MaterialPicker') ColorPicker.photoshop = require('./components/PhotoshopPicker') ColorPicker.sketch = require('./components/SketchPicker') ColorPicker.slider = require('./components/SliderPicker') ColorPicker.swatches = require('./components/SwatchesPicker') module.exports = ColorPicker export { default } from './DomainSecurityDetailsCertificates'; <reponame>mpj/sharkey import sharkey from '../src/core' const logger = console.log.bind(console, '[LOGGER]') export default (tape) => { const reducerTest = (title, [input, result]) => tape(title, (t) => { t.plan(1) deepLooseEqual(sharkey(input), result) }) tape('when passing in connection parameters', (t) => { t.plan(1) t.deepLooseEqual( sharkey({ state: {}, message: ['connect', { host: '172.16.17.32', port: 1234}] }), { state: { connecting: true }, messages: [ [ 'net-connect', { host: '172.16.17.32', port: 1234 } ], [ 'net-set-encoding', 'utf8' ], ] } ) }) tape('when passing in connected', (t) => { t.plan(1) t.deepEqual(sharkey({ message: ['connected'], state: { connecting: true } }), { state: { connected: true } }) }) tape('when passing in connected', (t) => { t.plan(1) t.deepLooseEqual(sharkey({ state: { connecting: true }, message: ['connected'] }),{ state: { connected: true } }) }) tape('when issuing play', (t) => { t.plan(1) t.deepLooseEqual(sharkey({ state: { connected: true }, message: [ 'play' ] }), { messages: [ [ 'net-write', 'consume\n' ] ], state: { connected: true, playRequested: true } }) }) tape('on socket data', (t) => { t.plan(1) t.deepLooseEqual(sharkey({ state: { connected: true }, message: [ 'net-data', 'msg ' + JSON.stringify({ hello:123 })] }),{ messages: [[ 'log', { hello: 123} ]] }) }) reducerTest('ready (no guid)', { "state": { "topic": "mytopic", "connecting": true }, "message": [ "net-data", "ready\n" ] },{ "state": { "topic": "mytopic", "connecting": true }, "messages": [ [ "generate-guid" ], [ "net-data", "ready\n" ] ] }) reducerTest('on guid-generated', { "state": { "topic": "mytopic", "connecting": true }, "message": [ "guid-generated", "99c885d2-9ef9-4fdb-ba2c-00eaab94a820" ] },{ "state": { "lastGeneratedGUID": "99c885d2-9ef9-4fdb-ba2c-00eaab94a820" } }) reducerTest('ready (with guid generated)', { "message": [ "net-data", "ready\n" ] "state": { "topic": "mytopic", "connecting": true, "lastGeneratedGUID": "7091319e-101d-4fa4-b392-6b5cf6901755" }, },{ "state": { "connected": true, "playRequested": true }, "messages": [ [ "net-write", "consume mytopic 7091319e-101d-4fa4-b392-6b5cf6901755 smallest\n" ] ] }) } <reponame>auth0/configurated-sample-generator var express = require('express'); var logger = require('morgan'); var http = require('http'); var debug = require('debug')('server'); var PackerConfigurer = require('configurated-sample-generator'); var bodyParser = require('body-parser'); var app = express(); // Prettify HTML app.locals.pretty = true; app.use(logger('dev')); // Request body parsing middleware should be above methodOverride app.use(bodyParser.urlencoded()); app.use(bodyParser.json()); // Packer configuration var Packer = new PackerConfigurer() .setInformationLoader(function(context) { context.otherConfigId = 'other configuration id from db'; return context; }) .addTypeProcesor('server', PackerConfigurer.envFileCreator(function(context) { return { 'CONFIG_ID': context.configId, 'OTHER_CONFIG_ID': context.otherConfigId }; })) .getPacker(); app.get('/:org/:repo/:branch/create-package', function(req, res) { var packer = new Packer({ organization: req.params.org, repository: req.params.repo, gitBranch: req.params.branch, examplePath: req.query.path, sampleType: 'server', configurationFilePath: req.query.filePath, contextInformation: { configId: req.query.configId } }); packer.create() .then(function(stream) { debug("Got the stream OK"); res.writeHead('200', { 'Content-Type': 'application/zip', 'Content-disposition': 'attachment; filename=' + req.params.repo + '-sample.zip' }); res.end(stream,'binary'); }) .catch(function(error) { debug('There is an error', error); res.send(400, error); }); }); http.createServer(app).listen(3000, function (err) { console.log('listening in http://localhost:3000'); }); 'use strict'; var expect = require('chai').expect; var MockUI = require('../../helpers/mock-ui'); var rewire = require('rewire'); var Command = rewire('../../../lib/command'); describe('help command', function() { var ui; var commands = { 'test-command-1': new Command({ name: 'test-command-1', description: 'command-description', availableOptions: [ { name: 'option-with-default', type: String, default: 'default-value' }, { name: 'required-option', type: String, required: 'true', description: 'option-descriptionnnn' } ], run: function() {} }), 'test-command-2': new Command({ name: 'test-command-2', run: function() {} }) }; var helpCommand = rewire('../../../lib/commands/help'); beforeEach(function() { ui = new MockUI(); }); it('should generate complete help output', function() { helpCommand.ui = ui; helpCommand.run({ commands: commands }); expect(ui.output).to.include('ember test-command-1'); expect(ui.output).to.include('command-description'); expect(ui.output).to.include('option-with-default'); expect(ui.output).to.include('(Default: default-value)'); expect(ui.output).to.include('required-option'); expect(ui.output).to.include('(Required)'); expect(ui.output).to.include('ember test-command-2'); }); it('should generate specific help output', function() { helpCommand.ui = ui; helpCommand.run({ commands: commands, cliArgs: ['help', 'test-command-2'] }); expect(ui.output).to.include('test-command-2'); expect(ui.output).to.not.include('test-command-1'); }); }); <filename>server/src/routes.js const router = require('express').Router(); const controller = require('./controllers.js'); router.get('/', controller.products) router.get('/productId', controller.product) router.get('/productId/styles', controller.styles) router.get('/productId/related', controller.related) module.exports = router;<filename>LabWork_Project/doc/html/search/functions_6.js var searchData= [ ['outputmatrix_0',['OutPutMatrix',['../class_out_put_matrix.html#a46ed9cb9aee77c623a18b9dbc44cd0b5',1,'OutPutMatrix']]] ]; <filename>src/views/goulag.js import html from "./goulag.html"; import layout from "./newsletter.html"; import "./goulag.css"; import { doStyles } from "../services"; let elements = []; let body; export function show() { doStyles(); // convert plain HTML string into DOM elements let temporary = document.createElement("div"); temporary.innerHTML = layout; // append elements to body body = document.getElementsByTagName("body")[0]; while (temporary.children.length > 0) { elements.push(temporary.children[0]); body.appendChild(temporary.children[0]); } fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((json) => { return json; }) .then((json) => { document.getElementById("legalText").innerHTML = json.body; }); function handler(e) { let email = document.getElementById("email").value; if (email !== "") { document.getElementById("email").value = ""; } // TODO Send data to Kuzzle or Reach5 } document.getElementById("register").addEventListener("click", handler); } export function showWithParams(text) { // convert plain HTML string into DOM elements let temporary = document.createElement("div"); temporary.innerHTML = html; temporary.getElementsByClassName( "js-widget-kaaris-content" )[0].textContent = text; // append elements to body body = document.getElementsByTagName("body")[0]; while (temporary.children.length > 0) { elements.push(temporary.children[0]); body.appendChild(temporary.children[0]); } } <filename>modules/investor/components/InvestorReactApp/src/components/members/MembersList.js<gh_stars>0 import React from 'react'; import MembersListHead from './MembersListHead'; import MembersListItem from './MembersListItem'; import Spinner from '../common/loader/Spinner'; import MembersForm from './MembersForm'; const MembersList = (props) => { const {members, loading} = props; return ( <div className='members-list'> <MembersForm /> <MembersListHead /> <div> { loading ? <Spinner size={2} /> : members && members.length > 0 && members.map((item,i) => <MembersListItem key={item.id} num={i} item={item} />) } </div> </div> ) } export default MembersList;<reponame>onsightit/onsightit-web const { create, env } = require('sanctuary'); const { env: flutureEnv } = require('fluture-sanctuary-types'); const { Future, Par, seq } = require('fluture'); const checkTypes = process.env.NODE_ENV !== 'production'; const S = create({checkTypes, env: env.concat(flutureEnv)}); S.any = S.curry2((pred, list) => S.reduce(S.or, false, S.map(pred, list))); S.all = S.curry2((pred, list) => S.reduce(S.and, true, S.map(pred, list))); S.contains = S.curry2((elem, list) => S.any(S.equals(elem), list)); S.eitherToFuture = either => either.isLeft ? Future.reject(either.value) : Future.of(either.value); S.maybeToFuture = err => S.compose(S.eitherToFuture, S.maybeToEither(err)); module.exports = { S, F: Future, P: Par, seq }; // returns a license badge based on which license is passed in // If there is no license, returns an empty string function renderLicenseBadge(license) { switch (license) { case "MIT": return "[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)]"; break; case "APACHE 2.0": return "[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)]"; break; case "GPL 3.0": return "[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)]"; break; case "BSD 3": return "[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)]"; break; case "None": return ""; break; } } // returns the license link // If there is no license, returns an empty string function renderLicenseLink(license) { switch (license) { case "MIT": return "(https://opensource.org/licenses/MIT)"; break; case "APACHE 2.0": return "(https://opensource.org/licenses/Apache-2.0)"; break; case "GPL 3.0": return "(https://www.gnu.org/licenses/gpl-3.0)"; break; case "BSD 3": return "(https://opensource.org/licenses/BSD-3-Clause)"; break; case "None": return ""; break; } } // returns the license section of README // If there is no license, returns an empty string function renderLicenseSection(license) { switch (license) { case "MIT": return ` ## License This application is covered under the [${license}]${renderLicenseLink( license )} license.`; break; case "APACHE 2.0": return ` ## License This application is covered under the [${license}]${renderLicenseLink( license )} license.`; break; case "GPL 3.0": return ` ## License This application is covered under the [${license}]${renderLicenseLink( license )} license.`; break; case "BSD 3": return ` ## License This application is covered under the [${license}]${renderLicenseLink( license )} license.`; break; case "None": return ""; break; } } // returns the license section of table of contents // If there is no license, returns an empty string function renderLicenseTableOfContents(license) { if (license === "None") { return ""; } else { return ` - [License](#license)`; } } //generate markdown for README function generateMarkdown(answers) { return `# ${answers.title} ${renderLicenseBadge(answers.lic)}${renderLicenseLink(answers.lic)} ${answers.desc} ## Table of Contents - [Installation](#installation) - [Usage](#usage) - [Contributing](#contributing) - [Tests](#tests) - [Questions](#questions) ${renderLicenseTableOfContents(answers.lic)} ## Installation ${answers.instr} ## Usage ${answers.usage} ## Contributing ${answers.contr} ## Tests ${answers.test} ## Questions <a href="https://github.com/${answers.github}">Github for ${answers.github}</a> <a href="mailto:${answers.email}">Send me an email if you have any questions.</a> ${renderLicenseSection(answers.lic)} `; } module.exports = generateMarkdown; <filename>api/auth/service/authService.js<gh_stars>1-10 const jwt = require('jsonwebtoken'); const authConstants = require('../domain/authConstants'); require('dotenv').config(); const accessTokenEncryption = process.env.JWT_ENCRYPTION_ACCESS; const accessTokenExpiration = parseInt(process.env.JWT_EXPIRATION_ACCESS); const refreshTokenEncryption = process.env.JWT_ENCRYPTION_REFRESH; const refreshTokenExpiration = parseInt(process.env.JWT_EXPIRATION_REFRESH); module.exports = { verifyToken: (type, token) => jwt.verify(token, module.exports.setTokenEncryption(type), {}, (error, result) => ({ result: (!error) ? true : false, data: (!error) ? result : error, })), decodeToken: (type, token) => jwt.verify(token, module.exports.setTokenEncryption(type), { ignoreExpiration: true }, (error, decoded) => decoded), generateToken: (type, id) => jwt.sign({ tokenId: id }, module.exports.setTokenEncryption(type), { expiresIn: module.exports.setTokenExpiration(type) }), isTokenExpiredMessage: (verifiedTokenData) => verifiedTokenData.data.name === 'TokenExpiredError', isTokenExpiredMessageTime: (verifiedTokenData) => verifiedTokenData.data.expiredAt, setTokenEncryption: (tokenType) => ((tokenType === authConstants.TOKEN_TYPE.ACCESS_TOKEN) ? accessTokenEncryption : refreshTokenEncryption), setTokenExpiration: (tokenType) => ((tokenType === authConstants.TOKEN_TYPE.ACCESS_TOKEN) ? accessTokenExpiration : refreshTokenExpiration), }; 'use strict'; const AWS = require('aws-sdk'); // add new const const utils = require('../utils'); module.exports.handler = function(event, context, callback){ try{ exports.main(event).then(allTotals => { // console.log(allTotals) var response = { statusCode: 200, headers: {'Access-Control-Allow-Origin': '*'}, body: JSON.stringify( allTotals ), }; callback(null, response); }) }catch(exception){ // var response = { // statusCode: 400, // headers: {'Access-Control-Allow-Origin': '*'}, // body: JSON.stringify(exception), // }; callback(exception) } } exports.main = function(event){ let body = checkInputs(event) const dates = { start: new Date(body["startDate"] + " 15:00"), end: new Date(body["endDate"] + " 15:00") } const username = body["username"] return exports.getValues(username, dates) .then(assetsReturns => getTotalReturn(assetsReturns, dates) ) }; function checkInputs(event){ // console.log(event) utils.checkDefined(event["body"], "body"); let body = JSON.parse(event["body"]) // event = event["body"] utils.checkDefined(body["startDate"], "startDate"); utils.checkDefined(body["endDate"], "endDate"); utils.checkDefined(body["username"], "username"); console.log("startDate:", body["startDate"]); console.log("endDate:", body["endDate"]); console.log("username:", body["username"]); return body; } exports.getValues = function(username, dates){ var documentClient = new AWS.DynamoDB.DocumentClient(); var params = { TableName: process.env.DAILY_RETURN_TABLE, KeyConditionExpression: '#id = :id', ExpressionAttributeNames: { '#id': 'userId' }, ExpressionAttributeValues: { ':id': username } }; return new Promise( (resolve, reject) => documentClient.query(params, function(err, data) { if (err || typeof data.Items == undefined) reject(Error("<Get asset Returns from table> "+ err)); console.log(`${data.Items.length} asset returns loaded! typeof: ${typeof data.Items}`); resolve(data.Items) }) ) } function getTotalReturn(returns, dates){ let allTotals = {} for(let day = dates.start; day <= dates.end; day.setDate(day.getDate() + 1)){ if(day.getDay() == 0 || day.getDay()==6) continue; let dailyTotals = {cost: 0.0, return: 0.0, profit: 0.0} let foundOne = false returns.forEach(r => { let assetValues = r.assetValues[utils.dateToString(day)] if(assetValues){ dailyTotals.cost += assetValues.cost; dailyTotals.profit += assetValues.profit; dailyTotals.return += assetValues.return * assetValues.cost; foundOne = true } else if(foundOne) console.info("Values of", r.assetCode, "not available on day", utils.dateToString(day)) }) if(dailyTotals.cost > 0){ dailyTotals.return /= dailyTotals.cost; allTotals[utils.dateToString(day)] = {...dailyTotals}; console.log("return on", utils.dateToString(day), ":", allTotals[utils.dateToString(day)].return) } } return allTotals; } <gh_stars>0 $(document).ready(function(){ $('#eleves-niveaux_id').change(function(){ $("#eleves-groupe_id").html("<option value=''>Selectionner groupe</option>"); $.ajax({ type: 'POST', datatype: 'json', url: "http://rj-resto.com/ecole_application/backend/web/groupes/groupes_liste_by_niveau_for_select", cache: false, data: { niveaux_id: $(this).val() }, success: function (data) { var groupes = JSON.parse(data); groupes.forEach(function(groupe) { $("#eleves-groupe_id").append("<option value='" + groupe.id + "'>" + groupe.libelle + "</option>"); }); return false; }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log('erreur'); } }); }); }); <reponame>noahlevenson/passerby "use strict"; const Journal = require("../core/journal.js"); class Kbucket { constructor({max_size, prefix} = {}) { this.max_size = max_size; this.prefix = prefix; this.data = []; this.touch(); } /** * Fetch a Record from this k-bucket by index */ get(i) { return this.data[i]; } /** * Return this Kbucket's prefix */ get_prefix() { return this.prefix; } /** * Set time last touched (ms since Unix Epoch) */ touch() { this.touched = Date.now(); } /** * Get time last touched */ get_touched() { return this.touched; } /** * Has this Kbucket reached max capacity? */ is_full() { return this.data.length >= this.max_size; } /** * Return the current length of this Kbucket */ length() { return this.data.length; } /** * Enqueue a Record, evicting the least recently seen */ enqueue(rec) { // TODO: for sanity during development if (!(rec instanceof Record)) { throw new Error("rec must be instance of Record"); } // For safety, since all the kbucket records in a kbucket must describe unique contacts if (this.exists(rec.node_info)) { return; } this.data.push(rec); if (this.data.length > this.max_size) { this.data.shift(); } } /** * Check whether a Record for a given Node_info exists in this k-bucket. * Return a reference to the existing Record, or null if nonexistent */ exists(node_info) { for (let i = 0; i < this.data.length; i += 1) { const c = this.data[i]; if (c.node_info.node_id.equals(node_info.node_id) && c.node_info.addr === node_info.addr && c.node_info.port === node_info.port) { return c; } } return null; } /** * Delete a Record from this k-bucket. rec must be a reference to an * Record that exists in this k-bucket */ delete(rec) { this.data.splice(this.data.indexOf(rec), 1); } /** * Return a shallow copy of this Kbucket's underlying array */ to_array() { return [...this.data]; } } class Record { static MAX_LOCK_ATTEMPTS = 3; static LOCK_BASE_SECONDS = 100; static BACKOFF_FUNC = x => (Record.LOCK_BASE_SECONDS ** x) * 1000; constructor({node_info, lock_until = Number.NEGATIVE_INFINITY, n_locks = 0} = {}) { this.node_info = node_info; this.lock_until = lock_until; this.n_locks = n_locks; } is_locked() { return this.lock_until > Date.now(); } is_stale() { return this.n_locks === Record.MAX_LOCK_ATTEMPTS; } lock(reason = "Unknown") { if (this.is_stale()) { return; } this.n_locks += 1; const ttl = !this.is_stale() ? Record.BACKOFF_FUNC(this.n_locks) : Number.POSITIVE_INFINITY; this.lock_until = Date.now() + ttl; Journal.log("KDHT", `Locked contact ${this.node_info.node_id.to_base64_str()} ` + `(${this.node_info.addr}:${this.node_info.port}) <${reason}> ` + `${this.n_locks}/${Record.MAX_LOCK_ATTEMPTS} ` + `(${ttl < Number.POSITIVE_INFINITY ? (ttl / 1000).toFixed(1) + " sec" : "permanent"})`); } } module.exports = { Kbucket, Record };<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.BookingHandler = void 0; require("reflect-metadata"); const typeorm_1 = require("typeorm"); const Booking_1 = require("./entity/Booking"); const User_1 = require("./entity/User"); const Room_1 = require("./entity/Room"); class BookingHandler { GetMultiple(predicate) { switch (predicate.CLASSNAME) { case Booking_1.Booking.name: return this.GetBooking(predicate, false); case User_1.User.name: return this.GetUser(predicate, false); case Room_1.Room.name: return this.GetRoom(predicate, false); default: throw new Error("Invalid type detected - ERROR ERROR ERROR"); } } GetOne(predicate) { switch (predicate.CLASSNAME) { case Booking_1.Booking.name: return this.GetBooking(predicate, true); case User_1.User.name: return this.GetUser(predicate, true); case Room_1.Room.name: return this.GetRoom(predicate, true); default: throw new Error("Invalid type detected - ERROR ERROR ERROR"); } } GetBooking(predicate, onlyOne) { let result = null; this.PerformActionOnConnection((connection) => __awaiter(this, void 0, void 0, function* () { let query = yield connection.getRepository(Booking_1.Booking).createQueryBuilder('booking'). leftJoinAndSelect('booking.user', 'user').leftJoinAndSelect('booking.room', 'room') .where(predicate); if (onlyOne) result = yield query.getOne(); else result = yield query.getMany(); })); return result; } GetUser(predicate, onlyOne) { let result = null; this.PerformActionOnConnection((connection) => __awaiter(this, void 0, void 0, function* () { let query = yield connection.getRepository(User_1.User).createQueryBuilder('user'). leftJoinAndSelect('user.bookings', 'bookings').where(predicate); if (onlyOne) result = yield query.getOne(); else result = yield query.getMany(); })); return result; } GetRoom(predicate, onlyOne) { let result = null; this.PerformActionOnConnection((connection) => __awaiter(this, void 0, void 0, function* () { let query = yield connection.getRepository(Room_1.Room).createQueryBuilder('room'). leftJoinAndSelect('room.bookings', 'bookings').where(predicate); if (onlyOne) result = yield query.getOne(); else result = yield query.getMany(); })); return result; } Create(entity) { if (entity.id != 0) throw new Error("Id of a new entity has to be 0"); let result = null; this.PerformActionOnConnection((connection) => __awaiter(this, void 0, void 0, function* () { result = yield connection.manager.save(entity); })); return result; } Update(entity) { if (entity.id == 0) throw new Error("Id of an updating entity cannot be 0"); let result = null; this.PerformActionOnConnection((connection) => __awaiter(this, void 0, void 0, function* () { result = yield connection.manager.save(entity); })); return result; } Delete(entity) { if (entity.id == 0) throw new Error("Id of a deleting entity cannot be 0"); let result = null; this.PerformActionOnConnection((connection) => __awaiter(this, void 0, void 0, function* () { result = yield connection.manager.remove(entity); })); return result; } PerformActionOnConnection(action) { (0, typeorm_1.createConnection)().then((connection) => __awaiter(this, void 0, void 0, function* () { return action(connection); })).catch(error => console.log(error)); } } exports.BookingHandler = BookingHandler; console.log('main.js works!!') /* global Math */ // // Copyright (C) 2016-2017 DBot. All other content, that was used, but not created in this project, is licensed under their own licenses, and belong to their authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // 'use strict'; Array.Trim = function(arr) { let newArray = []; arr.forEach(function(item, i) { if (item !== '') { newArray.push(item); }; }); return newArray; }; Array.Random = function(arr) { return arr[Math.Random(0, arr.length - 1)]; }; Array.concat = function(obj, sep) { sep = sep || ''; if (Array.isArray(obj)) return obj.join(sep); else { let first = true; let out = ''; for (let i in obj) { let item = obj[i]; if (first) { first = false; out = item; } else { out += sep + item; } } return out; } }; Array.Append = function(Dest, Source) { for (let i in Source) { Dest.push(Source[i]); } return Dest; }; Array.Copy = function(Source) { let Dest = []; for (let i in Source) { Dest.push(Source[i]); } return Dest; }; Array.MapDiff = function(newMap, oldMap) { const added = []; const removed = []; for (const key of oldMap.keys()) { if (!newMap.has(key)) { removed.push(oldMap.get(key)); } } for (const key of newMap.keys()) { if (!oldMap.has(key)) { added.push(newMap.get(key)); } } return [added, removed]; }; Array.Diff = function(newArray, oldArray) { const added = []; const removed = []; for (const c of newArray) { if (!oldArray.includes(c)) { added.push(c); } } for (const c of oldArray) { if (!newArray.includes(c)) { removed.push(c); } } return [added, removed]; }; Array.random = Array.Random; Array.Concat = Array.concat; Array.append = Array.Append; Array.copy = Array.Copy; /** * Created by Terry on 2017-01-10. */ export const GET_SECONDARY_LEVELS = 'GET_SECONDARY_LEVELS';var class_tempo_test_1_1_tests_1_1_memory_cell_test = [ [ "MemoryCellFlatten", "class_tempo_test_1_1_tests_1_1_memory_cell_test.html#ad180b6452cef607dcca7434d4a5ec422", null ], [ "MemoryCellMerge", "class_tempo_test_1_1_tests_1_1_memory_cell_test.html#a1036557963b821c9b425961612f8fc94", null ] ];const { createRobot } = require('./robot') module.exports = createRobot <reponame>VOLTTRON/volttron-AIRCx-visualization<gh_stars>1-10 // Copyright (c) 2020, Battelle Memorial Institute // All rights reserved. // 1. Battelle Memorial Institute (hereinafter Battelle) hereby grants // permission to any person or entity lawfully obtaining a copy of this // software and associated documentation files (hereinafter "the Software") // to redistribute and use the Software in source and binary forms, with or // without modification. Such person or entity may use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and // may permit others to do so, subject to the following conditions: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimers. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // - Other than as used herein, neither the name Battelle Memorial Institute // or Battelle may be used in any form whatsoever without the express // written consent of Battelle. // 2. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL BATTELLE OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // This material was prepared as an account of work sponsored by an agency of the // United States Government. Neither the United States Government nor the United // States Department of Energy, nor Battelle, nor any of their employees, nor any // jurisdiction or organization that has cooperated in the development of these // materials, makes any warranty, express or implied, or assumes any legal // liability or responsibility for the accuracy, completeness, or usefulness or // any information, apparatus, product, software, or process disclosed, or // represents that its use would not infringe privately owned rights. // Reference herein to any specific commercial product, process, or service by // trade name, trademark, manufacturer, or otherwise does not necessarily // constitute or imply its endorsement, recommendation, or favoring by the // United States Government or any agency thereof, or Battelle Memorial Institute. // The views and opinions of authors expressed herein do not necessarily state or // reflect those of the United States Government or any agency thereof. // PACIFIC NORTHWEST NATIONAL LABORATORY // operated by // BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY // under Contract DE-AC05-76RL01830 import { ButtonBase, Paper, Tooltip, Typography } from "@material-ui/core"; import { withStyles } from "@material-ui/core/styles"; import clsx from "clsx"; import filters from "constants/filters"; import groups from "constants/groups"; import { white } from "constants/palette"; import { fetchDetailed, selectDetailed, selectDetailedBusy, selectDetailedRequest, selectSources, } from "controllers/data/action"; import _ from "lodash"; import moment from "moment"; import React from "react"; import { connect } from "react-redux"; import Popup from "./Popup"; import styles from "./styles"; class Graph extends React.Component { constructor(props) { super(props); const { form } = props; const group = groups.parse(_.get(form, "group", "day")); const time = moment(_.get(form, "date")); const noData = filters.parse("no-data"); const outsideRange = filters.parse("outside-range"); const start = moment(props.start); const end = moment(props.end); const range = { start: start.clone(), end: end.clone(), }; switch (group.name) { case "month": range.start = moment.max( range.start, time .clone() .startOf("month") .startOf("day") ); range.end = moment.min( range.end, time .clone() .endOf("month") .endOf("day") ); break; case "week": range.start = moment.max( range.start, time .clone() .startOf("week") .startOf("day") ); range.end = moment.min( range.end, time .clone() .endOf("week") .endOf("day") ); break; case "day": range.start = time.clone().startOf("day"); range.end = time.clone().endOf("day"); break; default: // no need to handle all cases } const pad = moment.min( end .clone() .date(1) .subtract(11, "month"), end .clone() .subtract(1, "year") .add(1, "day") ); const months = [ { name: pad.format("MMM"), label: pad.format("MMM").slice(0, 1), month: pad.month(), year: pad.year(), tooltip: pad.format("MMMM YYYY"), }, ]; const base = []; while (pad.isBefore(end)) { const month = months[months.length - 1]; base.push({ path: [`${month.year}`, `${month.month}`, `${pad.date()}`], x: months.length, y: pad.date(), size: 10, color: pad.isBefore(start) ? outsideRange.color : noData.color, date: pad.isBefore(start) ? null : pad.clone(), selected: pad.isBetween(range.start, range.end, "hour", true), tooltip: pad.format("MMMM Do YYYY"), }); pad.add(1, "day"); if (months[months.length - 1].month !== pad.month()) { months.push({ name: pad.format("MMM"), label: pad.format("MMM").slice(0, 1), month: pad.month(), year: pad.year(), tooltip: pad.format("MMMM YYYY"), }); } } const month = months[months.length - 1]; base.push({ path: [`${month.year}`, `${month.month}`, `${pad.date()}`], x: months.length, y: pad.date(), size: 10, color: pad.isBefore(start) ? outsideRange.color : noData.color, date: pad.clone(), selected: pad.isBetween(range.start, range.end, "hour", true), tooltip: pad.format("MMMM Do YYYY"), }); this.state = { start: moment(props.start), end: moment(props.end), months: months, base: base, temp: [], show: null, }; } isPrevious = () => { const { show, start } = this.state; if (show) { return !show.date.isSame(start, "day"); } }; isNext = () => { const { show, end } = this.state; if (show) { return !show.date.isSame(end, "day"); } }; handleValueClick = (value) => { const { current, sources } = this.props; if (value.date) { const { site, building, device, diagnostic } = current; const topic = Object.values( _.get(sources, [diagnostic, site, building, device], {}) ); this.setState({ show: value }); this.props.fetchDetailed( _.merge({}, current, { start: value.date .clone() .startOf("day") .format(), end: value.date .clone() .endOf("day") .format(), topic: topic, }) ); } }; handleValuePrevious = () => { const { current, sources } = this.props; const { base, months, show } = this.state; if (this.isPrevious()) { const { site, building, device, diagnostic } = current; const topic = Object.values( _.get(sources, [diagnostic, site, building, device], {}) ); const date = show.date.clone().subtract("day", 1); const mark = _.find(base, { x: _.findIndex(months, { month: date.month(), year: date.year() }) + 1, y: date.date(), }); this.setState({ show: mark }); this.props.fetchDetailed( _.merge({}, current, { start: date .clone() .startOf("day") .format(), end: date .clone() .endOf("day") .format(), topic: topic, }) ); } }; handleValueNext = () => { const { current, sources } = this.props; const { base, months, show } = this.state; if (this.isNext()) { const { site, building, device, diagnostic } = current; const topic = Object.values( _.get(sources, [diagnostic, site, building, device], {}) ); const date = show.date.clone().add("day", 1); const mark = _.find(base, { x: _.findIndex(months, { month: date.month(), year: date.year() }) + 1, y: date.date(), }); this.setState({ show: mark }); this.props.fetchDetailed( _.merge({}, current, { start: date .clone() .startOf("day") .format(), end: date .clone() .endOf("day") .format(), topic: topic, }) ); } }; handleClose = () => { this.setState({ show: null }); }; renderHeader() { const { classes } = this.props; const { months } = this.state; return ( <React.Fragment> <div className={classes.monthsTitle}> <span className={classes.month}> <strong>Month</strong> </span> </div> <div className={classes.months} style={{ width: months.length * 19 }}> {months.map((m) => ( <Tooltip key={`tooltip-${m.year}-${m.month}`} title={m.tooltip} placement="top" > <span key={`month-${m.year}-${m.month}`} className={classes.month} > <strong>{m.label}</strong> </span> </Tooltip> ))} </div> </React.Fragment> ); } renderChart() { const { classes, data, form } = this.props; const { base, months } = this.state; const likely = filters.parse("likely"); const sensitivity = _.get(form, "sensitivity", "normal"); const filter = filters.parse(form.filter); const outsideRange = filters.parse("outside-range"); const marks = base.map((item) => { let temp = {}; if (item.color !== outsideRange.color) { const values = Object.values(_.get(data, item.path, {})) .reduce((p, v) => p.concat(v), []) .filter((v) => { const t = filter.isType(v[sensitivity]); return t; }) .map((v) => ({ filter: filters.getType(v[sensitivity]), value: v[sensitivity], })); if (filter === likely) { const errors = _.filter(values, { filter: filters.parse("fault") }) .length; const passed = _.filter(values, { filter: filters.parse("okay") }) .length; const aggregate = filters.aggregate(errors, passed); temp = { color: aggregate.color, value: 0 }; } else { for (let index = 0; index < filters.values.length; index++) { const filter = filters.values[index]; const value = _.find(values, { filter }); if (value) { temp = { color: filter.color, value: value }; break; } } } } return _.merge({}, item, temp); }); return ( <div className={classes.chart} style={{ width: months.length * 19 + 4 }}> {marks.map((mark, index) => ( <React.Fragment key={`fragment-${mark.x}-${mark.y}`}> {mark.selected && ( <div key={`selected-${mark.x}-${mark.y}`} className={classes.selected} style={{ left: mark.x * 19 - 20, top: mark.y * 21 - 20, height: _.get(marks, [index + 1, "selected"], false) && _.get(marks, [index + 1, "path", "1"]) === mark.path[1] ? "44px" : "24px", }} /> )} <Tooltip key={`tooltip-${mark.tooltip}`} title={mark.tooltip} placement="top" > <ButtonBase key={`mark-${mark.x}-${mark.y}`} className={clsx( classes.mark, Boolean(mark.date) && classes.hover )} style={{ left: mark.x * 19 - 14, top: mark.y * 21 - 14, background: mark.color, }} onClick={() => this.handleValueClick(mark)} /> </Tooltip> </React.Fragment> ))} </div> ); } renderTitle() { const { classes, label } = this.props; const { months } = this.state; return ( <div className={classes.footer} style={{ width: months.length * 19 + 4 }}> <Typography className={classes.footerLabel} variant="body1"> <strong>{_.replace(label, / Dx$/i, "")}</strong> </Typography> </div> ); } renderFooter() { const { classes } = this.props; return <div className={classes.footer} style={{ height: "25px" }} />; } render() { const { classes, form, current, data, detailed, busy, request, label, } = this.props; const { show } = this.state; return ( <Paper className={classes.paper} color={white} elevation={3}> {this.renderTitle()} {this.renderHeader()} {this.renderChart()} {this.renderFooter()} {show && ( <Popup form={form} current={current} path={_.concat([label], show.path)} data={_.merge({}, show, { diagnostic: _.get(data, show.path, {}), detailed: detailed, busy: busy, })} request={request} onClose={this.handleClose} isNext={this.isNext()} isPrevious={this.isPrevious()} onNext={this.handleValueNext} onPrevious={this.handleValuePrevious} /> )} </Paper> ); } } const mapStateToProps = (state) => ({ detailed: selectDetailed(state), busy: selectDetailedBusy(state), request: selectDetailedRequest(state), sources: selectSources(state), }); const mapActionToProps = { fetchDetailed }; export default connect( mapStateToProps, mapActionToProps )(withStyles(styles)(Graph)); <filename>app/view/searchResults/searchResults_test.js 'use strict'; describe('csrLookupApp.searchResults module', function() { beforeEach(module('csrLookupApp.searchResults')); describe('searchResults controller', function() { var scope, searchResultsCtrl; beforeEach(inject(function($rootScope, $controller) { document.body.insertAdjacentHTML( 'afterbegin', '<div id="map"></div>' ); scope = $rootScope.$new(); searchResultsCtrl = $controller('SearchResultsCtrl', {$scope: scope}); })); it('should be defined', inject(function($controller) { expect(searchResultsCtrl).toBeDefined(); })); }); }); <reponame>devrafalko/tablio import props from 'typeof-properties'; import args from 'typeof-arguments'; import type from 'of-type'; import joinArray from 'join-array'; import Style from './class-style'; import Column from './class-column'; import {isPositiveInteger} from './utils'; export default class Validator { constructor() { this.data = {}; this.data.defaults = {}; } validate(config, callback) { this.hasConfigPassed(config); this.validateConfig(); this.addDefaultConfigValues(); this.validateConfigStyle(); this.validateConfigData(); this.validateConfigPageRows(); this.validateConfigPageTiles(); this.validateConfigColumns(); this.validateColumnProperties(); callback(this.data.config); } get styleList() { return joinArray({ array: Style.list, separator: ', ', last: ' or ', each: (value) => `"${value}"` }); } get errors() { return { incorrectStyleValue: () => new Error(`The [String] config.style property must be: ${this.styleList}.`), invalidRecordType: (index) => new TypeError(`Invalid [${index}] record type. Each item of [Array] config.data must be of [Object] type.`), invalidPageRowsItem: (index) => new TypeError(`Invalid [${index}] row tile value. Each item of [Array] config.pageRows must be a [Number] positive integer.`), outOfRangePageRowsItem: (index) => new Error(`Invalid [${index}] row tile value. The maximal acceptable value of [Array] config.pageRows [Number] item is 5000.`), outOfLengthPageRows: () => new Error('The [Array] config.pageRows should contain at most 10 items.'), tilesPageTilesValue: () => new Error('The config.pageTiles property must be a [Number] positive integer value between 2 and 25.'), emptyColumnsArray: () => new Error('The [Array] config.columns should contain at least 1 item.'), invalidColumnType: (index) => new TypeError(`Invalid [${index}] column type. Each item of [Array] config.columns must be of [Object] type.`) }; } get defaultConfigTypes() { return { style: [String, null, undefined], data: [Array, undefined], pageRows: [Array, null, undefined], pageTiles: [Number, undefined], header: [Boolean, undefined], columns: [Array], ready: [Function, undefined] }; } get defaultConfigValues() { return { style: Style.defaultStyle, data: [], pageRows: { default: 0, set: [10, 25, 50, 150] }, pageTiles: 5, header: true, ready: undefined }; } hasConfigPassed(userConfig) { args(arguments, [[Object]]); this.data.userConfig = userConfig; } validateConfig() { props(this.data.userConfig, this.defaultConfigTypes); } addDefaultConfigValues() { const config = Object.assign({}, this.data.userConfig); const defaults = this.defaultConfigValues; for (let property in defaults) { if (config.hasOwnProperty(property)) continue; config[property] = defaults[property]; this.data.defaults[property] = true; } this.data.config = config; } validateConfigStyle() { if (this.data.defaults['style'] || !type(this.data.config.style, String)) return; if (Style.list.some((style) => style === this.data.config.style)) return; throw this.errors.incorrectStyleValue(); } validateConfigData() { if (this.data.defaults['data']) return; for (let i = 0; i < this.data.config.data.length; i++) { let record = this.data.config.data[i]; if (!type(record, Object)) throw this.errors.invalidRecordType(i); } } validateConfigPageRows() { const rows = this.data.config.pageRows; const rowsMap = new Map(); const rowsSet = []; if (this.data.defaults['pageRows'] || !type(rows, Array)) return; if (!rows.length) return this.data.config.pageRows = null; for (let i = 0; i < rows.length; i++) { let row = rows[i]; if (!isPositiveInteger(row)) throw this.errors.invalidPageRowsItem(i); if (row > 5000) throw this.errors.outOfRangePageRowsItem(i); rowsMap.set(row, i === 0); } if (rowsMap.size > 10) throw this.errors.outOfLengthPageRows(); rowsMap.forEach((val, prop) => rowsSet.push(prop)); rowsSet.sort((a, b) => a - b); this.data.config.pageRows = { default: rowsSet.indexOf(rows[0]), set: rowsSet }; } validateConfigPageTiles() { if (this.data.defaults['pageTiles']) return; const tiles = this.data.config.pageTiles; if (!isPositiveInteger(tiles) || tiles > 25 || tiles < 2) throw this.errors.tilesPageTilesValue(); } validateConfigColumns() { const columns = this.data.config.columns; if (!columns.length) throw this.errors.emptyColumnsArray(); for (let i = 0; i < columns.length; i++) { let column = columns[i]; if (!type(column, Object)) throw this.errors.invalidColumnType(i); } } validateColumnProperties() { const columns = this.data.config.columns; const columnCollection = []; for (let i = 0; i < columns.length; i++) { let column = columns[i]; columnCollection.push(new Column({ userData:column, columnIndex:i, columnCollection:columnCollection, headerDefined:this.data.config.header })); } this.data.config.columns = columnCollection; } }<reponame>blueww/azure-sdk-for-node /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * Information about a stateless service instance deployed on a node. * * @extends models['DeployedServiceReplicaInfo'] */ class DeployedStatelessServiceInstanceInfo extends models['DeployedServiceReplicaInfo'] { /** * Create a DeployedStatelessServiceInstanceInfo. * @member {string} [instanceId] */ constructor() { super(); } /** * Defines the metadata of DeployedStatelessServiceInstanceInfo * * @returns {object} metadata of DeployedStatelessServiceInstanceInfo * */ mapper() { return { required: false, serializedName: 'Stateless', type: { name: 'Composite', className: 'DeployedStatelessServiceInstanceInfo', modelProperties: { serviceName: { required: false, serializedName: 'ServiceName', type: { name: 'String' } }, serviceTypeName: { required: false, serializedName: 'ServiceTypeName', type: { name: 'String' } }, serviceManifestName: { required: false, serializedName: 'ServiceManifestName', type: { name: 'String' } }, codePackageName: { required: false, serializedName: 'CodePackageName', type: { name: 'String' } }, partitionId: { required: false, serializedName: 'PartitionId', type: { name: 'String' } }, replicaStatus: { required: false, serializedName: 'ReplicaStatus', type: { name: 'String' } }, address: { required: false, serializedName: 'Address', type: { name: 'String' } }, servicePackageActivationId: { required: false, serializedName: 'ServicePackageActivationId', type: { name: 'String' } }, hostProcessId: { required: false, serializedName: 'HostProcessId', type: { name: 'String' } }, serviceKind: { required: true, serializedName: 'ServiceKind', type: { name: 'String' } }, instanceId: { required: false, serializedName: 'InstanceId', type: { name: 'String' } } } } }; } } module.exports = DeployedStatelessServiceInstanceInfo; /** * showdown extension * * see [GitHub](https://github.com/excing/showdown-extensions) */ (function (extension) { 'use strict'; if (typeof showdown !== 'undefined') { // global (browser or nodejs global) extension(showdown); } else if (typeof define === 'function' && define.amd) { // AMD define(['showdown'], extension); } else if (typeof exports === 'object') { // Node, CommonJS-like module.exports = extension(require('showdown')); } else { // showdown was not found so we throw throw Error('Could not find showdown library'); } }(function (showdown) { 'use strict'; var latexCodeBlocks = []; /** * 支持数学公式的编辑,语法参照 LaTeX。 * * Support editing of mathematical formulas, syntax reference LaTeX. */ showdown.extension('mathjax', function () { return [ { type: 'lang', regex: '(?:^|\\n)~D~D(.*)\\n([\\s\\S]*?)\\n~D~D', replace: function (match, leadingSlash, codeblock) { // Check if we matched the leading \ and return nothing changed if so if (leadingSlash === '\\') { return match; } else { return '\n\n~Z' + (latexCodeBlocks.push({text: match.substring(1), codeblock: codeblock}) - 1) + 'Z\n\n'; } } }, { type: 'lang', regex: '~D([^`\\f\\n\\r]+?)~D', replace: function (match, leadingSlash, codeblock) { // Check if we matched the leading \ and return nothing changed if so if (leadingSlash === '\\') { return match; } else { return '~Z' + (latexCodeBlocks.push({text: match, codeblock: codeblock}) - 1) + 'Z'; } } }, { type: 'output', regex: '~(Z)(\\d+)\\1', replace: function (match, leadingSlash, index) { // Check if we matched the leading \ and return nothing changed if so if (leadingSlash === '\\') { return match; } else { index = Number(index); var code = latexCodeBlocks[index].text; return code.replace(/~D/g, '$$'); } } }, // 清除缓存 // clear cache { type: 'output', filter: function (text, globals_converter, options) { latexCodeBlocks = []; return text; } }, ]; }); var diagramSeqBlocks = []; var diagramFlowBlocks = []; /** * 支持时序图和流程图的编辑,语法参见:js-sequence-diagrams 和 flowchart。 * * Support for the editing of sequence diagrams and flowcharts. See the syntax: js-sequence-diagrams and flowchart. */ showdown.extension('diagrams', function () { return [ { type: 'lang', regex: '(?:^|\\n)```seq(.*)\\n([\\s\\S]*?)\\n```', replace: function (match, leadingSlash, codeblock) { // Check if we matched the leading \ and return nothing changed if so if (leadingSlash === '\\') { return match; } else { return '\n\n~X' + (diagramSeqBlocks.push({text: match.substring(1), codeblock: codeblock}) - 1) + 'X\n\n'; } } }, { type: 'lang', regex: '(?:^|\\n)```flow(.*)\\n([\\s\\S]*?)\\n```', replace: function (match, leadingSlash, codeblock) { // Check if we matched the leading \ and return nothing changed if so if (leadingSlash === '\\') { return match; } else { return '~Y' + (diagramFlowBlocks.push({text: match, codeblock: codeblock}) - 1) + 'Y'; } } }, { type: 'output', regex: '~(X|Y)(\\d+)\\1', replace: function (match, leadingSlash, index) { // Check if we matched the leading \ and return nothing changed if so if (leadingSlash === '\\') { return match; } else { index = Number(index); if ('X' == match.charAt(1)) { var seq = diagramSeqBlocks[index].codeblock; return '<div style="white-space: pre" class="diagram seq", id="diagram_seq_' + index + '">' + seq + '</div>'; } else { var flow = diagramFlowBlocks[index].codeblock; return '<div style="white-space: pre" class="diagram flow", id="diagram_flow_' + index + '">' + flow + '</div>'; } } } }, // 清除缓存 // clear cache { type: 'output', filter: function (text, globals_converter, options) { diagramSeqBlocks = []; diagramFlowBlocks = []; return text; } }, ]; }); /** * 支持 ![](https://video.mp4) 语法的视频显示。 * * Support for the syntax of video display, syntax: ![](https://video.mp4) */ showdown.extension('video', function () { return [ { type: 'output', regex: '<p><img src="(.+(mp4|ogg|webm).*?)"(.+?)\\/>', replace: function (match, url, format, other) { // Check if we matched the leading \ and return nothing changed if so if (url === ('.' + format)) { return match; } else { // src="https://image.png" alt="image alt text" title="image title" width="100" height="auto" // var regex = /([a-z]+)="(.*?)"/g; // return `<video src="${url}" ${other} controls>I am sorry; your browser does not support HTML5 video in WebM with VP8/VP9 or MP4 with H.264.</video>`; return `<video ${other} controls><source src="${url}" type="video/${format}">I am sorry, Your browser does not support the <code>video</code> element.</video>`; } } }, ]; }); /** * 支持 ![](https://video.mp4) 语法的视频显示。 * * Support for the syntax of video display, syntax: ![](https://video.mp4) */ showdown.extension('audio', function () { return [ { type: 'output', regex: '<p><img src="(.+(mp3|ogg|wav).*?)"(.+?)\\/>', replace: function (match, url, format, other) { // Check if we matched the leading \ and return nothing changed if so if (url === ('.' + format)) { return match; } else { // src="https://image.png" alt="image alt text" title="image title" width="100" height="auto" // var regex = /([a-z]+)="(.*?)"/g; if ('mp3' === format) format = 'mpeg'; // return `<video src="${url}" ${other} controls>I am sorry; your browser does not support HTML5 video in WebM with VP8/VP9 or MP4 with H.264.</video>`; return `<audio ${other} controls><source src="${url}" type="audio/${format}">I am sorry, Your browser does not support the <code>audio</code> element.</audio>`; } } }, ]; }); var needCat = false; var catalogues = []; /** * 支持 <h1> 到 <h6> 的目录显示 * * Support <h1> to <h6> catalog display */ showdown.extension('catalog', function () { return [ { type: 'lang', regex: '\\n(\\[TOC\\])\\n', replace: function (match) { needCat = true; return '[[[TOC]]]]]'; } }, { type: 'output', regex: '<h\\d id="(.+?)">(.*?)<\\/h(\\d)>', replace: function (match, id, title, level) { if (needCat) { var title_ahref_reg = /(.*?)<a .*>(.*?)<\/a>(.*)/g; var title_ahref_reg_match = title_ahref_reg.exec(title); if (null !== title_ahref_reg_match) { title = title_ahref_reg_match[1] + ' ' + title_ahref_reg_match[2] + ' ' + title_ahref_reg_match[3]; } catalogues.push({'id': id, 'title': title, 'level': level}); } return match; } }, { type: 'output', filter: function (text, globals_converter, options) { if (catalogues.length <= 0) return text; var catDiv = '<div class="cat" id="toc_catalog">'; var lastLevel = 0; var levelCount = 0; for (var i = 0; i < catalogues.length; i++) { var cat = catalogues[i]; if (cat.level < lastLevel) { var count = lastLevel - cat.level; if (levelCount <= count) { count = levelCount - 1; } for (var l = 0; l < count; l++) { catDiv += ('</ul>'); } levelCount -= count; } else if (lastLevel < cat.level) { catDiv += ('<ul>'); levelCount ++; } catDiv += ('<li><a href="#' + cat.id + '">' + cat.title + '</a></li>'); lastLevel = cat.level; } catDiv += '</ul></div>'; needCat = false; catalogues = []; return text.replace(/\[\[\[TOC\]\]\]\]\]/g, catDiv); } }, ]; }); /** * 支持 <h1> 到 <h6> 标题的锚点按钮 * * Support for anchor buttons for <h1> to <h6> titles */ showdown.extension('anchor', function () { return [ { type: 'output', regex: '<h\\d id="(.+?)">(.*?)<\\/h(\\d)>', replace: function (match, id, title, level) { // github anchor style var octicon_html = `<a class="anchor" aria-hidden="true" href="#${id}"><svg class="octicon" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>`; return `<h${level} id="${id}">${octicon_html}${title}</h${level}>`; } }, ]; }); }));angular.module('MyApp') .controller('MainCtrl', ['$scope', '$rootScope', '$route', '$window', 'Post', 'GitHub', '$routeParams', 'ngProgress' ,function($scope, $rootScope, $route, $window, Post, GitHub, $routeParams, ngProgress) { $scope.$on('$routeChangeSuccess', function($currentRoute, $previousRoute) { if ($routeParams.name) { ngProgress.start(); Post.getBySlug($routeParams.name, function(post) { $scope.post = post; ngProgress.complete(); $window.document.title = $scope.post.title + " - " + 'JS Recipes' // Get last commit date GitHub.lastCommit(post.file, function(data, status, headers, config) { if (status === 0) return $scope.lastUpdated = 'Unknown'; $scope.lastUpdated = new Date(data[0].commit.committer.date).toLocaleString(); }); }); } else { $window.document.title = $route.current.title ? $route.current.title + " - " + 'JS Recipes' : 'JS Recipes'; $rootScope.title = $route.current.title; Post.getPosts(function(posts) { $scope.posts = posts; }); GitHub.getContributors(function(contributors) { $scope.contributors = contributors.slice(0,10); }); } }); }]); /* Copyright 2019 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Adobe Campaign Standard Core SDK */ 'use strict' const Swagger = require('swagger-client') const loggerNamespace = 'aio-lib-campaign-standard' const logger = require('@adobe/aio-lib-core-logging')(loggerNamespace, { level: process.env.LOG_LEVEL }) const fetch = require('cross-fetch') const { reduceError, requestInterceptor, responseInterceptor, createRequestOptions } = require('./helpers') const { codes } = require('./SDKErrors') /** * Returns a Promise that resolves with a new CampaignStandardCoreAPI object. * * @param {string} tenantId the tenant id (your personal organization in Campaign Standard) * @param {string} apiKey the API key for your Adobe I/O Campaign Standard Integration * @param {string} accessToken the access token for your Adobe I/O Campaign Standard Integration * @return {Promise<CampaignStandardCoreAPI>} */ function init (tenantId, apiKey, accessToken) { return new Promise((resolve, reject) => { const clientWrapper = new CampaignStandardCoreAPI() clientWrapper.init(tenantId, apiKey, accessToken) .then(initializedSDK => { logger.debug('sdk initialized successfully') resolve(initializedSDK) }) .catch(err => { logger.debug(`sdk init error: ${err}`) reject(err) }) }) } /** * This class provides methods to call Adobe Campaign Standard APIs. * Before calling any method initialize the instance by calling the `init` method on it * with valid values for tenantId, apiKey and accessToken */ class CampaignStandardCoreAPI { /** * Initializes this object. * * @param {string} tenantId the tenant id (your personal organization in Campaign Standard) * @param {string} apiKey the API key for your Adobe I/O Campaign Standard Integration * @param {string} accessToken the access token for your Adobe I/O Campaign Standard Integration * @returns {CampaignStandardCoreAPI} */ async init (tenantId, apiKey, accessToken) { // init swagger client const spec = require('../spec/api.json') const swagger = new Swagger({ spec: spec, requestInterceptor, responseInterceptor, usePromise: true }) this.sdk = (await swagger) const initErrors = [] if (!tenantId) { initErrors.push('tenantId') } if (!apiKey) { initErrors.push('apiKey') } if (!accessToken) { initErrors.push('accessToken') } if (initErrors.length) { const sdkDetails = { tenantId, apiKey, accessToken } throw new codes.ERROR_SDK_INITIALIZATION({ sdkDetails, messageValues: `${initErrors.join(', ')}` }) } /** the tenant id (your personal organization in Campaign Standard) */ this.tenantId = tenantId /** the api key from your Adobe I/O Campaign Standard integration */ this.apiKey = apiKey /** the access token from your Adobe I/O Campaign Standard integration */ this.accessToken = accessToken return this } __createRequestOptions ({ body } = {}) { return createRequestOptions({ tenantId: this.tenantId, apiKey: this.apiKey, accessToken: this.accessToken, body }) } __createFilterParams (params = {}) { const { filters, hasCustomFilter, lineCount, order, descendingSort } = params const fixedParams = ['filters', 'hasCustomFilter', 'lineCount', 'order', 'descendingSort'] const retParams = { EXT: '', FILTERS: [] } // filter for extra keys, set these to the 'freeForm' property (for free-form query parameters) retParams.freeForm = Object.keys(params) .filter(key => !fixedParams.includes(key)) .reduce((o, key) => { o[key] = params[key] return o }, {}) if (filters) { // this is a fixed path param retParams.FILTERS = filters.join('/') } if (hasCustomFilter) { // this is modifies the url (append to resource) retParams.EXT = 'Ext' } // this is a fixed query param if (lineCount) { // lineCount default is 25 retParams._lineCount = lineCount } if (order) { // this is a fixed query param retParams._order = order if (descendingSort) { // ascending is the default retParams._order += '%20desc' } } return retParams } /** * Get all Profile records * * @param {Object} [parameters={}] parameters to pass * @param {Array} [parameters.filters=[]] apply the filters to the results. List of filters for a resource can be retrieved via a getMetadataForResource call * @param {Boolean} [parameters.hasCustomFilter=false] set to true if you have a custom filter. Defaults to false. * @param {integer} [parameters.lineCount=25] limit the number of records to return (default is 25) * @param {string} [parameters.order] the field to order your records by (see the fields of a {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#profile|Profile}) * @param {boolean} [parameters.descendingSort=false] set to true to get results in descending order (default is ascending) * * @see getMetadataForResource */ getAllProfiles (parameters) { const sdkDetails = { parameters } return new Promise((resolve, reject) => { this.sdk.apis.profile.getAllProfiles(this.__createFilterParams(parameters), this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_ALL_PROFILES({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Create a Profile record * * @param {Object} profileObject see {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#profile|profile properties} */ createProfile (profileObject) { const sdkDetails = { profileObject } return new Promise((resolve, reject) => { this.sdk.apis.profile.createProfile(this.__createFilterParams({}), this.__createRequestOptions({ body: profileObject })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_CREATE_PROFILE({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Update a Profile record * * @param {string} profilePKey the PKey property of a Profile record * @param {Object} profileObject see {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#profile|profile properties}. Only set the properties you want to update. */ updateProfile (profilePKey, profileObject) { const sdkDetails = { profileObject, profilePKey } return new Promise((resolve, reject) => { this.sdk.apis.profile.updateProfile({ PROFILE_PKEY: profilePKey }, this.__createRequestOptions({ body: profileObject })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_UPDATE_PROFILE({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Get a Profile record * * @param {string} profilePKey the PKey property of a Profile record */ getProfile (profilePKey) { const sdkDetails = { profilePKey } return new Promise((resolve, reject) => { this.sdk.apis.profile.getProfile({ PROFILE_PKEY: profilePKey }, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_PROFILE({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Get all Service records * * @param {Object} [parameters={}] parameters to pass * @param {Array} [parameters.filters=[]] apply the filters to the results. List of filters for a resource can be retrieved via a getMetadataForResource call * @param {Boolean} [parameters.hasCustomFilter=false] set to true if you have a custom filter. Defaults to false. * @param {integer} [parameters.lineCount=25] limit the number of records to return (default is 25) * @param {string} [parameters.order] the field to order your records by (see the fields of a {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#service|Service}) * @param {descendingSort} [parameters.descendingSort=false] set to true to get results in descending order (default is ascending) * * @see getMetadataForResource */ getAllServices (parameters) { const sdkDetails = { parameters } return new Promise((resolve, reject) => { this.sdk.apis.service.getAllServices(this.__createFilterParams(parameters), this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_ALL_SERVICES({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Create a Service record * * @param {Object} serviceObject see {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#service|service properties} */ createService (serviceObject) { const sdkDetails = { serviceObject } return new Promise((resolve, reject) => { this.sdk.apis.service.createService(this.__createFilterParams({}), this.__createRequestOptions({ body: serviceObject })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_CREATE_SERVICE({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Get a Service record * * @param {string} servicePKey the PKey property of a Service record */ getService (servicePKey) { const sdkDetails = { servicePKey } return new Promise((resolve, reject) => { this.sdk.apis.service.getService({ SERVICE_PKEY: servicePKey }, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_SERVICE({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Get the marketing history of a Profile * * @param {string} profilePKey the PKey property of a Profile record */ getHistoryOfProfile (profilePKey) { const sdkDetails = { profilePKey } return new Promise((resolve, reject) => { this.sdk.apis.history.getHistoryOfProfile({ PROFILE_PKEY: profilePKey }, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_HISTORY_OF_PROFILE({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Get the metadata information for a resource. * * @param {string} resource one of profile, service, history */ getMetadataForResource (resource) { const sdkDetails = { resource } return new Promise((resolve, reject) => { const acceptedResources = ['profile', 'service', 'history'] if (!acceptedResources.includes(resource.toLowerCase())) { reject(new codes.ERROR_INVALID_RESOURCE_TYPE({ sdkDetails, messageValues: `${acceptedResources.join(', ')}` })) } this.sdk.apis.metadata.getMetadataForResource({ RESOURCE: resource }, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_METADATA_FOR_RESOURCE({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Get all the custom resource collections linked to the Profile table. */ getCustomResources () { return new Promise((resolve, reject) => { this.sdk.apis.metadata.getCustomResources({}, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_CUSTOM_RESOURCES({ messageValues: reduceError(err) })) }) }) } /** * Create a new GDPR request. * * @param {Object} gdprRequest see {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#create-a-new-gdpr-request|the properties} that are needed. */ createGDPRRequest (gdprRequest) { const sdkDetails = { gdprRequest } return new Promise((resolve, reject) => { this.sdk.apis.gdpr.createGDPRRequest({}, this.__createRequestOptions({ body: gdprRequest })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_CREATE_GDPR_REQUEST({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Get data about the current GDPR request. */ getGDPRRequest () { return new Promise((resolve, reject) => { this.sdk.apis.gdpr.getGDPRRequest({}, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_GDPR_REQUEST({ messageValues: reduceError(err) })) }) }) } /** * Get the GDPR data file. * * @param {string} privacyRequestDataUrl this is acquired from a getGDPRRequest call * @param {string} requestInternalName the request internal name * * @see getGDPRRequest */ getGDPRDataFile (privacyRequestDataUrl, requestInternalName) { const sdkDetails = { privacyRequestDataUrl, requestInternalName } return new Promise((resolve, reject) => { this.postDataToUrl(privacyRequestDataUrl, { name: requestInternalName }) .then(res => responseInterceptor(res).json()) .then(json => resolve(json)) .catch(err => reject(new codes.ERROR_GET_GDPR_DATA_FILE({ sdkDetails, messageValues: reduceError(err) }))) }) } /** * Send a transactional event. * * @param {string} eventId the type of event you want to send. This depends on the {@link https://docs.adobe.com/content/help/en/campaign-standard/using/administrating/configuring-channels/configuring-transactional-messaging.html|event definition}. * @param {Object} eventBody the event data to send. This depends on the {@link https://docs.adobe.com/content/help/en/campaign-standard/using/administrating/configuring-channels/configuring-transactional-messaging.html|event definition}. */ sendTransactionalEvent (eventId, eventBody) { const sdkDetails = { eventId, eventBody } return new Promise((resolve, reject) => { this.sdk.apis.messaging.sendTransactionalEvent( { ORGANIZATION: this.tenantId, EVENT_ID: eventId }, this.__createRequestOptions({ body: eventBody })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_SEND_TRANSACTIONAL_EVENT({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Gets data about a transactional event (status, properties) * * @param {string} eventId the type of event you want to send * @param {string} eventPKey the PKey of an event (you get this from a sendTransactionalEvent call) * @see sendTransactionalEvent */ getTransactionalEvent (eventId, eventPKey) { const sdkDetails = { eventId, eventPKey } return new Promise((resolve, reject) => { this.sdk.apis.messaging.getTransactionalEvent( { ORGANIZATION: this.tenantId, EVENT_ID: eventId, EVENT_PKEY: eventPKey }, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_TRANSACTIONAL_EVENT({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Gets the properties of a workflow. * * @param {string} workflowId the id of the workflow */ getWorkflow (workflowId) { const sdkDetails = { workflowId } return new Promise((resolve, reject) => { this.sdk.apis.workflow.getWorkflow({ WORKFLOW_ID: workflowId }, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_WORKFLOW({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Trigger a workflow. * * @param {string} workflowTriggerUrl the trigger url for a workflow. You can get this from a call to getWorkflow * @param {Object} [workflowParameters] workflow parameters object. see the payload in the {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#triggering-a-signal-activity|docs} * @param {string} workflowParameters.source the triggering request source * @param {Object} workflowParameters.parameters the parameters to send to the workflow (paramater name, and parameter value pairs) * @see getWorkflow */ triggerSignalActivity (workflowTriggerUrl, workflowParameters) { const sdkDetails = { workflowTriggerUrl, workflowParameters } return new Promise((resolve, reject) => { this.postDataToUrl(workflowTriggerUrl, workflowParameters) .then(res => responseInterceptor(res).json()) .then(json => resolve(json)) .catch(err => reject(new codes.ERROR_TRIGGER_SIGNAL_ACTIVITY({ sdkDetails, messageValues: reduceError(err) }))) }) } /** * Controls execution of a workflow. * * @param {string} workflowId the id of the workflow * @param {string} command the command to execute for the workflow. one of start, pause, resume, stop */ controlWorkflow (workflowId, command) { const sdkDetails = { workflowId, command } return new Promise((resolve, reject) => { const acceptedCommands = ['start', 'pause', 'resume', 'stop'] if (!acceptedCommands.includes(command.toLowerCase())) { reject(new codes.ERROR_INVALID_WORKFLOW_CONTROL_COMMAND({ sdkDetails, messageValues: `${acceptedCommands.join(', ')}` })) } this.sdk.apis.workflow.controlWorkflow({ WORKFLOW_ID: workflowId }, this.__createRequestOptions({ body: { method: command.toLowerCase() } })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_CONTROL_WORKFLOW({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Get all available orgUnits * * @param {Object} [parameters={}] parameters to pass * @param {Array} [parameters.filters=[]] apply the filters to the results. List of filters for a resource can be retrieved via a getMetadataForResource call * @param {integer} [parameters.lineCount=25] limit the number of records to return (default is 25) * @param {string} [parameters.order] the field to order your records by (see the fields of a {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#orgunitbase|OrgUnitBase}) * @param {descendingSort} [parameters.descendingSort=false] set to true to get results in descending order (default is ascending) * * @see getMetadataForResource */ getAllOrgUnits (parameters) { const sdkDetails = { parameters } return new Promise((resolve, reject) => { this.sdk.apis.organization.getAllOrgUnits(this.__createFilterParams(parameters), this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_ALL_ORG_UNITS({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Gets a Profile record (with it's orgUnit property) * * @param {string} profilePKey the PKey property of a Profile record */ getProfileWithOrgUnit (profilePKey) { const sdkDetails = { profilePKey } return new Promise((resolve, reject) => { this.sdk.apis.organization.getProfileWithOrgUnit({ PROFILE_PKEY: profilePKey }, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_PROFILE_WITH_ORG_UNIT({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Update the orgUnit of a Profile * * @param {string} profilePKey the PKey property of a Profile record * @param {string} orgUnitPKey the PKey property of a OrgUnitBase record */ updateProfileOrgUnit (profilePKey, orgUnitPKey) { const sdkDetails = { profilePKey, orgUnitPKey } return new Promise((resolve, reject) => { this.sdk.apis.organization.updateProfileOrgUnit({ PROFILE_PKEY: profilePKey }, this.__createRequestOptions({ body: { orgUnit: { PKey: orgUnitPKey } } })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_UPDATE_PROFILE_ORG_UNIT({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Update the properties of an OrgUnitBase. * * @param {string} orgUnitPKey the PKey property of a OrgUnitBase record * @param {Object} orgUnitObject see {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#orgunitbase|orgUnitBase properties}. Only set the properties you want to update. */ updateOrgUnit (orgUnitPKey, orgUnitObject) { const sdkDetails = { orgUnitPKey, orgUnitObject } return new Promise((resolve, reject) => { this.sdk.apis.organization.updateOrgUnit({ ORGUNIT_PKEY: orgUnitPKey }, this.__createRequestOptions({ body: orgUnitObject })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_UPDATE_ORG_UNIT({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Post to an absolute url. * * @param {string} url the url to POST to * @param {Object} body the POST body */ postDataToUrl (url, body) { const options = this.__createRequestOptions() const request = new fetch.Request(url, { method: 'post', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json;charset=utf-8', 'Cache-Control': 'no-cache', Authorization: `Bearer ${options.securities.authorized.BearerAuth.value}`, 'X-Api-Key': options.securities.authorized.ApiKeyAuth.value } }) return fetch(requestInterceptor(request)) } /** * Gets data from a relative url. Helper function. * * @param {string} relativeUrl the relative url (returned from some ACS API calls) */ getDataFromRelativeUrl (relativeUrl) { const sdkDetails = { relativeUrl } return new Promise((resolve, reject) => { this.sdk.apis.util.getDataFromRelativeUrl({ RELATIVE_URL: relativeUrl }, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_DATA_FROM_RELATIVE_URL({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Get all Custom Resource records * * @param {string} customResource the custom resource to get records from * @param {Object} [parameters={}] parameters to pass * @param {Array} [parameters.filters=[]] apply the filters to the results. List of filters for a resource can be retrieved via a getMetadataForResource call * @param {Boolean} [parameters.hasCustomFilter=false] set to true if you have a custom filter. Defaults to false. * @param {integer} [parameters.lineCount=25] limit the number of records to return (default is 25) * @param {string} [parameters.order] the field to order your records by (see the fields of a {@link https://docs.campaign.adobe.com/doc/standard/en/api/ACS_API.html#profile|Profile}) * @param {boolean} [parameters.descendingSort=false] set to true to get results in descending order (default is ascending) * * @see getMetadataForResource */ getAllCustomResources (customResource, parameters) { const sdkDetails = { customResource, parameters } return new Promise((resolve, reject) => { const filterParams = { ...this.__createFilterParams(parameters), CUSTOMRESOURCE: customResource } this.sdk.apis.customresource.getAllCustomResources(filterParams, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_GET_ALL_CUSTOM_RESOURCES({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Update a Custom Resource record * * @param {string} customResource the custom resource * @param {string} customResourcePKey the PKey property of a Custom Resource record * @param {Object} customResourceObject A Custom Resource object. Only set the properties you want to update. */ updateCustomResource (customResource, customResourcePKey, customResourceObject) { const sdkDetails = { customResource, customResourceObject, customResourcePKey } return new Promise((resolve, reject) => { this.sdk.apis.customresource.updateCustomResource({ CUSTOMRESOURCE: customResource, PKEY: customResourcePKey }, this.__createRequestOptions({ body: customResourceObject })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_UPDATE_CUSTOM_RESOURCE({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Create a Custom Resource record * * @param {string} customResource the custom resource * @param {Object} customResourceObject a Custom Resource object */ createCustomResource (customResource, customResourceObject) { const sdkDetails = { customResource, customResourceObject } return new Promise((resolve, reject) => { this.sdk.apis.customresource.createCustomResource({ CUSTOMRESOURCE: customResource }, this.__createRequestOptions({ body: customResourceObject })) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_CREATE_CUSTOM_RESOURCE({ sdkDetails, messageValues: reduceError(err) })) }) }) } /** * Delete a Custom Resource record * * @param {string} customResource the custom resource * @param {string} customResourcePKey the PKey property of a Custom Resource record * @param {Object} customResourceObject a Custom Resource object */ deleteCustomResource (customResource, customResourcePKey) { const sdkDetails = { customResource, customResourcePKey } return new Promise((resolve, reject) => { this.sdk.apis.customresource.deleteCustomResource({ CUSTOMRESOURCE: customResource, PKEY: customResourcePKey }, this.__createRequestOptions()) .then(response => { resolve(response) }) .catch(err => { reject(new codes.ERROR_DELETE_CUSTOM_RESOURCE({ sdkDetails, messageValues: reduceError(err) })) }) }) } } module.exports = { init: init } <filename>src/sap.ui.fl/src/sap/ui/fl/Cache.js /*! * ${copyright} */ sap.ui.define(["sap/ui/fl/LrepConnector", "sap/ui/fl/Utils"], function (LrepConnector, Utils) { "use strict"; /** * Helper object to access a change from the back end. * Access helper object for each change (and variant) fetched from the back end * * @namespace * @alias sap.ui.fl.Cache * @experimental Since 1.25.0 * @author SAP SE * @version ${version} */ var Cache = function () { }; Cache._isOn = true; Cache._entries = {}; Cache._switches = {}; Cache._oFlexDataPromise = undefined; /** * Get the list of the switched-on business functions from the flex response * * @returns {object} map which has switched-on business functions as its keys * * @public */ Cache.getSwitches = function () { return Cache._switches; }; /** * Indicates if the cache is active or not (for testing) * * @returns {boolean} Is Cache currently active or not * * @public */ Cache.isActive = function () { return Cache._isOn; }; /** * Sets the active state * * @param {boolean} bActive - cache active or not * * @public */ Cache.setActive = function (bActive) { Cache._isOn = bActive; }; /** * Returns the last cached flex data request promise * * @returns {Promise} Promise of a flex data request * * @protected */ Cache.getFlexDataPromise = function () { return Cache._oFlexDataPromise; }; /** * Returns the entries stored in the cache. * * @return {object} _entries - a map of flexibility references and server responses for the given entry * * @protected */ Cache.getEntries = function () { return Cache._entries; }; /** * Clears whole entries stored in the cache. * * @protected * @sap-restricted sap.ui.fl */ Cache.clearEntries = function () { Cache._entries = {}; }; /** * Returns the entry stored in the cache and creates an entry if needed. * * @param {string} sComponentName - Name of the application component * @param {string} sAppVersion - Currently running version of application * @return {object} Cache entry of specific application component and application version * * @protected */ Cache.getEntry = function (sComponentName, sAppVersion) { if (!Cache._entries[sComponentName]) { Cache._entries[sComponentName] = {}; } if (!Cache._entries[sComponentName][sAppVersion]) { Cache._entries[sComponentName][sAppVersion] = { file: { changes: { changes: [], contexts: [], variantSection: {}, ui2personalization: {} } } }; } return Cache._entries[sComponentName][sAppVersion]; }; /** * Clears a single entry stored in the cache for a specific application component and application version. * * @param {string} sComponentName - Name of the application component * @param {string} sAppVersion - Current running version of application * * @protected * @sap-restricted sap.ui.fl */ Cache.clearEntry = function (sComponentName, sAppVersion) { Cache.getEntry(sComponentName, sAppVersion); Cache._entries[sComponentName][sAppVersion] = {}; }; /** * Deletes a single entry stored in the cache for a specific application component and application version. * * @param {string} sComponentName - Name of the application component * @param {string} sAppVersion - Current running version of application * * @private * @sap-restricted sap.ui.fl */ Cache._deleteEntry = function (sComponentName, sAppVersion) { if (Cache._entries[sComponentName] && Cache._entries[sComponentName][sAppVersion]) { delete Cache._entries[sComponentName][sAppVersion]; } if (jQuery.isEmptyObject(Cache._entries[sComponentName])) { delete Cache._entries[sComponentName]; } }; /** * This method retrieves the changes for a given * component. It answers all subsequent calls with the same promise, which * will resolve with the same result. In the success case, it will keep the * promise to resolve all calls in future event loop execution paths with * the same result. In case of an error, it will delete the initial promise * to give calls from future execution paths the chance to re-request the * changes from the back end. * * If the cache is not active, the method just delegates the call to the * loadChanges method of the given LrepConnector. * * @param {sap.ui.fl.LrepConnector} oLrepConnector - LrepConnector instance to retrieve the changes with * @param {map} mComponent - Contains component data needed for reading changes * @param {string} mComponent.name - Name of the component * @param {string} mComponent.appVersion - Current running version of application * @param {map} [mPropertyBag] - Contains additional data needed for reading changes * @param {object} [mPropertyBag.appDescriptor] - Manifest that belongs to actual component * @param {string} [mPropertyBag.siteId] - <code>sideId</code> that belongs to actual component * @param {string} [mPropertyBag.cacheKey] - key to validate the client side stored cache entry * @param {string} [mPropertyBag.url] - address to which the request for change should be sent in case the data is not cached * @param {string} [mPropertyBag.appName] - name where bundled changes from the application development are stored * @returns {Promise} resolves with the change file for the given component, either from cache or back end * * @public */ Cache.getChangesFillingCache = function (oLrepConnector, mComponent, mPropertyBag) { if (!this.isActive()) { return oLrepConnector.loadChanges(mComponent, mPropertyBag); } var sComponentName = mComponent.name; var sAppVersion = mComponent.appVersion || Utils.DEFAULT_APP_VERSION; var oCacheEntry = Cache.getEntry(sComponentName, sAppVersion); if (oCacheEntry.promise) { return oCacheEntry.promise; } var oChangesBundleLoadingPromise = Cache._getChangesFromBundle(mPropertyBag); // in case of no changes present according to async hints if (mPropertyBag && mPropertyBag.cacheKey === "<NO CHANGES>") { var currentLoadChanges = oChangesBundleLoadingPromise.then(function (aChanges) { oCacheEntry.file = { changes: { changes : aChanges, contexts : [], variantSection : {}, ui2personalization : {} }, componentClassName: sComponentName }; return oCacheEntry.file; }); oCacheEntry.promise = currentLoadChanges; return currentLoadChanges; } var oFlexDataPromise = oLrepConnector.loadChanges(mComponent, mPropertyBag); var oChangesLoadingPromise = oFlexDataPromise.then(function (oResult) { return oResult; }, function (oError) { // if the back end is not reachable we still cache the results in a valid way because the url request is // cached by the browser in its negative cache anyway. var sErrorMessage = jQuery.sap.formatMessage("flexibility service is not available:\nError message: {0}", oError.status); jQuery.sap.log.error(sErrorMessage); return Promise.resolve({ changes: { changes: [], contexts: [], variantSection: {}, ui2personalization: {} } }); }); var currentLoadChanges = Promise.all([oChangesBundleLoadingPromise, oChangesLoadingPromise]).then(function (aValues) { var aChangesFromBundle = aValues[0]; var mChanges = aValues[1]; if (mChanges && mChanges.changes) { if (mChanges.changes.settings && mChanges.changes.settings.switchedOnBusinessFunctions) { mChanges.changes.settings.switchedOnBusinessFunctions.forEach(function (sValue) { Cache._switches[sValue] = true; }); } mChanges.changes.changes = aChangesFromBundle.concat(mChanges.changes.changes); } oCacheEntry.file = mChanges; return oCacheEntry.file; }, function (err) { Cache._deleteEntry(sComponentName, sAppVersion); throw err; }); oCacheEntry.promise = currentLoadChanges; Cache._oFlexDataPromise = oFlexDataPromise; return currentLoadChanges; }; /** * Function to get the changes-bundle.json file stored in the application sources. * This data is returned only in case it is part of the application preload or in debug mode. * In case no debugging takes place and the file is not loaded an empty list is returned. * * @param {map} mPropertyBag * @param {string} mPropertyBag.appName Fully qualified name of the application * @return {Promise} Promise resolving with an array of changes stored in the application source code * * @private */ Cache._getChangesFromBundle = function (mPropertyBag) { var bChangesBundleDeterminable = mPropertyBag && mPropertyBag.appName; if (!bChangesBundleDeterminable) { return Promise.resolve([]); } var sResourcePath = jQuery.sap.getResourceName(mPropertyBag.appName, "/changes/changes-bundle.json"); var bChangesBundleLoaded = jQuery.sap.isResourceLoaded(sResourcePath); if (bChangesBundleLoaded) { return Promise.resolve(jQuery.sap.loadResource(sResourcePath)); } else { if (!sap.ui.getCore().getConfiguration().getDebug()) { return Promise.resolve([]); } // try to load the source in case a debugging takes place and the component could have no Component-preload try { return Promise.resolve(jQuery.sap.loadResource(sResourcePath)); } catch (e) { jQuery.sap.log.warning("flexibility did not find a changesBundle.json for the application"); return Promise.resolve([]); } } }; Cache.NOTAG = "<NoTag>"; /** * Function to retrieve the cache key of the SAPUI5 flexibility request of a given application * * @param {map} mComponent * @param {string} mComponent.name Name of the application component * @param {string} mComponent.appVersion Version of the application component * @return {Promise} Returns the promise resolved with the determined cache key * * @private * @restricted sap.ui.fl * */ Cache.getCacheKey = function (mComponent) { if (!mComponent || !mComponent.name || !mComponent.appVersion) { jQuery.sap.log.warning("Not all parameters were passed to determine a flexibility cache key."); return Promise.resolve(Cache.NOTAG); } return this.getChangesFillingCache(new LrepConnector(), mComponent).then(function (oWrappedChangeFileContent) { if (oWrappedChangeFileContent && oWrappedChangeFileContent.etag) { return oWrappedChangeFileContent.etag; } else { return Cache.NOTAG; } }); }; /** * @private * @param {object} oComponent - Contains component data needed for getting change array * @param {string} oComponent.name - Name of the component * @param {string} oComponent.appVersion - Current running version of application * @returns {array} Array of changes */ Cache._getChangeArray = function (oComponent) { var sComponentName = oComponent.name; var sAppVersion = oComponent.appVersion || Utils.DEFAULT_APP_VERSION; var oEntry = Cache.getEntry(sComponentName, sAppVersion); return oEntry.file.changes.changes; }; /** * Add a change for the given component to the cached changes. * * @param {object} oComponent - Contains component data needed for adding change * @param {string} oComponent.name - Name of the component * @param {string} oComponent.appVersion - Current running version of application * @param {object} oChange - The change in JSON format * @public */ Cache.addChange = function (oComponent, oChange) { var aChanges = Cache._getChangeArray(oComponent); if (!aChanges) { return; } aChanges.push(oChange); }; /** * Updates a change for the given component in the cached changes. * * @param {object} oComponent - Contains component data needed for adding change * @param {string} oComponent.name - Name of the component * @param {string} oComponent.appVersion - Current running version of application * @param {object} oChange - The change in JSON format * @public */ Cache.updateChange = function (oComponent, oChange) { var aChanges = Cache._getChangeArray(oComponent); if (!aChanges) { return; } for (var i = 0; i < aChanges.length; i++) { if (aChanges[i].fileName === oChange.fileName) { aChanges.splice(i, 1, oChange); break; } } }; /** * Delete a change for the given component from the cached changes. * * @param {object} oComponent - Contains component data needed for adding change * @param {string} oComponent.name - Name of the component * @param {string} oComponent.appVersion - Current running version of application * @param {object} oChangeDefinition - The change in JSON format * @public */ Cache.deleteChange = function (oComponent, oChangeDefinition) { var aChanges = Cache._getChangeArray(oComponent); if (!aChanges) { return; } for (var i = 0; i < aChanges.length; i++) { if (aChanges[i].fileName === oChangeDefinition.fileName) { aChanges.splice(i, 1); break; } } }; /** * Retrievea a personalization object stored for an application under a given container ID and item name; * in case no itemName is given all items for the given container key are returned. * * @param {string} sReference The reference of the application for which the personalization should be retrieved * @param {string} sAppVersion Currently running version of the application * @param {string} sContainerKey The key of the container in which the personalization was stored * @param {string} [sItemName] The item name under which the personalization was stored * @returns {Promise} Promise resolving with the object stored under the passed container key and item name, * or undefined in case no entry was stored for these; * in case no sItemName was passed all entries known for the container key */ Cache.getPersonalization = function (sReference, sAppVersion, sContainerKey, sItemName) { var mComponent = { name: sReference, appVersion: sAppVersion }; return this.getChangesFillingCache(LrepConnector.createConnector(), mComponent).then(function (oResponse) { if (!oResponse || !oResponse.changes || !oResponse.changes.ui2personalization || !oResponse.changes.ui2personalization[sContainerKey]) { // return undefined in case there is no personalization for the item or an empty array if a list was requested return sItemName ? undefined : []; } if (!sItemName) { return oResponse.changes.ui2personalization[sContainerKey] || []; } return oResponse.changes.ui2personalization[sContainerKey].filter(function (oEntry) { return oEntry.itemName === sItemName; })[0]; }); }; /** * Stores a personalization object for an application under a given key pair. * * @param {map} mPersonalization * @param {string} mPersonalization.reference The reference of the application for which the personalization should be stored * @param {string} mPersonalization.containerKey The key of the container in which the personalization should stored * @param {string} mPersonalization.itemName The name under which the personalization should be stored * @param {string} mPersonalization.content The personalization content to be stored * @returns {Promise} Promise resolving with the object stored under the passed container key and item name, * or undefined in case no entry was stored for these */ Cache.setPersonalization = function (mPersonalization) { if (!mPersonalization || !mPersonalization.reference || !mPersonalization.containerKey || !mPersonalization.itemName || !mPersonalization.content) { return Promise.reject("not all mandatory properties were provided for the storage of the personalization"); } return LrepConnector.createConnector().send("/sap/bc/lrep/ui2personalization/", "PUT", mPersonalization, {}) .then(this._addPersonalizationToEntries.bind(this, mPersonalization)); }; Cache._addPersonalizationToEntries = function (mPersonalization) { Object.keys(this._entries[mPersonalization.reference]).forEach(function (sVersion) { var oEntry = this._entries[mPersonalization.reference][sVersion]; var oPersonalizationSubsection = oEntry.file.changes.ui2personalization; if (!oPersonalizationSubsection[mPersonalization.containerKey]) { oPersonalizationSubsection[mPersonalization.containerKey] = []; } oPersonalizationSubsection[mPersonalization.containerKey].push(mPersonalization); }.bind(this)); }; /** * Deletes the personalization for a given reference * * @param {string} sReference The reference of the application for which the personalization should be deleted * @param {string} sContainerKey The key of the container for which the personalization should be deleted * @param {string} sItemName The name under which the personalization should be deleted * @returns {Promise} Promise resolving in case the deletion request was successful */ Cache.deletePersonalization = function(sReference, sContainerKey, sItemName) { if (!sReference || !sContainerKey || !sItemName) { return Promise.reject("not all mandatory properties were provided for the storage of the personalization"); } var sUrl = "/sap/bc/lrep/ui2personalization/?reference="; sUrl += sReference + "&containerkey=" + sContainerKey + "&itemname=" + sItemName; return LrepConnector.createConnector().send(sUrl, "DELETE", {}) .then(this._removePersonalizationFromEntries.bind(this, sReference, sContainerKey, sItemName)); }; Cache._removePersonalizationFromEntries = function (sReference, sContainerKey, sItemName) { var aDeletionPromises = []; Object.keys(this._entries[sReference]).forEach(function (sAppVersion) { var oGetAllItemsPromise = this.getPersonalization(sReference, sAppVersion, sContainerKey); var oGetItemPromise = this.getPersonalization(sReference, sAppVersion, sContainerKey, sItemName); var oDeletionPromise = Promise.all([oGetAllItemsPromise, oGetItemPromise]).then(function (aParams) { var aItems = aParams[0]; var oToBeDeletedItem = aParams[1]; var nIndexOfItem = aItems.indexOf(oToBeDeletedItem); aItems.splice(nIndexOfItem, 1); }); aDeletionPromises.push(oDeletionPromise); }.bind(this)); return Promise.all(aDeletionPromises); }; return Cache; }, /* bExport= */true); const express = require("express"); const router = express.Router(); const bcrypt = require("bcrypt"); const pool = require("../db"); // const validInfo = require("../middleware/validInfo"); const jwtGenerator = require("../utils/jwtGenerator"); const authorize = require("../middleware/authorize"); router.post("/api/post/episodes/:id", authorize, (req, res, next) => { const values = [ req.body.episode_title, req.body.episode_audio, req.body.episode_description, req.body.episode_artwork, req.body.season_number, req.body.episode_number, req.body.episode_type, req.body.episode_explicit_content, req.body.episode_contributors, req.body.search_keywords, req.user.id, req.params.id, req.body.audio_duration, req.body.episode_audio_length, req.body.episode_audio_type, req.body.episode_date_created, ]; pool.query( `INSERT INTO episodes(episode_title, episode_audio, episode_description, episode_artwork, season_number, episode_number, episode_type, episode_explicit_content, episode_contributors, search_keywords, user_id, pid, audio_duration, episode_audio_length, episode_audio_type, episode_date_created) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16 )`, values, (q_err, q_res) => { if (q_err) return next(q_err); res.json(q_res.rows); } ); }); router.post("/api/post/new-episode", authorize, (req, res, next) => { const values = [ req.body.episode_title, req.body.episode_audio, req.body.episode_description, req.body.episode_artwork, req.body.season_number, req.body.episode_number, req.body.episode_type, req.body.episode_explicit_content, req.body.episode_contributors, req.body.search_keywords, req.user.id, req.body.pid, req.body.audio_duration, req.body.episode_date_created, ]; pool.query( `INSERT INTO episodes(episode_title, episode_audio, episode_description, episode_artwork, season_number, episode_number, episode_type, episode_explicit_content, episode_contributors, search_keywords, user_id, pid, audio_duration, episode_date_created) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14 )`, values, (q_err, q_res) => { if (q_err) return next(q_err); res.json(q_res.rows); } ); }); router.get("/api/get/episodes", authorize, async (req, res, next) => { const user = await pool.query( `SELECT * FROM users RIGHT JOIN episodes ON users.user_id = episodes.user_id INNER JOIN podcasts ON podcasts.pid = episodes.pid WHERE users.user_id = $1 ORDER BY eid DESC`, [req.user.id] ); res.json(user.rows); }); // `SELECT * FROM users RIGHT JOIN episodes ON users.user_id = episodes.user_id WHERE users.user_id = $1 ORDER BY eid DESC`, router.get("/api/get/episodes/:eid", authorize, (req, res, next) => { const eid = req.params.eid; pool.query( `SELECT * FROM episodes RIGHT JOIN podcasts ON episodes.pid = podcasts.pid WHERE eid = ${eid}`, (q_err, q_res) => { res.json(q_res.rows[0]); } ); }); router.get("/api/get/episodes/public/:eid", (req, res, next) => { const eid = req.params.eid; pool.query( `SELECT * FROM episodes RIGHT JOIN podcasts ON episodes.pid = podcasts.pid WHERE eid = ${eid}`, (q_err, q_res) => { res.json(q_res.rows[0]); } ); }); router.get("/api/get/podcast/:pid/episodes", authorize, (req, res, next) => { const pid = req.params.pid; pool.query( `SELECT * FROM episodes WHERE pid = ${pid} ORDER BY eid DESC`, (q_err, q_res) => { if (q_err) return next(q_err); res.json(q_res.rows); } ); }); router.delete("/api/delete/episodes/:eid", authorize, (req, res, next) => { const eid = req.params.eid; pool.query(`DELETE FROM episodes WHERE eid = ${eid}`, (q_err, q_res) => { res.json(q_res.rows); }); }); router.put("/api/update/episodes/:eid", (req, res, next) => { const eid = req.params.eid; const values = [ req.body.episode_title, req.body.episode_audio, req.body.episode_description, req.body.episode_artwork, req.body.season_number, req.body.episode_number, req.body.episode_type, req.body.episode_explicit_content, req.body.episode_contributors, req.body.search_keywords, eid, ]; pool.query( `UPDATE episodes SET episode_title=$1, episode_audio=$2, episode_description=$3, episode_artwork=$4, season_number=$5, episode_number=$6, episode_type=$7, episode_explicit_content=$8, episode_contributors=$9, search_keywords=$10 WHERE eid = $11`, values, (q_err, q_res) => { res.json(q_res.rows); } ); }); router.patch("/api/update/episodes/:eid/views", async (req, res) => { const eid = req.params.eid; try { pool.query( `UPDATE episodes SET episode_audio_plays = episode_audio_plays + 1 WHERE eid = ${eid}`, (q_err, q_res) => { res.json(q_res.rows); } ); } catch (error) { console.log(error); } }); router.patch("/api/update/episodes/:eid/views/completed", async (req, res) => { const eid = req.params.eid; try { pool.query( `UPDATE episodes SET episode_audio_plays_completed = episode_audio_plays_completed + 1 WHERE eid = ${eid}`, (q_err, q_res) => { res.json(q_res.rows); } ); } catch (error) { console.log(error); } }); module.exports = router; <gh_stars>0 import React, { Component } from "react"; import ResolvedTable from "../components/ResolvedTable"; class ResolvedAudits extends Component { //function that sees scores and if totalscore == 100 then add to table of resolved ///deleted from table of ongoing audits render() { return ( <div className="auditsstaff" > <ResolvedTable /> </div> ); } } export default ResolvedAudits; <filename>project_dict_front_vue2/src/filters/time.js<gh_stars>0 import moment from 'moment' function time (value, format = 'YYYY-MM-DD HH:mm:ss') { const mmt = moment(value); if (mmt.isValid()) { return mmt.format(format) } else { return '-' } } export default time <gh_stars>0 'use strict' const t = require('tap') const test = t.test const FindMyWay = require('../') test('Falling back for node\'s parametric brother', t => { t.plan(3) const findMyWay = FindMyWay({ defaultRoute: (req, res) => { t.fail('Should not be defaultRoute') } }) findMyWay.on('GET', '/:namespace/:type/:id', () => {}) findMyWay.on('GET', '/:namespace/jobs/:name/run', () => {}) t.same( findMyWay.find('GET', '/test_namespace/test_type/test_id').params, { namespace: 'test_namespace', type: 'test_type', id: 'test_id' } ) t.same( findMyWay.find('GET', '/test_namespace/jobss/test_id').params, { namespace: 'test_namespace', type: 'jobss', id: 'test_id' } ) t.same( findMyWay.find('GET', '/test_namespace/jobs/test_id').params, { namespace: 'test_namespace', type: 'jobs', id: 'test_id' } ) }) <filename>components/notice-box/src/index.js<gh_stars>10-100 export { NoticeBox } from './notice-box.js' 'use strict'; const bot = require('./../../index.js'); const log = require('./../../logger.js'); bot.registerCommand('kick', (msg, args) => { if (args.length === 0 || msg.mentions.length === 0 || args[0] !== `<@${msg.mentions[0].id}>`) return `**${msg.author.username}**, I need to know who to kick, tag them after ${msg.prefix}kick.`; if (msg.mentions.length > 1) return `**${msg.author.username}**, I can only kick one person at a time.`; if (msg.mentions[0].id === msg.channel.guild.ownerID) return `**${msg.author.username}**, this person is the owner of the server. No one can kick them.`; if (msg.mentions[0].id === bot.user.id) return `**${msg.author.username}**, bitch please. (seriously though, if you want to kick me, do it manually)`; let rolesOfKicker = msg.channel.guild.roles.filter(r => msg.member.roles.indexOf(r.id) > -1); let rolesOfKicked = msg.channel.guild.roles.filter(r => msg.channel.guild.members.get(msg.mentions[0].id).roles.indexOf(r.id) > -1); let highPositionOfKicker = 0; let highPositionOfKicked = 0; for (let i = 0; i < rolesOfKicker.length; i++) { if (rolesOfKicker[i].position > highPositionOfKicker) { highPositionOfKicker = rolesOfKicker[i].position; } } for (let i = 0; i < rolesOfKicked.length; i++) { if (rolesOfKicked[i].position > highPositionOfKicked) { highPositionOfKicked = rolesOfKicked[i].position; } } if (msg.author.id !== msg.channel.guild.ownerID) { if (highPositionOfKicked >= highPositionOfKicker) return `**${msg.author.username}**, this person is of equal or higher rank than you in the role hierarchy. If your role *should* be able to kick a person of this role, you need to re-order your role list.`; } let botRole = msg.channel.guild.roles.get(msg.channel.guild.members.get(bot.user.id).roles[0]).position; if (highPositionOfKicked >= botRole) return `**${msg.author.username}**, I cannot kick this person. They're of equal or higher rank than me. If you wish for me to be able to kick this person, move my role above theirs.`; bot.kickGuildMember(msg.channel.guild.id, msg.mentions[0].id).catch(error => log.errC(error)); }, { caseInsensitive: true, deleteCommand: true, description: 'kick a member.', fullDescription: 'kicks a member from the server.', usage: '<mention of user>', guildOnly: true, requirements: { permissions: { 'kickMembers': true, } }, cooldown: 3000 }); 'use strict'; // Задание 8 - дополнительное, выполнять не обязательно // Напиши скрипт создания и очистки коллекции элементов. Пользователь вводит количество // элементов в input и нажимает кнопку Создать, после чего рендерится коллекция. // При нажатии на кнопку Очистить, коллекция элементов очищается. // Создай функцию createBoxes(amount), которая принимает 1 параметр amount - число. // Функция создает столько div, сколько указано в amount и добавляет их в div#boxes. // Каждый созданный div: // Имеет случайный rgb цвет фона // Размеры самого первого div - 30px на 30px // Каждый следующий div после первого, должен быть шире и выше предыдущего на 10px // Создай функцию destroyBoxes(), которая очищает div#boxes. /* <div id="controls"> <input type="number" min="0" max="100" step="1" /> <button type="button" data-action="render">Создать</button> <button type="button" data-action="destroy">Очистить</button> </div> */ /* <div id="boxes"></div> */ const input = document.querySelector('input[type="number"]'); const render = document.querySelector('button[data-action="render"]'); const destroy = document.querySelector('button[data-action="destroy"]'); const boxes = document.querySelector('#boxes'); destroy.addEventListener('click', handlerDestroy); render.addEventListener('click', handlerRender); function createBoxes(amount) { let itemDiv = []; for (let i = 0; i < amount; i++) { const currentDiv = document.createElement('div'); currentDiv.innerHTML = i + 1; currentDiv.style.width = (30 + 10 * i)+'px'; currentDiv.style.height = (30 + 10 * i)+'px'; currentDiv.style.backgroundColor = randomColor(); itemDiv.push(currentDiv); } boxes.append(...itemDiv); } function handlerRender() { createBoxes(input.value); input.value = ''; } function handlerDestroy() { boxes.innerHTML = ''; input.value = ''; } function randomColor() { const color = () => Math.floor((Math.random()) * 255 + 1); return `rgb(${color()}, ${color()}, ${color()})` } import { fromIni as fromAwsCredentialsFile, } from '@aws-sdk/credential-provider-ini'; import { IAMClient, CreateAccessKeyCommand, } from '@aws-sdk/client-iam'; import {Octokit} from '@octokit/rest'; import { getToken as getGitHubToken, encryptSecret, } from './lib/gh-utils.js'; export default async function ghaws(passedConfig) { const config = await enrichConfig(passedConfig); const accessKey = await createAwsAccessKey(config); await setGitHubRepoActionsSecrets(accessKey, config); } const enrichConfig = async passedConfig => { const orgaName = passedConfig.orgaName; // TODO default from git from current directory const repoName = passedConfig.repoName; // TODO default from git from current directory const awsAccountName = passedConfig.awsAccountName; // TODO default from serverless.yml file? const config = { orgaName, repoName, awsAccountName, ghaAccessUserName: `${repoName}-gha-access`, // TODO from cf-stack `GhaUser` ghaSecretPrefix: awsAccountName.toUpperCase(), }; return Promise.resolve(config); }; const createAwsAccessKey = async ({awsAccountName, ghaAccessUserName}) => { console.log(`create accesskey for ${awsAccountName} aws account`); const iam = new IAMClient({ credentials: fromAwsCredentialsFile({profile: awsAccountName}), }); const createAccessKeyCmd = new CreateAccessKeyCommand({ UserName: ghaAccessUserName, }); try { const response = await iam.send(createAccessKeyCmd); return response.AccessKey; } catch (error) { throw new Error(`Could not create new aws AccessKey. Caused by:\n${error}`); } }; const setGitHubRepoActionsSecrets = async ({AccessKeyId, SecretAccessKey}, {orgaName, repoName, ghaSecretPrefix}) => { console.log('create/update GitHub secrets'); const octokit = new Octokit({ auth: getGitHubToken(), }); const deployRepoActionsSecrets = async () => { const ghRepo = await fetchGhRepoPublicKey(); const awsAccessKeyId = encryptSecret(AccessKeyId, ghRepo.key); const awsSecretAccessKey = encryptSecret(SecretAccessKey, ghRepo.key); // TODO can be done in parallel await createOrUpdateRepoActionSecret('AWS_ACCESS_KEY_ID', awsAccessKeyId, ghRepo.keyId); await createOrUpdateRepoActionSecret('AWS_SECRET_ACCESS_KEY', awsSecretAccessKey, ghRepo.keyId); }; const fetchGhRepoPublicKey = async () => { const repoPublicKey = await octokit.actions.getRepoPublicKey({ owner: orgaName, repo: repoName, }); return { keyId: repoPublicKey.data.key_id, key: repoPublicKey.data.key, }; }; const createOrUpdateRepoActionSecret = (ghaSecretSuffix, encryptedValue, keyId) => { /* eslint-disable camelcase */ octokit.actions.createOrUpdateRepoSecret({ owner: orgaName, repo: repoName, secret_name: `${ghaSecretPrefix}__${ghaSecretSuffix}`, encrypted_value: encryptedValue, key_id: keyId, }); /* eslint-enable camelcase */ }; await deployRepoActionsSecrets(); }; /** * @author <NAME> <<EMAIL>>, 2016 * @class * @classdesc Grid column Float class class * @extends GridColumn * @requires core/extend.js * @requires controls/GridColumn.js * @param {object} options * @param {int} [options.precision=DEF_PRECISION] */ function GridColumnFloat(options){ options = options || {}; this.m_precision = options.precision || this.DEF_PRECISION; GridColumnFloat.superclass.constructor.call(this,options); } extend(GridColumnFloat,GridColumn); /* Constants */ GridColumnFloat.prototype.DEF_PRECISION = 2; GridColumnFloat.prototype.DEF_SEPAR = " "; /* private members */ /* protected*/ /* public methods */ GridColumnFloat.prototype.formatVal = function(v){ //var n = v; //n = CommonHelper.numberFormat(v, this.m_precision, CommonHelper.getDecimalSeparator(), this.DEF_SEPAR); if (isNaN(v)){ return ""; } else{ return CommonHelper.numberFormat(v, this.m_precision, CommonHelper.getDecimalSeparator(), this.DEF_SEPAR); } } import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M4.21 5.61C6.23 8.2 10 13 10 13v5c0 1.1.9 2 2 2s2-.9 2-2v-5s3.77-4.8 5.79-7.39C20.3 4.95 19.83 4 19 4H5c-.83 0-1.3.95-.79 1.61z" /> , 'FilterAltRounded'); <gh_stars>1-10 var a04418 = [ [ "FloatVec", "a04418.html#a9ae9b86a7c7a14b024516132ac08d58c", null ], [ "FloatVec", "a04418.html#ab2f60b61ac946858427c9a241d835b0e", null ], [ "~FloatVec", "a04418.html#ace4d6df049f0b57f0f20594b11c2e33c", null ], [ "get", "a04418.html#ab267c30cf3e28e8b2d1ff8a0066ec4be", null ], [ "Init", "a04418.html#a7b99a600fb46ce08663a62b0f0d25fcc", null ], [ "operator double *", "a04418.html#ae015e502e570e6bf934f56806178eab9", null ] ];import ApiCaller from './base'; import { CALL_API } from '../constants'; class CallApi extends ApiCaller { constructor(...props) { super(...props); this.type = CALL_API; } call() { const { action, store } = this; const { dispatch } = store; const actionPromises = this._createPromiseChain(); return new Promise((resolve, reject) => { let overall = actionPromises.reduce((prev, curr) => { return prev.then(curr); }, Promise.resolve()); overall.then(resolve).catch(reject); }); } } export default CallApi;<filename>test/mocha-as-promised.js const Describe = (description, callback) => { return new Promise((resolve, reject) => { describe(description, () => { try { callback(); resolve(); } catch (e) { reject(e); } }); }); }; const It = (description, callback) => { return new Promise((resolve, reject) => { it(description, (done) => { try { callback(); done(); resolve(); } catch (e) { reject(e); } }); }); }; module.exports = { Describe, It };export { default as ChatBubble } from './chat_bubble'; export { default as ChatList } from './chat_list'; export { default as ChatSpace } from './chat_space'; export { default as ChatForm } from './chat_form'; export { default as ChatWelcome } from './chat_welcome_screen'; export { default as ChatUserSettings } from './chat_user_settings'; export * from './chat_utils'; "use strict"; var $ = require('jquery'); var Promise = require('es6-promise').Promise; var ESCAPE_MAP = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", "/": "/" }; // escapeHtml sanitizes special characters in text that could be interpreted as // HTML. function escapeHtml(string) { return String(string).replace(/[&<>"'\/]/g, function (c) { return ESCAPE_MAP[c]; }); } // I18N var gettext = (function () { if (typeof global.Gettext === 'function') { var _gettext = new global.Gettext({domain: "annotator"}); return function (msgid) { return _gettext.gettext(msgid); }; } return function (msgid) { return msgid; }; }()); // Returns the absolute position of the mouse relative to the top-left rendered // corner of the page (taking into account padding/margin/border on the body // element as necessary). function mousePosition(event) { var body = global.document.body; var offset = {top: 0, left: 0}; if ($(body).css('position') !== "static") { offset = $(body).offset(); } return { top: event.pageY - offset.top, left: event.pageX - offset.left }; } exports.$ = $; exports.Promise = Promise; exports.gettext = gettext; exports.escapeHtml = escapeHtml; exports.mousePosition = mousePosition; <filename>web/gds-ui/src/components/select/LanguageSelect.js import _ from 'lodash'; import React, { useContext } from 'react'; import NavDropdown from 'react-bootstrap/NavDropdown'; import LanguageContext from "../../contexts/LanguageContext"; const languages = { en: { flag: "🇺🇸", title: "English", }, fr: { flag: "🇫🇷", title: "Française", }, de: { flag: "🇩🇪", title: "Deutsch", }, zh: { flag: "🇨🇳", title: "中文", }, ja: { flag: "🇯🇵", title: "日本語" } } const LanguageSelect = () => { const context = useContext(LanguageContext); const selectLanguage = (lang) => (e) => { e.preventDefault(); context.changeLanguage(lang); return false; } const renderItems = () => { return _.map(languages, (value, key) => { return ( <NavDropdown.Item key={key} href="#" onClick={selectLanguage(key)} > <span className="mr-1">{value.flag}</span> {value.title} </NavDropdown.Item> ); }) } const currentLanguage = () => { return <><span className="mr-1">{languages[context.language].flag}</span> {context.language.toUpperCase()}</> } return ( <NavDropdown title={currentLanguage()} id="select-language-dropdown"> {renderItems()} </NavDropdown> ); }; export default LanguageSelect;import { translate } from '@localize'; import { AppStyles, images, metrics } from '@theme'; import React from 'react'; import { Image, StyleSheet, TouchableOpacity, View } from 'react-native'; import { Text } from 'react-native-paper'; import { useChangeLanguage } from '@hooks'; export const HomePageName = 'Home'; export const PromotionPageName = 'Promotion'; export const MenuPageName = 'Menu'; export const StorePageName = 'Store'; export const BottomBarComponent = ({ state, descriptors, navigation }) => { const routes = { Home: { title: translate('tabHome'), icon: images.icons.tab_home, }, Promotion: { title: translate('tabPromotion'), icon: images.icons.tab_promotion, }, Menu: { title: translate('tabMenu'), icon: images.icons.tab_menu, }, Store: { title: translate('tabStore'), icon: images.icons.tab_store, }, }; const [language] = useChangeLanguage(); const focusedOptions = descriptors[state.routes[state.index].key].options; if (focusedOptions.tabBarVisible === false) { return null; } return ( <View style={styles.barStyle}> {state.routes.map((route, index) => { const isFocused = state.index === index; const onPress = () => { const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true, }); if (!isFocused && !event.defaultPrevented) { navigation.navigate(route.name); } }; const onLongPress = () => { navigation.emit({ type: 'tabLongPress', target: route.key, }); }; const color = isFocused ? AppStyles.colors.accent : AppStyles.colors.text; const fontWeight = isFocused ? 'bold' : 'normal'; return ( <TouchableOpacity activeOpacity={1} accessibilityRole="button" accessibilityStates={isFocused ? ['selected'] : []} onPress={onPress} onLongPress={onLongPress} key={route.key} style={styles.buttonStyle}> {language && routes[route.name]?.icon && ( <Image style={[ styles.iconStyle, { tintColor: color, }, ]} source={routes[route.name]?.icon} /> )} <Text style={[ styles.labelStyle, { color: color, fontWeight: fontWeight, }, ]}> {routes[route.name]?.title} </Text> </TouchableOpacity> ); })} </View> ); }; const styles = StyleSheet.create({ barStyle: { height: metrics.tabBarHeight, padding: 0, backgroundColor: AppStyles.colors.primary, flexDirection: 'row', borderTopColor: AppStyles.colors.accent, borderTopWidth: 1, }, labelStyle: { fontSize: 14, textAlign: 'center', fontFamily: 'Roboto-Regular', margin: 5, lineHeight: 21, textAlignVertical: 'center', }, iconStyle: { height: 28, width: 35, resizeMode: 'center', }, buttonStyle: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); <reponame>laszlolm/decrediton<filename>test/mocks/electronMock.js export default {}; export const remote = { dialog: {}, getCurrentWindow() {} }; import React, { Component } from "react"; import { TouchableHighlight, Image, RefreshControl, StyleSheet, } from "react-native"; import { Content, Text, View } from "native-base"; import { connect } from "react-redux"; import { Colors } from "../../constants/colors"; import { Ranges } from "../../constants/ranges"; import { TextStrings } from "../../constants/textStrings"; import { getStock, showAutoSuggest } from "../../store/actions"; import { formatPercentage, positiveOrNegative, upOrDownSymbol, } from "../../helpers/priceFormat"; // import ListHeader from "../ListHeader"; class List extends Component { onPress = (symbol) => { this.props.getStock(symbol, Ranges.ONE_MONTH); // this.props.showAutoSuggest(false); this.props.navigation.navigate("Stock", symbol); }; render() { return ( <View style={{ flex: 1 }}> {/* <ListHeader latestUpdate={this.props.latestUpdate} title={this.props.headerTitle} /> */} <Content refreshControl={ <RefreshControl colors={[Colors.TEXT_NORMAL]} onRefresh={this.props.onRefresh} progressBackgroundColor={Colors.BLUE3} refreshing={this.props.loading} /> } style={styles.list} > {this.props.list.length === 0 && ( <Text style={styles.noData}> {this.props.noListData || TextStrings.NO_LIST_DATA} </Text> )} {this.props.list.map((stock, index) => { const logo = `https://storage.googleapis.com/iex/api/logos/${stock.symbol}.png`; return ( <TouchableHighlight background={Colors.BLUE2} key={index} style={styles.button} onPress={() => this.onPress(stock.symbol)} > <View style={styles.rowContainer}> <Image source={{ uri: logo }} style={styles.image} /> <View style={styles.textContainer}> <View style={styles.textInnerContainer}> <Text>{stock.symbol}</Text> <Text>{stock.latestPrice} USD</Text> </View> <View style={styles.textInnerContainer}> <Text ellipsizeMode="tail" numberOfLines={1} style={styles.companyName} > {stock.companyName} </Text> <Text> <Text style={[ styles.stockChange, positiveOrNegative(stock.change), ]} > {stock.change} </Text> <Text style={[ styles.stockChange, positiveOrNegative(stock.change), ]} > {" "} ({formatPercentage(stock.changePercent)} %) {upOrDownSymbol(stock.changePercent)} </Text> </Text> </View> </View> </View> </TouchableHighlight> ); })} </Content> </View> ); } } const styles = StyleSheet.create({ button: { backgroundColor: "transparent", elevation: 0, flex: 1, flexDirection: "column", paddingHorizontal: 16, paddingVertical: 12, width: "100%", }, rowContainer: { alignItems: "center", flexDirection: "row", width: "100%", }, textContainer: { flexGrow: 1, }, textInnerContainer: { justifyContent: "space-between", flexDirection: "row", flexGrow: 1, }, image: { borderRadius: 3, height: 28, marginRight: 16, width: 28, }, companyName: { color: Colors.TEXT_DARK, flex: 1, fontSize: 13, paddingRight: 8, }, stockChange: { fontSize: 13, }, noData: { color: Colors.TEXT_DARK, fontSize: 13, padding: 20, textAlign: "center", }, }); const mapStateToProps = (state) => ({ symbol: state.symbol, }); const mapDispatchToProps = { getStock, showAutoSuggest, }; export default connect(mapStateToProps, mapDispatchToProps)(List); const Workstate = { ADD: 0, EDIT: 1, SEARCH: 2, SELECTED: 3, VIEW_DETAILS: 4, VIEW_LIST: 5, }; const WorkstateAsString = { 0: "Создание", 1: "Редактирование", 2: "Поиск", 3: "Выделен элемент списка", 4: "Просмотр объекта", 5: "Просмотр списка", }; export {Workstate, WorkstateAsString};<gh_stars>0 import React, { Component } from "react"; import { Text, View, ActivityIndicator, FlatList, RefreshControl } from "react-native"; import firebase from "react-native-firebase"; export default class CollectionLoader extends Component { constructor(props) { super(props); this.state = { items: [], loading: true, refreshing: false }; } componentDidMount() { this.get(); } get() { let collection = this.props.collection; firebase .firestore() .collection(collection) .get() .then(snap => { console.log(snap); this.setState({ loading: false, refreshing: false, items: snap._docs.map(d => { return d._data; }) }); }); } refresh() { this.setState({ refreshing: true }, () => { this.get(); }); } render() { return this.state.loading ? ( this.props.loading ? ( this.props.loading ) : ( <View> <ActivityIndicator /> </View> ) ) : ( <FlatList ListHeaderComponent={this.props.header || null} ListFooterComponent={<View style={{ height: 8 }} />} style={this.props.style} refreshControl={ <RefreshControl onRefresh={() => { this.refresh(); }} refreshing={this.state.refreshing} /> } keyExtractor={i => { return i.id; }} data={this.state.items} renderItem={this.props.renderItem} /> ); } } <reponame>datyayu/voxfeed-test export * from "./CirclesAnimation"; class Tray { constructor(prods) { this.products = prods || []; } add(prod) { this.products.push(prod); } calculate(){ let sum = 0; /** * Calculate the sum of all products * in the tray and pass it back. Do * not change the code given */ return sum; } } import * as publicUiFunctions from './ui'; import * as publicSheetFunctions from './sheets'; // Expose public functions by attaching to `global` global.onOpen = publicUiFunctions.onOpen; global.openEditorSidebar = publicUiFunctions.openEditorSidebar; global.getCurrentPosition = publicSheetFunctions.getCurrentPosition; global.updateRow = publicSheetFunctions.updateRow; global.moveCursor = publicSheetFunctions.moveCursor; global.getSheetRecords = publicSheetFunctions.getSheetRecords; <filename>api/models/Category.js const mongoose = require("mongoose"); const CategorySchema = new mongoose.Schema( { title: { type: String, required: true, unique: true }, img: { type: String, required: true }, cat: { type: String, required: true }, }, { timestamps: true }, ); module.exports = mongoose.model("Category", CategorySchema);window.onscroll = toogleScrollButton; /* Footer Date */ setInterval(function () { var data = new Date(); document.querySelector("#hora").innerHTML = addZero(data.getDate()) + "/" + addZero(data.getMonth() + 1) + "/" + addZero(data.getFullYear()) + "\t" + addZero(data.getHours()) + ":" + addZero(data.getMinutes()) + ":" + addZero(data.getSeconds()); /* Adds 0 (zero) if < 10 */ function addZero(number) { if (number < 10) { return "0" + number; } return number.toString(); } }, 1000); /* Scroll Top */ function toogleScrollButton() { if ( document.body.scrollTop > window.innerHeight / 2 || document.documentElement.scrollTop > window.innerHeight / 2 ) { showScrollButton(); } else { hideScrollButton(); } } function ScrollToTop() { document.scrollTop = 0; document.documentElement.scrollTop = 0; } function showScrollButton() { document.getElementById("scrollTop").style.opacity = 1; } function hideScrollButton() { document.getElementById("scrollTop").style.opacity = 0; } <filename>app/lib/collections/members.js<gh_stars>1-10 Members = new Mongo.Collection('members'); var Schemas = {}; Schemas.Member = new SimpleSchema({ logId: { type: String, optional: true }, userId: { type: String, optional: true }, lastSeenAt: { type: Date, optional: true }, createdAt: { type: Date } }); Members.attachSchema(Schemas.Member); if (Meteor.isServer) { Members.allow({ insert: function (userId, doc) { return userId === doc.userId; }, update: function (userId, doc, fieldNames, modifier) { return userId === doc.userId; }, remove: function (userId, doc) { return userId === doc.userId; } }); } <gh_stars>1-10 import Controller from '@ember/controller'; export default class DocsUsageController extends Controller { uncontrolledMode = ` <AriaTabs @defaultIndex={{1}} @onSelect={{action onSelect}} as |at|> <at.tabList as |tl|> <tl.tab>Title 1</tl.tab> <tl.tab>Title 2</tl.tab> </at.tabList> <at.tabPanel></at.tabPanel> <at.tabPanel></at.tabPanel> </AriaTabs> `; controlledMode = ` <AriaTabs @selectedIndex={{this.tabIndex}} @onSelect={{action (mut this.tabIndex)}} as |at|> <at.tabList as |tl|> <tl.tab>Title 1</tl.tab> <tl.tab>Title 2</tl.tab> </at.tabList> <at.tabPanel></at.tabPanel> <at.tabPanel></at.tabPanel> </AriaTabs> `; } define(function(require) { 'use strict'; var Backbone = require('lib/backbone'), selectCollections = require('collections/selects'), optionCollections = require('collections/options'), SelectView = require('views/selectv'), tree = require('lib/tree'), CONFIG = require('util/config'), cache = require('util/cache'), $ = require('lib/jquery'), send = require('util/send'), FilterView; FilterView = Backbone.View.extend({ el: '.JfiltersContainer', initialize: function() { this.listenTo(selectCollections, 'add', this.addOne); Backbone.on('bindTree', this.initTree, this); Backbone.on('fillGlobalObj', this.fillGlobalObj, this); this.render(); }, render: function() { this.initTree(); this.initConstrutor(CONFIG.select); }, addAll: function() { }, addOne: function(item) { var selectview = new SelectView({ model: item }); this.$el.append(selectview.render().el); }, initConstrutor: function(data) { var len = data.length, i = 0; for (; i < len; i++) { selectCollections.add(data[i]); }; }, initTree: function(cfg) { var currentConfig, setting; if (!cfg) { cfg = {}; } currentConfig = { foldnUrl: cfg.foldnUrl || CONFIG.foldnUrl, oprUrl: cfg.oprUrl || CONFIG.oprUrl, container: cfg.container || '#dimensionTree', baseNode: cfg.baseNode || { name: "指标树", open: false, isParent: true, chkDisabled: true, level: 0 } }; setting = { async: { enable: true, url: currentConfig.foldnUrl, contentType: 'application/json', type: 'get', autoParam: ["id"] }, data: { simpleData: { enable: true } }, callback: { onClick: this.unionFilters.bind(this) } }; $.fn.zTree.init($(currentConfig.container), setting, currentConfig.baseNode); }, unionFilters: function(e, treeId, treeNode) { if (treeNode.level === 0) { return; } this.fillGlobalObj({ treeNode: treeNode, step: 1 }); }, fillGlobalObj: function(cfg) { var sendData; if (cfg.step === 1) { sendData = this.mosaicData(cfg.treeNode); } else { var currentNode = { name: cfg.name, fid: cfg.fid, level: cfg.step } var configData = optionCollections.getSelectedExcludByLevel(cfg.step); configData.push(currentNode); sendData = JSON.stringify({ filters: configData, step: cfg.step }); } send({ url: CONFIG.oprUrl, data: sendData, success: function(data) { Backbone.trigger('reFillOption', data.filters); Backbone.trigger('fillExplain', data.explain); Backbone.trigger('fillTable', data.table); cache.explain = data.explain; cache.table = data.table; Backbone.trigger('controlDisplay', { isHide: true }); } }); }, mosaicData: function(node) { var configData = optionCollections.getSelectedExcludByLevel(1), currentNode = { name: node.name, level: 1, fid: node.id }; configData.push(currentNode); return JSON.stringify({ filters: configData, step: 1 }); } }); return FilterView; })<reponame>MattMattC/Website import React from 'react'; import { Link as LinkGatsby } from 'gatsby'; import { Box, Text, Heading, useColorMode, Link, Icon, Flex, } from '@chakra-ui/core'; import BadgeByCat from './BadgeByCat'; const Article = props => { const { node } = props; const { colorMode } = useColorMode(); const colorText = { light: 'teal.800', dark: 'gray.100' }; const colorTextSmall = { light: 'gray.500', dark: 'gray.300' }; const colorDescription = { light: 'gray.600', dark: 'gray.300' }; const title = node.frontmatter.title || node.fields.slug; var options = { year: 'numeric', month: 'short', day: 'numeric' }; const date = new Intl.DateTimeFormat('fr-FR', options).format( new Date(node.frontmatter.date) ); return ( <Box key={node.fields.slug} pt={2}> <header> <Flex justifyContent="space-between"> <Flex alignItems="center"> <Icon name="calendar" size="14px" mr="2" color={colorTextSmall[colorMode]} /> <Text as="small" fontSize="xs" color={colorTextSmall[colorMode]} > {date} </Text> </Flex> <Flex alignItems="center"> <Icon name="time" size="14px" mr="2" color={colorTextSmall[colorMode]} /> <Text as="small" fontSize="xs" color={colorTextSmall[colorMode]} > {node.frontmatter.time_to_read} min </Text> </Flex> </Flex> <Heading as="h3" fontSize="2xl" color={colorText[colorMode]}> <Link as={LinkGatsby} to={'/blog' + node.fields.slug}> {title} </Link> </Heading> </header> <Flex> {node.frontmatter.categories ? node.frontmatter.categories.map((cat, index) => ( <BadgeByCat key={index} cat={cat} /> )) : null} </Flex> <Text mt="2" fontSize="sm" color={colorDescription[colorMode]} dangerouslySetInnerHTML={{ __html: node.frontmatter.description || node.excerpt, }} /> <Flex justifyContent="right"> <Text fontSize="xs"> <Link color={colorText[colorMode]} as={LinkGatsby} to={'/blog' + node.fields.slug} > Lire l'article </Link> </Text> </Flex> </Box> ); }; Article.propTypes = {}; export default Article; import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { logout } from '../store'; import SelectCategory from './SelectCategory'; import HomeIcon from '@material-ui/icons/Home'; import ShoppingCartIcon from '@material-ui/icons/ShoppingCart'; import AccountBoxIcon from '@material-ui/icons/AccountBox'; import ExitToAppIcon from '@material-ui/icons/ExitToApp'; import StorefrontIcon from '@material-ui/icons/Storefront'; const Navbar = ({ handleClick, isLoggedIn }) => { return ( <div className="header"> <nav> <Link className="logo-navbar" to="/home"> Grizzly Winter Gear </Link> {isLoggedIn ? ( <div className="navBar"> {/* The navbar will show these links after you log in */} <Link to="/home"> <HomeIcon fontSize="small" /> Home </Link> <SelectCategory /> <Link to="/account"> <AccountBoxIcon fontSize="small" /> Account </Link> <Link to="/viewcart"> <ShoppingCartIcon fontSize="small" /> View Cart </Link> <a href="#" onClick={handleClick}> <ExitToAppIcon fontSize="small" /> Logout </a> </div> ) : ( <div className="navBar"> {/* The navbar will show these links before you log in */} <Link to="/login">Login</Link> <Link to="/signup">Sign Up</Link> <SelectCategory /> <Link to="/viewcart"> <ShoppingCartIcon fontSize="small" /> View Cart </Link> </div> )} </nav> <hr /> </div> ); }; /** * CONTAINER */ const mapState = (state) => { return { isLoggedIn: !!state.auth.id, }; }; const mapDispatch = (dispatch) => { return { handleClick() { dispatch(logout()); }, }; }; export default connect(mapState, mapDispatch)(Navbar); const net = require('net'); const BigInt = require('big-integer'); const version = 'SSH-2.0-JH_1.0\r\n'; const MIN = 1024; const PREFERED = 1024; const MAX = 8192; const config = { kex: "diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1", server_host_key: "ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521", cipher_s2c: "aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc", cipher_c2s: "aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc", mac_s2c: "hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96", mac_c2s: "hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96", compression_s2c: "none", compression_c2s: "none", lang_s2c: "", lang_c2s: "", 20: "SSH_MSG_KEXINIT", 21: "SSH_MSG_NEWKEYS", 30: "SSH_MSG_KEXDH_INIT", 31: "SSH_MSG_KEX_DH_GEX_GROUP", 32: "SSH_MSG_KEX_DH_GEX_INIT", 33: "SSH_MSG_KEX_DH_GEX_REPLY", 34: "SSH_MSG_KEX_DH_GEX_REQUEST" } const SSH_MSG_DISCONNECT = 1; const SSH_MSG_IGNORE = 2; const SSH_MSG_UNIMPLEMENTED = 3; const SSH_MSG_DEBUG = 4; const SSH_MSG_SERVICE_REQUEST = 5; const SSH_MSG_SERVICE_ACCEPT = 6; const SSH_MSG_KEXINIT = 20; const SSH_MSG_NEWKEYS = 21; const SSH_MSG_KEXDH_INIT = 30; const SSH_MSG_KEXDH_REPLY = 31; const SSH_MSG_KEX_DH_GEX_GROUP = 31; const SSH_MSG_KEX_DH_GEX_INIT = 32; const SSH_MSG_KEX_DH_GEX_REPLY = 33; const SSH_MSG_KEX_DH_GEX_REQUEST = 34; const SSH_MSG_GLOBAL_REQUEST = 80; const SSH_MSG_REQUEST_SUCCESS = 81; const SSH_MSG_REQUEST_FAILURE = 82; const SSH_MSG_CHANNEL_OPEN = 90; const SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91; const SSH_MSG_CHANNEL_OPEN_FAILURE = 92; const SSH_MSG_CHANNEL_WINDOW_ADJUST = 93; const SSH_MSG_CHANNEL_DATA = 94; const SSH_MSG_CHANNEL_EXTENDED_DATA = 95; const SSH_MSG_CHANNEL_EOF = 96; const SSH_MSG_CHANNEL_CLOSE = 97; const SSH_MSG_CHANNEL_REQUEST = 98; const SSH_MSG_CHANNEL_SUCCESS = 99; const SSH_MSG_CHANNEL_FAILURE = 100; const STEP = { VERSIONEXCHANGE: "VX", KEXINIT: "KI" }; var status = [STEP.VERSIONEXCHANGE]; var client = new net.Socket(); client.connect(22, '172.16.17.32'); client.on('data', function(data) { if (status[0] === STEP.VERSIONEXCHANGE) { printStatus(status); // exchange version console.log('Received V_S: ' + data); var packet = version; console.log('Sent C_S: ' + packet); client.write(packet, function() { status[0] = STEP.KEXINIT; }); } else if (status[0] === STEP.KEXINIT) { var msgCode = data.readUInt8(4 + 1); status[1] = msgCode; printStatus(status); if (status[1] === SSH_MSG_KEXINIT) { console.log('Received I_C: ' + data.slice(4 + 1 + 1 + 16).toString('ascii')); var payload = Buffer.alloc(1); payload.writeUInt8(SSH_MSG_KEXINIT); var cookie = Buffer.from('E943B8EAD89BC6BD6861A54CFD333DB0', 'hex'); payload = Buffer.concat([payload, cookie], payload.length + cookie.length); const kex = Buffer.from(config.kex); const kexLen = Buffer.alloc(4); kexLen.writeUInt32BE(config.kex.length); payload = Buffer.concat([payload, kexLen], 4 + payload.length); payload = Buffer.concat([payload, kex], kex.length + payload.length); const server_host_key = Buffer.from(config.server_host_key); const server_host_keyLen = Buffer.alloc(4); server_host_keyLen.writeUInt32BE(config.server_host_key.length); payload = Buffer.concat([payload, server_host_keyLen], 4 + payload.length); payload = Buffer.concat([payload, server_host_key], server_host_key.length + payload.length); const cipher_c2s = Buffer.from(config.cipher_c2s); const cipher_c2sLen = Buffer.alloc(4); cipher_c2sLen.writeUInt32BE(config.cipher_c2s.length); payload = Buffer.concat([payload, cipher_c2sLen], 4 + payload.length); payload = Buffer.concat([payload, cipher_c2s], cipher_c2s.length + payload.length); const cipher_s2c = Buffer.from(config.cipher_s2c); const cipher_s2cLen = Buffer.alloc(4); cipher_s2cLen.writeUInt32BE(config.cipher_s2c.length); payload = Buffer.concat([payload, cipher_s2cLen], 4 + payload.length); payload = Buffer.concat([payload, cipher_s2c], cipher_s2c.length + payload.length); const mac_c2s = Buffer.from(config.mac_c2s); const mac_c2sLen = Buffer.alloc(4); mac_c2sLen.writeUInt32BE(config.mac_c2s.length); payload = Buffer.concat([payload, mac_c2sLen], 4 + payload.length); payload = Buffer.concat([payload, mac_c2s], mac_c2s.length + payload.length); const mac_s2c = Buffer.from(config.mac_s2c); const mac_s2cLen = Buffer.alloc(4); mac_s2cLen.writeUInt32BE(config.mac_s2c.length); payload = Buffer.concat([payload, mac_s2cLen], 4 + payload.length); payload = Buffer.concat([payload, mac_s2c], mac_s2c.length + payload.length); const compression_c2s = Buffer.from(config.compression_c2s); const compression_c2sLen = Buffer.alloc(4); compression_c2sLen.writeUInt32BE(config.compression_c2s.length); payload = Buffer.concat([payload, compression_c2sLen], 4 + payload.length); payload = Buffer.concat([payload, compression_c2s], compression_c2s.length + payload.length); const compression_s2c = Buffer.from(config.compression_s2c); const compression_s2cLen = Buffer.alloc(4); compression_s2cLen.writeUInt32BE(config.compression_s2c.length); payload = Buffer.concat([payload, compression_s2cLen], 4 + payload.length); payload = Buffer.concat([payload, compression_s2c], compression_s2c.length + payload.length); const lang_c2s = Buffer.from(config.lang_c2s); const lang_c2sLen = Buffer.alloc(4); lang_c2sLen.writeUInt32BE(config.lang_c2s.length); payload = Buffer.concat([payload, lang_c2sLen], 4 + payload.length); payload = Buffer.concat([payload, lang_c2s], lang_c2s.length + payload.length); const lang_s2c = Buffer.from(config.lang_s2c); const lang_s2cLen = Buffer.alloc(4); lang_s2cLen.writeUInt32BE(config.lang_s2c.length); payload = Buffer.concat([payload, lang_s2cLen], 4 + payload.length); payload = Buffer.concat([payload, lang_s2c], lang_s2c.length + payload.length); printLiner(); console.log("Sent I_S: " + payload.toString('ascii')); var temp = Buffer.alloc(1); temp.writeUInt8(0); payload = Buffer.concat([payload, temp], temp.length + payload.length); var temp = Buffer.alloc(4); temp.writeUInt32BE(0); payload = Buffer.concat([payload, temp], temp.length + payload.length); var padding = getPadding(payload.length + 5, 8); var pad = Buffer.alloc(padding); pad.fill(0); var packet = Buffer.alloc(5); packet.writeUInt32BE(payload.length + padding + 1); packet.writeUInt8(padding, 4); packet = Buffer.concat([packet, payload], packet.length + payload.length); packet = Buffer.concat([packet, pad], packet.length + pad.length); client.write(packet, function() { printLiner(); console.log("Guessing:"); console.log("kex = diffie-hellman-group-exchange-sha256"); console.log("server_host_key = ssh-rsa"); console.log("encryption = aes128-ctr"); console.log("mac = hmac-sha1"); console.log("compression = none"); var payload = Buffer.alloc(1); payload.writeUInt8(SSH_MSG_KEX_DH_GEX_REQUEST); var min = Buffer.alloc(4); min.writeUInt32BE(MIN); var n = Buffer.alloc(4); n.writeUInt32BE(PREFERED); var max = Buffer.alloc(4); max.writeUInt32BE(MAX); payload = Buffer.concat([payload, min, n, max], payload.length + min.length + n.length + max.length); printLiner(); console.log("Size:"); console.log("min = " + MIN); console.log("prefered = " + PREFERED); console.log("max = " + MAX); var padding = getPadding(payload.length + 5, 8); var pad = Buffer.alloc(padding); pad.fill(0); var packet = Buffer.alloc(5); packet.writeUInt32BE(payload.length + padding + 1); packet.writeUInt8(padding, 4); packet = Buffer.concat([packet, payload], packet.length + payload.length); packet = Buffer.concat([packet, pad], packet.length + pad.length); client.write(packet); }); } else if (status[1] === SSH_MSG_KEX_DH_GEX_GROUP) { var packetLength = data.readUInt32BE(); var padding = data.readUInt8(4); var payloadLength = packetLength - padding - 1; var pLen = data.readUInt32BE(4 + 1 + 1); var p = data.slice(4 + 1 + 1 + 4, 4 + 1 + 1 + 4 + pLen).toString('hex'); console.log("p = " + p); p = BigInt(p, 16); var gLen = data.readUInt32BE(4 + 1 + 1 + 4 + pLen); var g = data.slice(4 + 1 + 1 + 4 + pLen, 4 + 1 + 1 + 4 + pLen + gLen).toString('hex'); console.log("g = " + g); g = BigInt(g, 16); g = g.isZero() ? BigInt('2', 16) : g; var x = BigInt.randBetween(1, (p.minus(1)).divide(2)); var e = g.modPow(x, p); console.log("x = " + x.toString(16)); console.log("e = " + e.toString(16)); var payload = Buffer.alloc(1); payload.writeUInt8(SSH_MSG_KEX_DH_GEX_INIT); e = e.toString(16); e = Buffer.from(e, 'hex'); const eLen = Buffer.alloc(4); eLen.writeUInt32BE(e.length); payload = Buffer.concat([payload, eLen], 4 + payload.length); payload = Buffer.concat([payload, e], payload.length + e.length); var padding = getPadding(payload.length + 5, 8); var pad = Buffer.alloc(padding); pad.fill(0); var packet = Buffer.alloc(5); packet.writeUInt32BE(payload.length + padding + 1); packet.writeUInt8(padding, 4); packet = Buffer.concat([packet, payload], packet.length + payload.length); packet = Buffer.concat([packet, pad], packet.length + pad.length); client.write(packet); } else if (status[1] === SSH_MSG_KEX_DH_GEX_REPLY) { var packetLength = data.readUInt32BE(); var padding = data.readUInt8(4); var payloadLength = packetLength - padding - 1; var K_SLen = data.readUInt32BE(4 + 1 + 1); var K_S = data.slice(4 + 1 + 1 + 4, 4 + 1 + 1 + 4 + K_SLen).toString('hex'); if (!check(K_S)) { client.close(); } var fLen = data.readUInt32BE(4 + 1 + 1 + 4 + K_SLen); var f = data.slice(4 + 1 + 1 + 4 + K_SLen + 4, 4 + 1 + 1 + 4 + K_SLen + 4 + fLen).toString('hex'); f = BigInt(f, 16); var sigLen = data.readUInt32BE(4 + 1 + 1 + 4 + K_SLen + 4 + fLen); var sig = data.slice(4 + 1 + 1 + 4 + K_SLen + 4 + fLen + 4, 4 + 1 + 1 + 4 + K_SLen + 4 + fLen + 4 + sigLen).toString('hex'); // calculate K and H var K; var H; if (verify(sig, H)) { console.log("Verified!"); var payload = Buffer.alloc(1); payload.writeUInt8(SSH_MSG_NEWKEYS); console.log("Sent: SSH_MSG_NEWKEYS"); var padding = getPadding(payload.length + 5, 8); var pad = Buffer.alloc(padding); pad.fill(0); var packet = Buffer.alloc(5); packet.writeUInt32BE(payload.length + padding + 1); packet.writeUInt8(padding, 4); packet = Buffer.concat([packet, payload], packet.length + payload.length); packet = Buffer.concat([packet, pad], packet.length + pad.length); client.write(packet, function() { // done! drop connection console.log("Done! Drop Connection"); client.end(); }); } } } }); client.on('close', function() { console.log('Connection closed'); }); function getPadding(length, blockSize) { var cnt = length / blockSize; cnt = Math.ceil(cnt); var padding = cnt * blockSize - length; padding = padding < 4 ? 4 : padding; if (length + padding < 16) { padding = 16 - length; } return padding; } function printStatus(status) { var str; if (status[0] === STEP.VERSIONEXCHANGE) { str = "Exchange Version"; } else { str = "Key Exchange"; } if (typeof status[1] !== 'undefined') { str += " " + config[status[1]]; } printLiner(); console.log(str); printLiner(); } function printLiner() { console.log('================================================================================'); } function check(K_S) { return true; } function verify(sig, H) { return true; } module.exports = { before: { options: { force: true }, src: [ '<%= paths.dist.default %>/**/*' ] }, after: { options: { force: true }, src: [ '<%= paths.dist.javascripts %>/nip.to-app.loader.min.js', // inlined '<%= paths.dist.default %>/**/*.tmp', '<%= paths.dist.default %>/**/*.inline.*' ] } }; <reponame>phat471996/gantt-chart<gh_stars>1-10 'use strict'; describe('test the Gantt Chart', function() { var gantt; beforeEach(function() { var container = document.createElement('div'), body = document.getElementsByTagName('body')[0]; container.setAttribute('id', 'gantt_chart'); body.appendChild(container); gantt = ganttChart(); }); afterEach(function() { d3.selectAll('svg').remove(); }); it('should check defaults values', function() { var margin = {top: 20, right: 15, bottom: 20, left: 20}, translate = 'translate(' + margin.left + ',' + margin.top + ')'; expect(gantt.autoresize()).toBe(true); expect(gantt.enableDrag()).toBe(true); expect(gantt.enableItemResize()).toBe(true); expect(gantt.enableTooltip()).toBe(true); expect(gantt.enableZoom()).toBe(true); expect(gantt.chart()).not.toBe(undefined); expect(gantt.items().length).toBe(0); expect(gantt.lanes().length).toBe(0); expect(gantt.margin()).toEqual(margin); expect(d3.select('svg g.main').attr('transform')).toEqual(translate); expect(gantt.showLaneLabel()).toBe(true); expect(gantt.showXGrid()).toBe(true); expect(gantt.showYGrid()).toBe(true); expect(gantt.size()).toEqual(getSize()); expect(gantt.sublanes()).toBe(1); expect(gantt.svg()).not.toBe(undefined); expect(gantt.renderTo()).toEqual('#gantt_chart'); expect(typeof d3.select(window).on('resize')).toBe('function'); expect(typeof gantt.xAxis()).toEqual('function'); expect(typeof gantt.xScale()).toEqual('function'); expect(typeof gantt.yAxis()).toEqual('function'); expect(typeof gantt.yScale()).toEqual('function'); expect(typeof gantt.zoom()).toEqual('function'); }); it('should add item', function() { var xDomain = gantt.xScale().domain(), yDomain = gantt.yScale().domain(); gantt.addItems(testData().getItem()); expect(gantt.items().length).toBe(1); expect(getRects().length).toBe(1); expect(gantt.lanes().length).toBe(3); expect(gantt.xScale().domain()).not.toEqual(xDomain); expect(gantt.yScale().domain()).not.toEqual(yDomain); expect(gantt.zoom().x()).toEqual(gantt.xScale()); }); it('should add items', function() { var xDomain = gantt.xScale().domain(), yDomain = gantt.yScale().domain(); gantt.addItems(testData().getItems()); expect(gantt.items().length).toBe(3); expect(getRects().length).toBe(3); expect(gantt.lanes().length).toBe(3); expect(gantt.xScale().domain()).not.toEqual(xDomain); expect(gantt.yScale().domain()).not.toEqual(yDomain); expect(gantt.zoom().x()).toEqual(gantt.xScale()); }); it('should throw error when incorrect items added', function() { function addIncorrectItems() { gantt.addItems(25); } expect(addIncorrectItems).toThrow(new TypeError('Expected object or array. Got: [object Number]')); }); it('should set autoresize', function() { gantt.autoresize(false); expect(gantt.autoresize()).toBe(false); expect(d3.select(window).on('resize')).toBe(undefined); gantt.autoresize(true); expect(gantt.autoresize()).toBe(true); expect(d3.select(window).on('resize')).not.toBe(undefined); }); it('should enable/disable drag and drop', function() { gantt.enableDrag(false); expect(gantt.enableDrag()).toBe(false); gantt.enableDrag(true); expect(gantt.enableZoom()).toBe(true); }); it('should enable/disable items resize', function() { gantt.enableItemResize(false); expect(gantt.enableItemResize()).toBe(false); gantt.enableItemResize(true); expect(gantt.enableItemResize()).toBe(true); }); it('should disable/enable tooltip', function() { gantt.items(testData().getItems()); gantt.enableTooltip(false); expect(gantt.enableTooltip()).toBe(false); expect(getRects()[0].__onclick).toBe(undefined); gantt.enableTooltip(true); expect(gantt.enableTooltip()).toBe(true); expect(getRects()[0].__onclick).not.toBe(undefined); }); it('should enable/disable zoom', function() { gantt.enableZoom(false); expect(gantt.enableZoom()).toBe(false); expect(gantt.zoom().on("zoom")).toBe(undefined); gantt.enableZoom(true); expect(gantt.enableZoom()).toBe(true); expect(gantt.zoom().on("zoom")).not.toBe(undefined); }); it('should get chart', function() { expect(gantt.chart()).toEqual(getChart()); }); it('should set items', function() { gantt.addItems(testData().getItems()); var xDomain = gantt.xScale().domain(), yDomain = gantt.yScale().domain(); gantt.items([testData().getItem()]); expect(gantt.items().length).toBe(1); expect(getRects().length).toBe(1); expect(gantt.lanes().length).toBe(3); expect(gantt.xScale().domain()).not.toEqual(xDomain); expect(gantt.zoom().x()).toEqual(gantt.xScale()); }); it('should throw error of incorrect items set', function() { function addIncorrectItems() { gantt.items(25); } expect(addIncorrectItems).toThrow(new TypeError('Expected array. Got: [object Number]')); }); it('should set new lanes', function() { var lanes = ['1', '2']; gantt.lanes(lanes); expect(gantt.lanes()).toEqual(lanes); expect(gantt.lanes().length).toBe(2); gantt.items(testData().getItems()); expect(gantt.lanes().length).toBe(3); }); it('should throw error of incorrect items type', function() { function addIncorrectLanes() { gantt.lanes(25); } expect(addIncorrectLanes).toThrow(new TypeError('Expected array. Got: [object Number]')); }); it('should set margin', function() { var margin = {top: 0, right: 1, bottom: 2, left: 3}, translate = 'translate(' + margin.left + ',' + margin.top + ')'; gantt.margin(margin); expect(gantt.margin()).toEqual(margin); expect(getChart().attr('transform')).toEqual(translate); expect(+getChart().attr('width')).toEqual(getSize()[0] - margin.left - margin.right); expect(+getChart().attr('height')).toEqual(getSize()[1] - margin.top - margin.bottom); gantt.margin({bottom: 20}); expect(gantt.margin().bottom).toEqual(20); }); it('should throw error of incorrect margin', function() { var msg = "'Top' margin value is incorrect. All values should be numbers"; function addIncorrectMargin() { gantt.margin({top: 'azaza'}); } expect(addIncorrectMargin).toThrow(new TypeError(msg)); }) it('should hide/show lane labes', function() { function getLaneLabels() { return d3.select('svg g.laneLabels').selectAll('text')[0]; } gantt.lanes([1, 2]); gantt.showLaneLabel(false); expect(gantt.showLaneLabel()).toBe(false); expect(getLaneLabels().length).toBe(0); gantt.showLaneLabel(true); expect(gantt.showLaneLabel()).toBe(true); expect(getLaneLabels().length).toBe(2); }); it('should hide/show the X grid', function() { function getAxisLine() { return d3.select('svg g.main.axis.date').selectAll('line')[0][0]; } gantt.items(testData().getItems()); gantt.showXGrid(false); expect(gantt.showXGrid()).toBe(false); expect(gantt.xAxis().tickSize()).toBe(-6); expect(getAxisLine().y2.baseVal.value).toBe(-6); gantt.showXGrid(true); expect(gantt.showXGrid()).toBe(true); expect(gantt.xAxis().tickSize()).toBe(-gantt.size()[1]+gantt.margin().top+gantt.margin().bottom); expect(getAxisLine().y2.baseVal.value).toBe(-gantt.size()[1]+gantt.margin().top+gantt.margin().bottom); }); it('should hide/show the Y grid', function() { function getAxisLine() { return d3.select('svg g.main.axis.lane').selectAll('line')[0][0]; } gantt.items(testData().getItems()); gantt.showYGrid(false); expect(gantt.showYGrid()).toBe(false); expect(gantt.yAxis().tickSize()).toBe(-6); expect(getAxisLine().x2.baseVal.value).toBe(6); gantt.showYGrid(true); expect(gantt.showYGrid()).toBe(true); expect(gantt.yAxis().tickSize()).toBe(-gantt.size()[0]+gantt.margin().right+gantt.margin().left); expect(getAxisLine().x2.baseVal.value).toBe(gantt.size()[0]-gantt.margin().right-gantt.margin().left); }); it('should get/set the size', function() { var size = gantt.size(); expect(size).toEqual(getSize()); gantt.size(320, 240); size = gantt.size(); expect(size[0]).toBe(320); expect(size[1]).toBe(240); expect(size).toEqual(getSize()); expect(gantt.autoresize()).toBe(false); gantt.size(640); size = gantt.size(); expect(size[0]).toBe(640); expect(size[1]).toBe(240); expect(size).toEqual(getSize()); gantt.size(0, 480); size = gantt.size(); expect(size[0]).toBe(640); expect(size[1]).toBe(480); expect(size).toEqual(getSize()); }); it('should get/set sublanes', function() { expect(gantt.sublanes()).toBe(1); gantt.sublanes(4); expect(gantt.sublanes()).toBe(4); }); it('should get svg element', function() { expect(gantt.svg()).toEqual(d3.select('svg')); }); it('should test method chaining', function() { var data = testData(), margin = {top: 0, right: 1, bottom: 2, left: 3}, conf = { items: data.getItems(), isAutoResize: false, isEnableDrag: false, isEnableItemResize: false, isEnableTooltip: false, isEnableZoom: false, isShowXGrid: false, isShowYGrid: false, isShowLaneLabel: false, height: 240, lanes: [1, 2, 3], margin: margin, renderTo: 'body', sublanes: 2, width: 320, }; var o = gantt.addItems(data.getItems()) .autoresize(conf.isAutoResize) .enableDrag(conf.isEnableDrag) .enableItemResize(conf.isEnableItemResize) .enableTooltip(conf.isEnableTooltip) .enableZoom(conf.isEnableZoom) .items(data.getItems(10)) .lanes(conf.lanes) .margin(margin) .showLaneLabel(conf.isShowLaneLabel) .showXGrid(conf.isShowXGrid) .showYGrid(conf.isShowYGrid) .size(conf.width, conf.height) .sublanes(conf.sublanes); expect(gantt.autoresize()).toBe(conf.isAutoResize); expect(gantt.enableDrag()).toBe(conf.isEnableDrag) expect(gantt.enableItemResize()).toBe(conf.isEnableItemResize); expect(gantt.enableTooltip()).toBe(conf.isEnableTooltip); expect(gantt.enableZoom()).toBe(conf.isEnableZoom); expect(gantt.items().length).toBe(30); expect(gantt.lanes().length).toBe(conf.items.length); expect(gantt.margin()).toEqual(conf.margin); expect(gantt.showLaneLabel()).toBe(conf.isShowLaneLabel); expect(gantt.showXGrid()).toBe(conf.isShowXGrid); expect(gantt.showYGrid()).toBe(conf.isShowYGrid); expect(gantt.size()).toEqual([conf.width, conf.height]); expect(gantt.sublanes()).toBe(conf.sublanes); }); }); import React, {useState} from "react"; import "../App.css"; import { Nav } from "react-bootstrap"; import { Link } from "react-router-dom"; import Picture from "./Picture"; import Auth from '../utils/auth'; import './NavTabs.css'; import { DropdownButton, Dropdown } from 'react-bootstrap' import { useQuery } from '@apollo/client'; import { QUERY_ME } from '../utils/queries'; const styles = { links: { color: "#ac3b12", alignItems: "center", textDecoration: "none", fontWeight: "700" }, bar: { alignItems: "center", borderBottom: "2px solid #ac3b12", top: 0, paddingBottom: "2%", } } function NavTabs() { const [pageTab, setPageTab] = useState('re:mind'); const logout = (event) => { event.preventDefault(); Auth.logout(); }; const { data } = useQuery(QUERY_ME); return ( <div className="container-fluid"> {Auth.loggedIn() ? ( <> <Nav activeKey="1" style={styles.bar} className='color'> <Nav.Item> <Nav.Link eventKey="1" className="nav-link link left"> <Link to={"/"} style={styles.links}> re:mind </Link> </Nav.Link> </Nav.Item> <Nav.Item> <Nav.Link eventKey="1" className="nav-link link"> <Link to={"/greeting"} style={styles.links}> home </Link> </Nav.Link> </Nav.Item> <Nav.Item> <Nav.Link eventKey="2" className="nav-link link"> <Link to={"/dashboard"} style={styles.links} > dashboard </Link> </Nav.Link> </Nav.Item> <Nav.Item> <a variant="light" type="submit" onClick={logout} style={styles.links} className="nav-link"> logout </a> </Nav.Item> <Nav.Item> <Nav.Link eventKey="1" className="nav-link link"> <Link to={"/"} style={styles.links}> <Picture /> </Link> </Nav.Link> </Nav.Item> </Nav> <DropdownButton id="dropdown" title={pageTab} variant="light"> <Dropdown.Item> <Link to={"/"} style={styles.links} onClick={() => setPageTab('re:mind')}> re:mind </Link> </Dropdown.Item> <Dropdown.Item> <Link to={"/greeting"} style={styles.links} onClick={() => setPageTab('home')}> home </Link> </Dropdown.Item> <Dropdown.Item> <Link to={"/dashboard"} style={styles.links} onClick={() => setPageTab('dashboard')}> dashboard </Link> </Dropdown.Item> <Dropdown.Item> <a variant="light" type="submit" onClick={logout} style={styles.links} className="nav-link"> logout </a> </Dropdown.Item> <Dropdown.Item> <Link to={"/"} style={styles.links}> <Picture /> </Link> </Dropdown.Item> </DropdownButton> </> ) : ( <Nav activeKey="1" style={styles.bar} className="customNav color"> <Nav.Item> <Nav.Link eventKey="3" title="Item" className="nav-link link"> <Link to={"/login"} style={styles.links} > login </Link> </Nav.Link> </Nav.Item> <Nav.Item> <Nav.Link eventKey="1" className="nav-link link"> <Link to={"/"} style={styles.links}> re:mind </Link> </Nav.Link> </Nav.Item> </Nav> )} </div> ); } export default NavTabs; <reponame>scboesch/achievements<gh_stars>10-100 /** * Selectors for Account container */ /** * * @param {AchievementsAppState} state * @param {*} ownProps * @returns {*} */ export const getDisplayName = (state, ownProps) => state.firebase.auth.uid && state.firebase.data && state.firebase.data.users && state.firebase.data.users[ ownProps.match.params.accountId || state.firebase.auth.uid ] && state.firebase.data.users[ ownProps.match.params.accountId || state.firebase.auth.uid ].displayName; export const getProfileData = state => Object.keys(state.firebase.data.profileData || {}) .map(profileKey => { const profileType = state.firebase.data.profileData[profileKey]; return { id: profileKey, weight: profileType.weight, title: profileType.title, options: Object.keys(profileType.options || {}) .map(optionKey => ({ name: optionKey, id: profileType.options[optionKey] })) .sort((a, b) => (a.id > b.id ? 1 : -1)) }; }) .sort((a, b) => (a.weight > b.weight ? 1 : -1)); "bar"; function foo(bar) { throw new Error('Intentional.'); } <reponame>snapmaster-io/snapmaster-api // general-purpose module for returning provider-specific entities // this is used to fill dropdowns for clients // // this module validates the provider and entity to add a layer of indirection between // the client and the service, and prevent injection attacks when snap authors supply // malformed or malicious entity names // exports: // createHandlers(app): create handlers for GET endpoint // entityHandler(req, res): handle entity operations (get, add, edit, remove) const database = require('../data/database') const dbconstants = require('../data/database-constants') const providers = require('../providers/providers'); const requesthandler = require('./requesthandler'); const credentials = require('./credentials'); const connections = require('./connections'); const { successvalue, errorvalue } = require('./returnvalue'); exports.createHandlers = (app) => { // entities API endpoint app.use('/entities/:entityName', requesthandler.checkJwt, requesthandler.processUser, exports.entityHandler); } exports.entityHandler = (req, res) => { try { // get the entity name from the parameters let entity = req.params.entityName || req.body.entityName; // get the provider for the entity let [providerName, entityName] = entity.split(':'); if (!providerName) { const message = `could not retrieve provider from entity ${entity}`; console.error(`getEntities: ${message}`); res.status(200).send(errorvalue(message)); return; } // get the provider const provider = providers.getProvider(providerName); if (!provider) { const message = `could not retrieve provider ${providerName}`; console.error(`getEntities: ${message}`); res.status(200).send(errorvalue(message)); return; } // if an entity name wasn't specified, get the connection entity if (!entityName) { const name = provider.definition.connection && provider.definition.connection.entity; if (!name) { const message = `could not retrieve default entity for provider ${providerName}`; console.error(`getEntities: ${message}`); res.status(200).send(errorvalue(message)); return; } // since the entity name wasn't specificed, replace it with the connection entity name entity = name; } // validate entity const providerEntities = provider.entities; if (!providerEntities) { const message = `${provider.name} provider does not support any entities`; console.error(`getEntities: ${message}`); res.status(200).send(errorvalue(message)); return; } const providerEntity = providerEntities[entity]; if (!providerEntity) { const message = `${provider.name} provider does not support entity ${entity}`; console.error(`getEntities: ${message}`); res.status(200).send(errorvalue(message)); return; } if (req.method === 'GET') { getHandler(req, res, providerEntity); return; } // invoke the POST entity handler if (req.method === 'POST') { postHandler(req, res, provider, providerEntity); return; } // return an empty result res.status(200).send(errorvalue('method not supported')); } catch (error) { console.error(`handler: caught exception: ${error}`); res.status(200).send(errorvalue(error.message, error)); //res.status(200).send([]); } } const getHandler = (req, res, entity) => { // construct the api description that the DAL machinery expects const apiDescription = { ...entity }; apiDescription.func = () => []; // just return an empty array and let the DAL to the real work requesthandler.invokeProvider( res, req.userId, apiDescription, null, // use the default entity name [req.userId]); // parameter array } const postHandler = (req, res, provider, entity) => { const action = req.body && req.body.action; // construct the api description that the DAL machinery expects const apiDescription = { ...entity, func: entity.entityHandler }; const add = async () => { // use the generic edit handler as the function the DAL will call apiDescription.func = addHandler; // use the entity's func as the function the DAL will call //apiDescription.func = entity.func; requesthandler.invokeProvider( res, req.userId, apiDescription, null, // use the default entity name //[req.body.connectionInfo]); // parameter array [req.userId, entity, req.body.connectionInfo]); } const edit = async () => { // use the generic edit handler as the function the DAL will call apiDescription.func = editHandler; requesthandler.invokeProvider( res, req.userId, apiDescription, null, // use the default entity name [req.userId, entity.entity, req.body]); // parameter array } const remove = async () => { // use the generic remove handler as the function the DAL will call apiDescription.func = removeHandler; requesthandler.invokeProvider( res, req.userId, apiDescription, null, // use the default entity name [req.userId, entity.entity, req.body.id]); // parameter array } if (action === 'add' && req.body && req.body.connectionInfo) { add(); return; } if (action === 'edit') { edit(); return; } if (action === 'remove' && req.body && req.body.id) { remove(); return; } res.status(200).send(errormessage('Unknown action')); } // generic add handler const addHandler = async ([userId, entity, connectionInfo]) => { try { // const entityName = entity.entity; const connection = entity.provider; const func = entity.func; const defaultConnInfo = await connections.getConnectionInfo(userId, connection); const response = await func([connectionInfo, defaultConnInfo]); if (!response) { return errorvalue(`could not add the ${entityName} credential`); } // if this is an error, return it now if (response.error || response.message) { return response; } // store any secrets in the secret store if (response.secret) { const secretId = response[entity.itemKey]; const jsonValue = JSON.stringify(response.secret); const key = await credentials.set(userId, `${userId}:${entityName}:${secretId}`, jsonValue); // substitute the key name for the secret info in the response response[dbconstants.keyField] = key; delete response.secret; } return [response]; } catch (error) { console.log(`addHandler: caught exception: ${error}`); return null; } } // generic edit handler const editHandler = async ([userId, entityName, payload]) => { try { // retrieve the entity ID out of the payload const id = payload.__id; if (!id) { console.error('editHandler: entity ID not found in payload'); return null; } // retrieve the document from the entity collection const entity = await database.getDocument(userId, entityName, id); // remove the action from the payload delete payload.action; // merge the payload with the existing entity const result = { ...entity, ...payload }; // store the document in the entity collection await database.storeDocument(userId, entityName, id, result); // invokeProvider will re-read the entity collection and return it return []; } catch (error) { console.error(`editHandler: caught exception: ${error}`); return null; } } // generic remove handler const removeHandler = async ([userId, entityName, id]) => { try { // get the key if it exists const connectionInfo = await database.getDocument(userId, entityName, id); if (!connectionInfo) { return errorvalue(`${id} not found`); } if (connectionInfo[dbconstants.keyField]) { // remove the secret associated with the key credentials.remove(userId, connectionInfo[dbconstants.keyField]); } // remove the document from the entity collection await database.removeDocument(userId, entityName, id); // invokeProvider will re-read the entity collection and return it return []; } catch (error) { console.error(`removeHandler: caught exception: ${error}`); return null; } } <gh_stars>0 // jshint ignore: start (function () { 'use strict'; angular .module("metal.scenario") .controller("ScenarioController", ScenarioController); ScenarioController.$inject = ['$rootScope', '$scope', 'ScenarioFactory', 'ChartsFactory', 'CesiumFactory', 'StockFactory']; /** * @ngdoc controller * @name ScenarioController * @memberof metal.scenario * * @constructor */ function ScenarioController($rootScope, $scope, ScenarioFactory, ChartsFactory, CesiumFactory, StockFactory) { var vm = this; $scope.data = []; activate(); /** * activate function * * @memberof metal.cesium.cesiumController * @returns Console output */ function activate() { console.log("Activated Layout"); $rootScope.viewer = new Cesium.Viewer('cesiumContainer', { animation: false, timeline: false, baseLayerPicker: false, fullscreenButton: false, geocoder: false, homeButton: false, infoBox: true, sceneModePicker: true, sceneMode: Cesium.SceneMode.SCENE2D, selectionIndicator: true, navigationHelpButton: false, navigationInstructionsInitiallyVisible: false, scene3Donly: false, imageryProvider: new Cesium.createOpenStreetMapImageryProvider({ url: 'https://a.tile.openstreetmap.org' }) // imageryProvider: new Cesium.ArcGisMapServerImageryProvider({ // url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer' // }) }); var layers = $rootScope.viewer.scene.imageryLayers; var blackMarble = $rootScope.viewer.addImageryProvider(new Cesium.TileMapServiceImageryProvider({ url : '//cesiumjs.org/tilesets/imagery/blackmarble', maximumLevel : 8, credit : 'Black Marble imagery courtesy NASA Earth Observatory' })); blackMarble.alpha = 0.5; blackMarble.brightness = 2.0; $rootScope.server_port = '8070'; // Create jqxDocking // $("#docking").jqxDocking({width: 250, theme: 'classic'}); // $("#importBtn").click(); } $rootScope.$on('loadScenario', function (event, name) { console.log('caught the $emit of ', name); $scope.getScenario(name); }); $scope.getScenario = function (scenarioName) { //$scope.run_model(scenarioName); //$scope.getRoutes(scenarioName); //$scope.data = [{ key: "Some key", values:[{"label":"77", "value":"22.0"}]}]; ScenarioFactory.getScenarios().get({id: scenarioName}, function (data) { }); ChartsFactory.getTimeToFailure().get({id: scenarioName}).$promise.then(function (data) { console.log("In Line Factory"); var chartKey = data.key; var chartDataStr = data.data; var jsonChartData = angular.fromJson(chartDataStr); $scope.data = [ { key: chartKey, values: jsonChartData } ]; }).then(function () { CesiumFactory.getMapData().get({id: scenarioName}).$promise.then(function (data) { console.log('Cesium Factory; data follows :', data); // clear the existing map $rootScope.viewer.entities.removeAll(); // create entities from the map data $scope.selectedScenario = createCesiumMapEntities(data); // add entities to the map $scope.selectedScenario.forEach(function (e) { $rootScope.viewer.entities.add(e); }); // zoom into entity location $rootScope.viewer.flyTo($rootScope.viewer.entities, { duration: 5, maxiumHeight: 500 }); }); }); }; var earthradius = 3440.2769; var sqrt3 = Math.sqrt(3); function radians(deg) { return (deg * (Math.PI / 180)); } function degLatToNm(degLat) { return ((Math.PI * earthradius * 2 / 360) * degLat); } function nmToDegLat(nm) { return (nm / degLatToNm(1)); } function degLonToNm(degLon, lat) { var latradius = Math.cos(radians(lat)) * earthradius; return ((Math.PI * latradius * 2 / 360) * degLon); } function nmToDegLon(nm, lat) { return (nm / degLonToNm(1, lat)); } function nmToLatLon(nmx, nmy) { var lat = nmToDegLat(nmy); var lon = nmToDegLon(nmx, lat); return [lat, lon]; } $scope.export = function (eventData) { console.log("Export button clicked"); var jsondatastr = $('#docking').jqxDocking('exportLayout'); console.log(jsondatastr); $scope.perspective.jsondata = jsondatastr; StockFactory.getPerspectives().update($scope.perspective, function () { console.log("saved"); }); }; $scope.import = function (eventData) { console.log("Import button clicked"); //var jsondata = '{"panel0": {"window3":{"collapsed":false}},"floating":{"window1":{"x":"1320px","y":"55px","width":"265","height":"571","collapsed":false},"window2":{"x":"330px","y":"347px","width":"870","height":"537","collapsed":false}},"orientation": "horizontal"}'; StockFactory.getPerspectives().get({id: 1}, function (data) { //console.log(data); $scope.perspective = data; $('#docking').jqxDocking('importLayout', data.jsondata); }); }; $scope.run_model = function (scenarioName) { ScenarioFactory.getScenarios().run({id: scenarioName}, function (data) { console.log("model run for scenario:" + scenarioName); }); }; $scope.options = { chart: { type: 'discreteBarChart', height: 450, margin: { top: 20, right: 20, bottom: 50, left: 55 }, x: function (d) { return d.label; }, y: function (d) { return d.value; }, showValues: true, valueFormat: function (d) { return d3.format(',.4f')(d); }, duration: 500, xAxis: { axisLabel: 'X Axis' }, yAxis: { axisLabel: 'Y Axis', axisLabelDistance: -10 } } }; var createCesiumMapEntities = function (data) { var viewerData = []; // add sites data.sites.forEach(function (e) { var site = e; var ll = nmToLatLon(site.latitude, site.longitude); var assetresourcetable = 'none'; var ares; if (e.asset.asset_resources.length > 0) { assetresourcetable = '<br><table><tr><td>Resource</td><td>Congested Consumption</td><td>Uncongested Consumption</td></tr>'; for (var ar = 0; ar < e.asset.asset_resources.length; ar++) { ares = e.asset.asset_resources[ar]; assetresourcetable = assetresourcetable + '<tr><td>' + ares.resource.name + '</td><td>' + ares.contested_consumption + '</td><td>' + ares.uncontested_consumption + '</td></tr>'; } assetresourcetable = assetresourcetable + '</table>'; } viewerData.push({ id: site.name, name: site.name, description: 'Location: ' + site.latitude + ', ' + site.longitude + '<br>' + 'Asset Type: ' + site.asset.name + '<br>Asset Resources: ' + assetresourcetable, position: Cesium.Cartesian3.fromDegrees(ll[1], ll[0]), point: { pixelSize: 6, color: Cesium.Color.fromCssColorString(site.asset.htmlcolor), outlineColor: Cesium.Color.WHITE, outlineWidth: 2 }, label: { text: site.name, font: '14pt monospace', style: Cesium.LabelStyle.FILL_AND_OUTLINE, outlineWidth: 2, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, pixelOffset: new Cesium.Cartesian2(0, -9) } }); }); // add threat areas var riskareas = data.risk_areas; for (var i = 0; i < riskareas.length; i++) { var area = riskareas[i]; var degarray = []; for (var j = 0; j < area.risk_area_verteces.length; j++) { var vertex = area.risk_area_verteces[j]; var ll = nmToLatLon(vertex.latitude, vertex.longitude); degarray.push(ll[1]); degarray.push(ll[0]); } var rcolor = Cesium.Color.fromCssColorString(area.risktype.htmlcolor); viewerData.push({ id: area.name, name: area.name, description: 'Risk Type: ' + area.risktype.name, polygon: { hierarchy: Cesium.Cartesian3.fromDegreesArray(degarray), material: rcolor.withAlpha(0.5), fill: true, height: 0, outline: true, outlineColor: rcolor, outlineWidth: 5 } }); } // add routes var routedata = data.routes; for (var i = 0; i < routedata.length; i++) { var route = routedata[i]; if (route.asset_route_assignments.length === 0) { // no assignments to this route continue; } var degarray = []; for (var j = 0; j < route.route_segments.length; j++) { var seg = route.route_segments[j]; if (j === 0) { var ll0 = nmToLatLon(seg.start_latitude, seg.start_longitude); degarray.push(ll0[1]); degarray.push(ll0[0]); } var ll1 = nmToLatLon(seg.end_latitude, seg.end_longitude); degarray.push(ll1[1]); degarray.push(ll1[0]); } var asset_assignments = '<table>'; asset_assignments = asset_assignments + '<tr><td>Asset</td><td>Quantity</td>'; for (var r = 0; r < data.resources.length; r++) { asset_assignments = asset_assignments + '<td>' + data.resources[r].name + '</td>'; } asset_assignments = asset_assignments + '</tr>'; var ares; for (var j = 0; j < route.asset_route_assignments.length; j++) { var assetinv = route.asset_route_assignments[j]; var asset = assetinv.asset; asset_assignments = asset_assignments + '<tr><td>' + asset.name + '</td><td>' + assetinv.count + '</td>'; for (var r = 0; r < data.resources.length; r++) { var res = data.resources[r]; var found = false; for (var ar = 0; ar < asset.asset_resources.length; ar++) { ares = asset.asset_resources[ar]; if (ares.resource.id === res.id) { asset_assignments = asset_assignments + '<td>' + ares.transport_capacity + '</td>'; found = true; break; } } if (!found) { asset_assignments = asset_assignments + '<td>0</td>'; } } asset_assignments = asset_assignments + '</tr>'; } asset_assignments = asset_assignments + '</table>'; viewerData.push({ id: route.name, name: route.name, description: 'length: ' + route.distance + '<br>Asset Assignments:<br>' + asset_assignments, polyline: { positions: Cesium.Cartesian3.fromDegreesArray(degarray), width: 5, material: new Cesium.PolylineGlowMaterialProperty({ glowPower: 0.2, color: Cesium.Color.BLUE }) } }); } return viewerData; }; } })(); // jshint ignore: end <reponame>markhuot/now-craftcms (function($) { /** global: Craft */ /** global: Garnish */ Craft.Installer = Garnish.Base.extend( { $bg: null, $screens: null, $dots: null, $currentScreen: null, $currentDot: null, $dbDriverInput: null, $dbPortInput: null, modal: null, currentScreen: null, loading: false, /** * Constructor */ init: function() { this.$bg = $('#bg'); this.$screens = $('#screens').children(); this.$dbDriverInput = $('#db-driver'); this.$dbPortInput = $('#db-port'); this.updateDbPortInput(); this.addListener(this.$screens.find('form'), 'submit', 'handleScreenSubmit'); this.addListener(this.$screens.find('.btn.submit'), 'activate', 'handleScreenSubmit'); this.addListener($('#beginbtn'), 'activate', 'showModal'); this.addListener(this.$dbDriverInput, 'change', 'updateDbPortInput'); new Craft.PasswordInput('#account-password'); }, showModal: function() { if (!this.modal) { this.modal = new Garnish.Modal($('#install-modal').removeClass('hidden'), { shadeClass: '' }); this.gotoScreen(1); } else { this.modal.show(); } }, updateDbPortInput: function() { var driver = this.$dbDriverInput.val(); var port = this.$dbPortInput.val(); var defaultPort = Craft.Installer.defaultDbPorts[driver]; this.$dbPortInput.attr('placeholder', defaultPort); if (port == defaultPort) { this.$dbPortInput.val(''); } }, handleScreenSubmit: function(ev) { ev.preventDefault(); var inputs = this.getScreenInputNames(this.$currentScreen); if (inputs) { this.validate(this.$currentScreen.attr('id'), inputs); } else { this.gotoNextScreen(); } }, getScreenInputNames: function($screen) { var inputsStr = $screen.attr('data-inputs'); return inputsStr ? inputsStr.split(',') : null; }, getInputData: function(what, inputs, includePrefix) { var data = {}; for (var i = 0; i < inputs.length; i++) { var input = inputs[i], $input = $('#' + what + '-' + input); data[(includePrefix ? what + '-' : '') + input] = Garnish.getInputPostVal($input); } return data; }, showInstallScreen: function() { var data = {}; var $screen; var inputs; for (var i = 1; i < this.$screens.length - 1; i++) { $screen = this.$screens.eq(i); inputs = this.getScreenInputNames($screen); $.extend(data, this.getInputData($screen.attr('id'), inputs, true)); } Craft.postActionRequest('install/install', data, $.proxy(this, 'allDone'), { complete: $.noop }); }, allDone: function(response, textStatus) { $('#spinner').remove(); var $h1 = this.$currentScreen.find('h1:first'); if (textStatus === 'success' && response.success) { $h1.text(Craft.t('app', 'Craft is installed! 🎉')); setTimeout(function() { window.location.href = Craft.getUrl('dashboard'); }, 1000); } else { $h1.text('Install failed 😞'); $('<p/>', {text: 'Please check your logs for more info.'}) .insertAfter($h1); } }, gotoNextScreen: function() { this.gotoScreen(this.currentScreen + 1); }, gotoScreen: function(i) { // Show the dots (unless it's the license screen) if (i === 1) { if (this.$dots) { this.$dots.hide(); } } else { if (!this.$dots) { this.$dots = $(); for (var j = 0; j < this.$screens.length; j++) { this.$dots = this.$dots.add($('<div/>').appendTo($('#dots'))); } } else { this.$dots.show(); } } // Hide the current screen if (this.$currentScreen) { this.$currentScreen.addClass('hidden'); if (this.$currentDot) { this.$currentDot.removeClass('sel'); } } // Slide in the new screen this.currentScreen = i; this.$currentScreen = this.$screens.eq(i - 1) .removeClass('hidden'); if (this.$dots) { this.$currentDot = this.$dots.eq(i - 1) .addClass('sel'); } // Is this the install screen? if (i === this.$screens.length) { this.showInstallScreen(); } else if (i !== 1) { // Give focus to the first input this.$currentScreen.find('input[type=text]:first').trigger('focus'); } }, validate: function(what, inputs) { // Prevent double-clicks if (this.loading) { return; } this.loading = true; // Clear any previous error lists this.$currentScreen.find('.input').removeClass('errors'); this.$currentScreen.find('ul.errors').remove(); var $submitBtn = this.$currentScreen.find('.btn.submit'); $submitBtn.addClass('sel loading'); var action = 'install/validate-' + what; var data = this.getInputData(what, inputs, false); Craft.postActionRequest(action, data, $.proxy(function(response, textStatus) { this.loading = false; $submitBtn.removeClass('sel loading'); if (textStatus === 'success') { if (response.validates) { this.gotoNextScreen(); } else { var $errors = $('<ul/>', {'class': 'errors'}) .insertBefore($('#' + what).find('.buttons')); for (var input in response.errors) { if (!response.errors.hasOwnProperty(input)) { continue; } for (var i = 0; i < response.errors[input].length; i++) { $('<li>' + response.errors[input][i] + '</li>').appendTo($errors); } var $input = $('#' + what + '-' + input + '-field').children('.input'); $input.addClass('errors'); ($.proxy(function($input) { var $elements = $input.find('select,input'); this.addListener($elements, 'focus,blur,textchange,change', function() { $input.removeClass('errors'); this.removeListener($elements, 'focus,blur,textchange,change'); }); }, this))($input); } Garnish.shake(this.$currentScreen); } } }, this)); } }, { defaultDbPorts: { 'mysql': 3306, 'pgsql': 5432 } }); Garnish.$win.on('load', function() { Craft.installer = new Craft.Installer(); }); })(jQuery); <filename>src/pages/index.js import React from "react" import { Link } from "gatsby" import PageTransition from 'gatsby-plugin-page-transitions'; import Layout from "../components/layout" import Image from "../components/image" import SEO from "../components/seo" import PoemSingle from "../components/PoemSingle" const IndexPage = () => ( <PageTransition defaultStyle={{ transition: 'left 500ms cubic-bezier(0.47, 0, 0.75, 0.72)', left: '100%', position: 'absolute', width: '100%', }} transitionStyles={{ entering: { left: '0%' }, entered: { left: '0%' }, exiting: { left: '100%' }, }} transitionTime={500} > <Layout> <SEO title="Home" keywords={[`gatsby`, `application`, `react`]} /> <div className="PoemList"> </div> <Link to="/page-2/">Go to page 2</Link> </Layout> </PageTransition> ) export default IndexPage <gh_stars>10-100 // @flow import React, { type Node as ReactNode } from 'react'; import StyleSheet from '../stylesheet'; type Props = { name: String, style: { [string]: string | number }, children: ReactNode, }; export default class Text extends React.Component<Props> { static defaultProps = { name: 'Text', }; render() { const { name, style, children } = this.props; return ( <text name={name} style={{ fontSize: 16, ...(style && StyleSheet.flatten(style)) }} > {children} </text> ); } } 'use strict'; const Redis = require('ioredis'); const config = require('./../config'); const uuid = require('uuid/v4'); const azureSearch = require('./../azureSearch'); const client = new Redis(config.cache.params.indexPointerConnectionString); const pageSize = 25; const createIndex = async () => { const fields = [ { name: 'id', type: 'Edm.String', key: true, searchable: false }, { name: 'deviceId', type: 'Edm.String', searchable: false }, { name: 'deviceStatus', type: 'Edm.String', searchable: false, filterable: true }, { name: 'serialNumber', type: 'Edm.String', sortable: true, searchable: true }, { name: 'name', type: 'Edm.String', sortable: true, filterable: true, searchable: true }, { name: 'nameSearch', type: 'Edm.String', searchable: true }, { name: 'email', type: 'Edm.String', sortable: true, filterable: true, searchable: true }, { name: 'emailSearch', type: 'Edm.String', searchable: true }, { name: 'organisationName', type: 'Edm.String', sortable: true, filterable: true, searchable: true }, { name: 'lastLogin', type: 'Edm.Int64', sortable: true, filterable: true }, ]; return await azureSearch.createIndex(`userdevices-${uuid()}`, fields); }; const updateIndex = async (userDevices, index) => { if(!userDevices || userDevices.length === 0) { return; } if(!index) { index = await client.get('CurrentIndex_UserDevices'); } const userDeviceMap = userDevices.map((userDevice) => { let lastLogin = userDevice.lastLogin; if (lastLogin && lastLogin instanceof Date) { lastLogin = lastLogin.getTime(); } return { '@search.action': 'upload', id: userDevice.id, deviceId: userDevice.device.id, deviceStatus: userDevice.device.status, serialNumber: userDevice.device.serialNumber, name: userDevice.name, nameSearch: userDevice.name ? userDevice.name.replace(/\s/g, '').toLowerCase() : '', email: userDevice.email, emailSearch: userDevice.email ? userDevice.email.replace('@','').toLowerCase() : '', organisationName: userDevice.organisation ? userDevice.organisation.name : '', lastLogin, }; }); return await azureSearch.updateIndex(userDeviceMap, index) }; const updateActiveIndex = async (index) => { await client.set('CurrentIndex_UserDevices', index) }; const deleteUnusedIndexes = async () => { const currentIndexName = await client.get('CurrentIndex_UserDevices'); // Delete any indexes already marked as unused const unusedJson = await client.get('UnusedIndexes_UserDevices'); const unusedIndexes = unusedJson ? JSON.parse(unusedJson) : []; await azureSearch.deleteUnusedIndexes(unusedIndexes, currentIndexName); // Find any remaining indexes that appear to be unused const indexesResponse = await azureSearch.getIndexes(); const indexesAppearingUnused = indexesResponse.value.map(x => x.name).filter(x => x !== currentIndexName && x.toLowerCase().indexOf('userdevices-') !== -1); await client.set('UnusedIndexes_UserDevices', JSON.stringify(indexesAppearingUnused)); }; const mapUser = (user) => { if(!user) { return null; } return { id: user.id, name: user.name, email: user.email, organisation: user.organisationName ? { name: user.organisationName } : null, lastLogin: user.lastLogin ? new Date(user.lastLogin) : null, device: { id: user.deviceId, status: user.deviceStatus, serialNumber: user.serialNumber, serialNumberFormatted: `${user.serialNumber.substr(0, 2)}-${user.serialNumber.substr(2, 7)}-${user.serialNumber.substr(9, 1)}` } } }; const search = async (criteria, pageNumber, sortBy = 'serialNumber', sortAsc = true) => { const currentIndexName = await client.get('CurrentIndex_UserDevices'); try { const skip = (pageNumber - 1) * pageSize; let orderBy; switch (sortBy) { case 'serialNumber': orderBy = sortAsc ? 'serialNumber' : 'serialNumber desc'; break; case 'organisation': orderBy = sortAsc ? 'organisationName' : 'organisationName desc'; break; case 'name': orderBy = sortAsc ? 'name' : 'name desc'; break; case 'status': orderBy = sortAsc ? 'deviceStatus' : 'deviceStatus desc'; break; case 'lastlogin': orderBy = sortAsc ? 'lastLogin desc' : 'lastLogin'; break; default: orderBy = sortAsc ? 'serialNumber' : 'serialNumber desc'; break; } criteria = criteria.replace(/\s/g, '').replace('@','').toLowerCase(); const formattedCriteria = criteria.replace(/-/g,''); const serialNumber = parseInt(formattedCriteria); if(!isNaN(serialNumber)) { criteria = formattedCriteria; } const response = await azureSearch.search(currentIndexName, criteria, skip, pageSize, orderBy); let numberOfPages = 1; const totalNumberOfResults = parseInt(response['@odata.count']); if (!isNaN(totalNumberOfResults)) { numberOfPages = Math.ceil(totalNumberOfResults / pageSize); } return { userDevices: response.value.map((user) => { return mapUser(user); }), numberOfPages, totalNumberOfResults, }; } catch (e) { throw e; } }; const getByUserId = async (userId, filterParam='id') => { try { const currentIndexName = await client.get('CurrentIndex_UserDevices'); const user = await azureSearch.getIndexById(currentIndexName, userId, filterParam); return mapUser(user); } catch (e) { throw e; } }; module.exports = { createIndex, updateIndex, updateActiveIndex, deleteUnusedIndexes, search, getByUserId, }; <reponame>vinsonchuong/assertion-workflow import { connect } from 'react-redux' import { createStructuredSelector } from 'reselect' export default function(Component, selectors, actions) { return connect( createStructuredSelector(selectors), actions )(Component) } const mongoose = require('mongoose'); const Schema = mongoose.Schema; const OrderModel = new Schema( { cart: { type: Object, required: true, }, author: { type: Schema.Types.ObjectId, ref: 'User', }, delivery: { type: String, required: true, }, payment: { type: String, required: true, }, name: { type: String, required: true, }, // mail:{ // type:String, // required:true, // }, phone: { type: String, required: true, }, // country:{ // type:String, // required:true, // }, city: { type: String, required: true, }, address: { type: String, required: true, }, status: { type: String, required: true, default: 'new', }, }, { timestamps: true }, ); module.exports = mongoose.model('Order', OrderModel); export { default as remindersMiddlewares } from './reminders' export const schema = gql` type Email { id: String! name: String! email: String! subject: String! content: String! } type Query { emails: [Email!]! email(id: String!): Email } input CreateEmailInput { name: String! email: String! subject: String! content: String! } input UpdateEmailInput { name: String email: String subject: String content: String } type Mutation { createEmail(input: CreateEmailInput!): Email! updateEmail(id: String!, input: UpdateEmailInput!): Email! deleteEmail(id: String!): Email! } ` <filename>public/modules/pokerlogs/tests/pokerlogs.client.controller.test.js<gh_stars>0 'use strict'; (function() { // Pokerlogs Controller Spec describe('Pokerlogs Controller Tests', function() { // Initialize global variables var PokerlogsController, scope, $httpBackend, $stateParams, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the Pokerlogs controller. PokerlogsController = $controller('PokerlogsController', { $scope: scope }); })); it('$scope.find() should create an array with at least one Pokerlog object fetched from XHR', inject(function(Pokerlogs) { // Create sample Pokerlog using the Pokerlogs service var samplePokerlog = new Pokerlogs({ name: '<NAME>' }); // Create a sample Pokerlogs array that includes the new Pokerlog var samplePokerlogs = [samplePokerlog]; // Set GET response $httpBackend.expectGET('pokerlogs').respond(samplePokerlogs); // Run controller functionality scope.find(); $httpBackend.flush(); // Test scope value expect(scope.pokerlogs).toEqualData(samplePokerlogs); })); it('$scope.findOne() should create an array with one Pokerlog object fetched from XHR using a pokerlogId URL parameter', inject(function(Pokerlogs) { // Define a sample Pokerlog object var samplePokerlog = new Pokerlogs({ name: '<NAME>' }); // Set the URL parameter $stateParams.pokerlogId = '525a8422f6d0f87f0e407a33'; // Set GET response $httpBackend.expectGET(/pokerlogs\/([0-9a-fA-F]{24})$/).respond(samplePokerlog); // Run controller functionality scope.findOne(); $httpBackend.flush(); // Test scope value expect(scope.pokerlog).toEqualData(samplePokerlog); })); it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Pokerlogs) { // Create a sample Pokerlog object var samplePokerlogPostData = new Pokerlogs({ name: '<NAME>' }); // Create a sample Pokerlog response var samplePokerlogResponse = new Pokerlogs({ _id: '525cf20451979dea2c000001', name: '<NAME>' }); // Fixture mock form input values scope.name = '<NAME>'; // Set POST response $httpBackend.expectPOST('pokerlogs', samplePokerlogPostData).respond(samplePokerlogResponse); // Run controller functionality scope.create(); $httpBackend.flush(); // Test form inputs are reset expect(scope.name).toEqual(''); // Test URL redirection after the Pokerlog was created expect($location.path()).toBe('/pokerlogs/' + samplePokerlogResponse._id); })); it('$scope.update() should update a valid Pokerlog', inject(function(Pokerlogs) { // Define a sample Pokerlog put data var samplePokerlogPutData = new Pokerlogs({ _id: '525cf20451979dea2c000001', name: '<NAME>' }); // Mock Pokerlog in scope scope.pokerlog = samplePokerlogPutData; // Set PUT response $httpBackend.expectPUT(/pokerlogs\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality scope.update(); $httpBackend.flush(); // Test URL location to new object expect($location.path()).toBe('/pokerlogs/' + samplePokerlogPutData._id); })); it('$scope.remove() should send a DELETE request with a valid pokerlogId and remove the Pokerlog from the scope', inject(function(Pokerlogs) { // Create new Pokerlog object var samplePokerlog = new Pokerlogs({ _id: '525a8422f6d0f87f0e407a33' }); // Create new Pokerlogs array and include the Pokerlog scope.pokerlogs = [samplePokerlog]; // Set expected DELETE response $httpBackend.expectDELETE(/pokerlogs\/([0-9a-fA-F]{24})$/).respond(204); // Run controller functionality scope.remove(samplePokerlog); $httpBackend.flush(); // Test array after successful delete expect(scope.pokerlogs.length).toBe(0); })); }); }());<gh_stars>100-1000 /* * This file is part of the nivo project. * * (c) 2016 <NAME> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ 'use strict' const { generateCountriesData } = require('nivo-generators') const keys = [ 'hot dogs', 'burgers', 'sandwich', 'kebab', 'fries', 'donut', 'junk', 'sushi', 'ramen', 'curry', 'udon', 'bagel', ] module.exports = { type: 'heatmap', props: { width: 900, height: 600, data: generateCountriesData(keys, { size: 9, min: 0, max: 100 }), keys, indexBy: 'country', forceSquare: true, cellShape: 'circle', cellBorderWidth: 2, cellBorderColor: 'inherit:darker(0.4)', padding: 4, sizeVariation: 0.5, enableGridY: true, labelTextColor: 'inherit:darker(2.4)', colors: 'PuOr', }, } <reponame>AHurnell/Stripe-Webtask-StartupGrind //import stripe latest version var stripe = require('stripe@4.14.0'); module.exports = function(ctx, cb) { //ctx is equivalent to context //Call stripe to pay an order //Pass order ID and stripe credit card token (POST variables) stripe(ctx.secrets.stripe_private_api_key).orders.pay(ctx.body.order, { source: ctx.body.token }, function(err, paid_order){ //called asynchronously //returns the result of the stripe payment process cb(null, { paid_order: paid_order || err }); }); }; export const CAT_ENTRIES = [ { title: "Whatever", subtitle: "", illustration: "https://i.giphy.com/media/3o85xGr7NxBC4eGTte/giphy.webp", unlocked_illustration: "https://i.giphy.com/media/3o85xGr7NxBC4eGTte/giphy.webp", value: "" }, { title: "Video Games", subtitle: "", illustration: "https://imgix.bustle.com/uploads/image/2019/12/12/ed336be3-2ce1-4f50-9f73-967b0c9bd6d7-gettyimages-1129878609.jpg?w=1020&h=576&fit=crop&crop=faces&auto=format&q=70", unlocked_illustration: "https://imgix.bustle.com/uploads/image/2019/12/12/ed336be3-2ce1-4f50-9f73-967b0c9bd6d7-gettyimages-1129878609.jpg?w=1020&h=576&fit=crop&crop=faces&auto=format&q=70", value: 15 }, { title: "History", subtitle: "", illustration: "https://aralingua.com/wp-content/uploads/2019/03/History-of-Arabic-Translation-in-Arab-World.jpg", unlocked_illustration: "https://aralingua.com/wp-content/uploads/2019/03/History-of-Arabic-Translation-in-Arab-World.jpg", value: 23 }, { title: "Animals", subtitle: "", illustration: "https://i.imgur.com/orExM11.jpg", unlocked_illustration: "https://i.imgur.com/orExM11.jpg", value: 27 }, { title: "Geography", subtitle: "", illustration: "https://carleton.ca/geography/wp-content/uploads/Geography-Banner.jpg", unlocked_illustration: "https://carleton.ca/geography/wp-content/uploads/Geography-Banner.jpg", value: 22 }, { title: "Computers", subtitle: "", illustration: "https://assets.materialup.com/uploads/b0597a97-8347-4f9c-b6c2-0bdefa982d44/preview.jpg", unlocked_illustration: "https://assets.materialup.com/uploads/b0597a97-8347-4f9c-b6c2-0bdefa982d44/preview.jpg", value: 18 }, { title: "Science & Nature", subtitle: "", illustration: "https://i.imgur.com/sduLRvf.jpg", unlocked_illustration: "https://i.imgur.com/sduLRvf.jpg", value: 17 }, { title: "Books", subtitle: "", illustration: "https://i.imgur.com/C3MzO1Y.png", unlocked_illustration: "https://i.ebayimg.com/images/g/l6IAAOxyUrZS64di/s-l300.jpg", value: 10, unlockPoints: 25 }, { title: "Film", subtitle: "", illustration: "https://i.imgur.com/Y6Jml4L.png", unlocked_illustration: "https://static1.squarespace.com/static/55396962e4b053ce148cb1e1/t/57210fcab6aa60cca01f49fb/1461784525042/rolleiflex-brooklyn-film-camera.jpg?format=1500w", value: 11, unlockPoints: 35 } ]; export const DIFF_ENTRIES = [ { title: "Any", subtitle: "", illustration: "http://i.imgur.com/SsJmZ9jl.jpg", unlocked_illustration: "http://i.imgur.com/SsJmZ9jl.jpg", value: "" }, { title: "Easy", subtitle: "", illustration: "http://i.imgur.com/SsJmZ9jl.jpg", unlocked_illustration: "http://i.imgur.com/SsJmZ9jl.jpg", value: "easy" }, { title: "Medium", subtitle: "", illustration: "http://i.imgur.com/5tj6S7Ol.jpg", unlocked_illustration: "http://i.imgur.com/5tj6S7Ol.jpg", value: "medium" }, { title: "Hard", subtitle: "", illustration: "http://i.imgur.com/pmSqIFZl.jpg", unlocked_illustration: "http://i.imgur.com/pmSqIFZl.jpg", value: "hard" } ]; // Import server startup through a single index entry point import '/imports/startup/both/index'; import '/imports/api/mainIndex'; import '/imports/api/sandstorm'; import '/imports/api/sources'; import { exec } from 'child_process'; import { Config } from '/imports/startup/both/config'; if (Meteor.isServer) { import { ensureDirectoryStructure } from '/imports/lib/store'; ensureDirectoryStructure(Config.localFileRoot + '/apps'); ensureDirectoryStructure(Config.localFileRoot + '/packages'); ensureDirectoryStructure(Config.localFileRoot + '/images'); } <gh_stars>0 var chalk = require('chalk') function s (n) { return Array.apply(null, {length: n}).join(' ') } function logo (opts) { opts = opts || {} opts.leftPadding = typeof opts.leftPadding === 'number' ? opts.leftPadding : (process.stdout.columns / 2) - 4 opts.text = (opts.text) ? opts.text : '' return '\n' + '\n' + s(opts.leftPadding) + chalk.gray(' ĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐ') + '\n' + s(opts.leftPadding) + chalk.gray('Đ') + chalk.black('ĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐ') + chalk.gray('Đ') + '\n' + s(opts.leftPadding) + chalk.gray('Đ') + chalk.black('ĐĐĐ') + chalk.gray('ĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐ') + '\n' + s(opts.leftPadding) + chalk.gray('Đ') + chalk.black('ĐĐĐ') + chalk.gray('Đ') + chalk.white('ĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐ') + chalk.gray('Đ') + '\n' + s(opts.leftPadding) + chalk.gray('Đ') + chalk.black('ĐĐĐ') + chalk.gray('Đ') + chalk.white('ĐĐĐĐ') + chalk.gray('ĐĐĐĐĐ') + chalk.white('ĐĐĐĐĐĐĐ') + chalk.gray('Đ') + '\n' + s(opts.leftPadding) + chalk.gray('Đ') + chalk.black('ĐĐĐ') + chalk.gray('Đ') + chalk.white('ĐĐĐĐ') + chalk.gray('Đ') + chalk.white('ĐĐĐĐ') + chalk.gray('ĐĐ') + chalk.white('ĐĐĐĐĐ') + chalk.gray('Đ') + '\n' + s(opts.leftPadding) + chalk.gray('Đ') + chalk.black('ĐĐĐ') + chalk.gray('Đ') + chalk.white('ĐĐĐĐ') + chalk.gray('Đ') + chalk.white('ĐĐĐĐĐ') + chalk.gray('ĐĐ') + chalk.white('ĐĐĐĐ') + chalk.gray('Đ ') + chalk.white(opts.text) + '\n' + s(opts.leftPadding) + chalk.gray('Đ') + chalk.black('ĐĐĐ') + chalk.gray('Đ') + chalk.white('ĐĐĐĐ') + chalk.gray('Đ') + chalk.white('ĐĐĐĐ') + chalk.gray('ĐĐ') + chalk.white('ĐĐĐĐĐ') + chalk.gray('Đ') + '\n' + s(opts.leftPadding) + chalk.gray('ĐĐĐĐĐĐĐĐĐĐĐĐĐĐ') + chalk.white('ĐĐĐĐĐĐĐ') + chalk.gray('Đ') + '\n' + s(opts.leftPadding) + chalk.gray(' Đ') + chalk.white('ĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐ') + chalk.gray('Đ') + '\n' + s(opts.leftPadding) + chalk.gray(' ĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐ') + '\n\n' } logo.toTTY = function (opts) { return process.stdout.write(logo(opts)) } module.exports = logo (function () { if (window.CNListsManager) return; window.CNListsManager = function (containerDiv, params) { this.ContainerDiv = typeof (containerDiv) == "object" ? containerDiv : document.getElementById(containerDiv); if (!this.ContainerDiv) return; params = params || {}; this.Interface = { ItemsArea: null }; this.Objects = { NodeTypeID: params.NodeTypeID, NodeType: params.NodeType, Lists: [] }; var that = this; GlobalUtilities.load_files(["API/CNAPI.js"], { OnLoad: function () { that._preinit(); } }); } CNListsManager.prototype = { _preinit: function () { var that = this; CNAPI.GetLists({ NodeTypeID: that.Objects.NodeTypeID, ParseResults: true, ResponseHandler: function (result) { that._initialize(GlobalUtilities.get_type(result) == "array" ? result : (result || {}).Lists || []); } }); }, _initialize: function (lists) { var that = this; that.ContainerDiv.innerHTML = ""; var elems = GlobalUtilities.create_nested_elements([ { Type: "div", Class: "small-12 medium-12 large-12", Style: "text-align:center; font-weight:bold;", Childs: [{ Type: "text", TextValue: RVDic.CN.NodeTypeComplexes.replace("[NodeType]", that.Objects.NodeType || RVDic.NodeType) }] }, { Type: "div", Class: "small-12 medium-12 large-12", Style: "margin-top:1rem;", Childs: [ { Type: "input", Class: "rv-input", Name: "_input", Style: "width:100%; font-size:0.7rem;", InnerTitle: RVDic.NewComplexName + "..." } ] }, { Type: "div", Class: "small-12 medium-12 large-12 rv-trim-vertical-margins", Style: "margin-top:1rem;", Name: "itemsArea" } ], that.ContainerDiv); that.Interface.ItemsArea = elems["itemsArea"]; GlobalUtilities.set_onenter(elems["_input"], function () { var listName = GlobalUtilities.trim(elems["_input"].value); elems["_input"].value = ""; if (!listName) return; CNAPI.AddComplex({ NodeTypeID: that.Objects.NodeTypeID, Name: Base64.encode(listName), ParseResults: true, ResponseHandler: function (result) { if (result.ErrorText) alert(RVDic.MSG[result.ErrorText] || result.ErrorText); else that.add_list(result.List); } }); }); for (var i = 0, lnt = (lists || []).length; i < lnt; ++i) that.add_list(lists[i]); }, add_list: function (list) { var that = this; if (!list) return; list.Name = Base64.decode(list.Name); that.Objects.Lists[list.ListID] = list; var create_button = function (p) { p = p || {}; return { Type: "i", Class: "fa " + p.Icon + " fa-lg rv-icon-button", Name: p.Name, Style: "margin-" + RV_RevFloat + ":0.5rem; cursor:pointer;", Tooltip: p.Tooltip, Attributes: [{ Name: "aria-hidden", Value: true }], Properties: !p.OnClick ? null : [{ Name: "onclick", Value: p.OnClick }] }; }; var elems = GlobalUtilities.create_nested_elements([ { Type: "div", Name: "containerDiv", Class: "small-12 medium-12 large-12 rv-border-radius-quarter rv-bg-color-trans-white SoftBorder", Style: "position:relative; padding:0.3rem; margin-bottom:0.3rem; padding-" + RV_Float + ":7rem;", Childs: [ { Type: "div", Style: "position:absolute; top:0.3rem;" + RV_Float + ":0.3rem;", Childs: [ create_button({ Icon: "fa-times", Tooltip: RVDic.Remove, OnClick: function () { that.remove_list(list.ListID, elems["containerDiv"]); } }), create_button({ Icon: "fa-cubes", Tooltip: RVDic.ComplexNodes, OnClick: function () { that.manage_list_nodes(list.ListID); } }), create_button({ Icon: "fa-user", Tooltip: RVDic.Managers, OnClick: function () { that.manage_admins(list.ListID); } }), create_button({ Icon: "fa-pencil", Tooltip: RVDic.Edit, Name: "editButton" }) ] }, { Type: "div", Class: "small-12 medium-12 large-12", Name: "viewArea" }, { Type: "div", Class: "small-12 medium-12 large-12", Style: "display:none;", Name: "editArea", Childs: [ { Type: "input", Class: "rv-input", Name: "titleInput", Style: "width:100%; font-size:0.7rem;" } ] } ] } ], that.Interface.ItemsArea); var viewArea = elems["viewArea"]; var editArea = elems["editArea"]; var editButton = elems["editButton"]; var titleInput = elems["titleInput"]; var _set_data = function () { GlobalUtilities.set_text(viewArea, GlobalUtilities.convert_numbers_to_persian(GlobalUtilities.secure_string(list.Name))); titleInput.value = list.Name; }; var _on_edit = function () { var set_things = function () { editArea.style.display = editButton.__Editing ? "block" : "none"; viewArea.style.display = editButton.__Editing ? "none" : "block"; _set_data(); editButton.setAttribute("class", "fa " + (editButton.__Editing ? "fa-floppy-o" : "fa-pencil") + " fa-lg rv-icon-button"); GlobalUtilities.append_tooltip(editButton, editButton.__Editing ? RVDic.Save : RVDic.Edit); }; if (editButton.__Editing === true) { var newName = GlobalUtilities.trim(titleInput.value); if (!newName) return alert(RVDic.Checks.NCannotBeEmpty.replace("[n]", RVDic.Title)); GlobalUtilities.block(elems["containerDiv"]); CNAPI.ModifyComplex({ ListID: list.ListID, Name: Base64.encode(newName), ParseResults: true, ResponseHandler: function (result) { if (result.ErrorText) alert(RVDic.MSG[result.ErrorText] || result.ErrorText); else { list.Name = newName; editButton.__Editing = false; set_things(); } GlobalUtilities.unblock(elems["containerDiv"]); } }); } else editButton.__Editing = true; set_things(); }; //end of _on_edit editButton.onclick = _on_edit; _set_data(); }, remove_list: function (listId, containerDiv) { var that = this; GlobalUtilities.confirm(RVDic.Confirms.DoYouWantToRemoveTheComplex, function (result) { if (!result) return; CNAPI.RemoveComplex({ ListID: listId, ParseResults: true, ResponseHandler: function (result) { if (result.ErrorText) alert(RVDic.MSG[result.ErrorText] || result.ErrorText); else { that.Objects.Lists[listId] = null; containerDiv.parentNode.removeChild(containerDiv); } } }); }); }, manage_admins: function (listId) { var that = this; var _name = RVDic.CN.NodeTypeComplexAdmins.replace("[Name]", that.Objects.Lists[listId].Name) .replace("[NodeType]", that.Objects.NodeType || RVDic.NodeType); _name = GlobalUtilities.secure_string(_name); that.__ComplexAdmins = that.__ComplexAdmins || {}; if (that.__ComplexAdmins[listId]) { GlobalUtilities.set_text(that.__ComplexAdmins[listId].Title, _name); return GlobalUtilities.show(that.__ComplexAdmins[listId].Container); } that.__ComplexAdmins[listId] = { Container: null, Title: null }; var elems = GlobalUtilities.create_nested_elements([ { Type: "div", Class: "small-10 medium-9 large-8 rv-border-radius-1 SoftBackgroundColor", Style: "margin:0rem auto; padding:1rem;", Name: "container", Childs: [ { Type: "div", Name: "_title", Style: "font-weight:bold; text-align:center; margin-bottom:1rem;", Childs: [{ Type: "text", TextValue: _name }] }, { Type: "div", Class: "small-12 medium-12 large-12", Name: "content" } ] } ]); that.__ComplexAdmins[listId].Container = elems["container"]; that.__ComplexAdmins[listId].Title = elems["_title"]; var contentDiv = elems["content"]; GlobalUtilities.loading(contentDiv); GlobalUtilities.show(that.__ComplexAdmins[listId].Container); GlobalUtilities.load_files([{ Root: "API/", Ext: "js", Childs: ["CNAPI"] }, "USR/RelatedUsersManager.js"], { OnLoad: function () { new RelatedUsersManager(contentDiv, { Options: { Editable: true, Title: null, TitleStyle: "margin:0px;", ItemsAreaStyle: "margin-top:8px;", RemoveConfirm: RVDic.Confirms.DoYouWantToRemoveTheComplexAdmin, OnBeforeUsersGet: function (e, done) { e.preventDefault(); CNAPI.GetComplexAdmins({ ListID: listId, ParseResults: true, ResponseHandler: function (result) { done(result.Users); } }); }, OnBeforeAdd: function (e, done) { e.preventDefault(); CNAPI.AddComplexAdmin({ ListID: listId, UserID: e.User.UserID, ParseResults: true, ResponseHandler: function (result) { if (result.ErrorText) alert(RVDic.MSG[result.ErrorText] || result.ErrorText); else done(result.User); } }); }, OnBeforeRemove: function (e, done) { e.preventDefault(); CNAPI.RemoveComplexAdmin({ ListID: listId, UserID: e.User.UserID, ParseResults: true, ResponseHandler: function (result) { if (result.ErrorText) alert(RVDic.MSG[result.ErrorText] || result.ErrorText); else done(); } }); } } }); } }); }, manage_list_nodes: function (listId) { var that = this; var _name = RVDic.CN.NodeTypeComplexNodes.replace("[Name]", that.Objects.Lists[listId].Name) .replace("[NodeType]", that.Objects.NodeType || RVDic.NodeType); _name = GlobalUtilities.secure_string(_name); that.__ComplexNodes = that.__ComplexNodes || {}; if (that.__ComplexNodes[listId]) { GlobalUtilities.set_text(that.__ComplexAdmins[listId].Title, _name); return GlobalUtilities.show(that.__ComplexNodes[listId].Container); } that.__ComplexNodes[listId] = { Container: null, Title: null }; var elems = GlobalUtilities.create_nested_elements([ { Type: "div", Class: "small-10 medium-9 large-8 rv-border-radius-1 SoftBackgroundColor", Style: "margin:0rem auto; padding:1rem;", Name: "container", Childs: [ { Type: "div", Name: "_title", Style: "font-weight:bold; text-align:center; margin-bottom:1rem;", Childs: [{ Type: "text", TextValue: _name }] }, { Type: "div", Class: "small-12 medium-12 large-12", Name: "content" } ] } ]); that.__ComplexNodes[listId].Container = elems["container"]; that.__ComplexNodes[listId].Title = elems["_title"]; var contentDiv = elems["content"]; GlobalUtilities.loading(contentDiv); GlobalUtilities.show(that.__ComplexNodes[listId].Container); GlobalUtilities.load_files([{ Root: "API/", Ext: "js", Childs: ["CNAPI"] }, "CN/ListNodesManager.js"], { OnLoad: function () { new ListNodesManager(contentDiv, { ListID: listId, NodeTypeID: that.Objects.NodeTypeID, NodeType: that.Objects.NodeType, Options: { Editable: true } }); } }); } } })();const app = require('@arkecosystem/core-container') const appHelper = require('@arkecosystem/core-test-utils/lib/helpers/container') jest.setTimeout(30000) exports.setUp = async () => { await appHelper.setUp({ exit: '@arkecosystem/core-blockchain', exclude: ['@arkecosystem/core-transaction-pool-mem'], }) } exports.tearDown = async () => { await app.tearDown() } /** * @file KDElemStats.js * @author <NAME> * @copyright <NAME> 2020 * @license MIT * @fileoverview Functions for calculating mean, median, modes, and * standard deviation of a `number[]`. */ import { KDNumber } from './KDNumber'; /** * Holds functions for calculating mean, median, mode, and standard * deviation of an array of numbers. */ export const KDElemstats = { /** * Calculate the statistical mean of an `Array<number>`. * @param {number[]} arr - The array on which to operate. * @returns {number} */ mean: (arr) => { const sum = arr.reduce((previous, current) => (current += previous)); return KDNumber.floatingPointFix(sum / arr.length); }, /** * Calculate the statistical median of an `Array<number>`. * @param {number[]} arr - The array on which to operate. * @returns {number} */ median: (arr) => { arr.sort((a, b) => a - b); const median = (arr[(arr.length - 1) >> 1] + arr[arr.length >> 1]) / 2; return KDNumber.floatingPointFix(median); }, /** * Calculate the statistical modes of an `Array<number>`. * @param {number[]} arr - The array on which to operate. * @returns {number} */ modes: (arr) => { const modes = []; const counts = []; let max = 0; arr.forEach((number) => { counts[number] = (counts[number] || 0) + 1; if (counts[number] > max) max = counts[number]; }); counts.forEach((count, index) => { if (count === max) modes.push(KDNumber.floatingPointFix(index)); }); return modes; }, /** * Calculate the standard deviation of an `Array<number>`. * @param {number[]} arr - The array on which to operate. * @returns {number} Return is normalized (0-1). */ stdDev: (arr) => { const fix = KDNumber.floatingPointFix; const avg = KDElemstats.mean(arr); const sqDiffs = arr.map((value) => fix(fix(value - avg) * fix(value - avg)) ); const avgSqRt = fix(Math.sqrt(KDElemstats.mean(sqDiffs))); const stdDev = KDNumber.scale(avgSqRt, [0, Math.max(...arr)], [0, 1]); return stdDev; }, }; <reponame>nexmo-community/diease-information-service<filename>models/commands.js // How to modify for own use: // // Add commands to the constants file and then add the // command execution in the switch statement. For cases, // fromNumber and toNumber should be passed to know where // to send the SMS, source is the url to be parsed for // data, and country is the specified country to look for. // // Note: This code does not feature every country and sources used // may not be completely accurate. const fetch = require('node-fetch'), JSSoup = require('jssoup').default, config = require('../config/config'), Sms = require('./sms'), Cases = require('./cases'), // K represents constant variables K = require('../utilities/constants'), sources = require('../utilities/sources'); // This class handles various SMS commands. If the sender's // message matches any of the commands in the switch // statements, the statements following would be executed, // otherwise the console will display that the message was // not a valid command. class Commands { static sendSms({ fromNumber, toNumber, command } = {}) { let message = ''; switch (command) { case K.commands.cmd: // Sends a list of commands available. message = ''; // Gets all key values in the K variable and adds them into // the message variable. Object.keys(K).map(function(key, index) { if (index < Object.keys(K).length - 1) { message += `${K[key].desc}\n\n`; } else { message += `${K[key].desc}`; } }); // Send the list of commands Sms.sendSms({ fromNumber, toNumber, message }); break; case K.cases.cmd: message = K.cases.info; Sms.sendSms({ fromNumber, toNumber, message }); break; case K.cases.countries.UnitedKingdom.cmd: Cases.sendSms({ fromNumber, toNumber, source: K.cases.countries.UnitedKingdom.source, country: 'United Kingdom' }); break; case K.cases.countries.UnitedStates.cmd: Cases.sendSms({ fromNumber, toNumber, source: K.cases.countries.UnitedStates.source, country: 'United States' }); break; case K.cleanHands.cmd: message = K.cleanHands.info; Sms.sendSms({ fromNumber, toNumber, message }); break; case K.washHands.cmd: message = K.washHands.info; Sms.sendSms({ fromNumber, toNumber, message }); break; default: console.log(`${command} is not a valid command.`); break; } } } module.exports = Commands; import block from './component'; export default { type: 'component', install(Vue) { Vue.component(`ams-block-${this.type}`, block); } }; <filename>servestutil.js import { createApp } from "https://servestjs.org/@v1.1.9/mod.ts"; const resHTML = async (req, html) => { await req.respond({ status: 200, headers: new Headers({ "Content-Type": "text/html" }), body: html, }); }; const resJSON = async (req, data, alloworigin) => { const headers = new Headers({ "Content-Type": "application/json; charset=utf-8", "Access-Control-Allow-Headers": "Content-Type, Accept", }); if (!alloworigin) { headers.set("Access-Control-Allow-Origin", "*"); } else { headers.set("Access-Control-Allow-Origin", alloworigin); headers.set("Vary", "Origin"); } await req.respond({ status: 200, headers, body: JSON.stringify(data) }); }; const resText = async (req, text) => { await req.respond({ status: 200, headers: new Headers({ "Content-Type": "text/plain" }), body: html, }); }; const resJPG = async (req, bin) => { await req.respond({ status: 200, headers: new Headers({ "Content-Type": "image/jpeg" }), body: bin, }); }; const resTempRedirect = async (req, url) => { await req.respond({ status: 307, // Temporary Redirect headers: new Headers({ "Location": url, }), }); }; // handle const handleJSON = async (req, api, alloworigin) => { // async api(path, json) if (req.method === "OPTIONS") { await resJSON(req, "ok", alloworigin); return; } try { const json = await (async () => { if (req.method === "POST") { return await req.json(); } else if (req.method === "GET") { const n = req.url.indexOf("?"); if (n >= 0) { const sjson = decodeURIComponent(req.url.substring(n + 1)); try { return JSON.parse(sjson); } catch (e) { return sjson; } } } return null; })(); console.log("[req api]", json); const res = await api(req.path, json); console.log("[res api]", res); await resJSON(req, res, alloworigin); } catch (e) { console.log("err", e.stack); } }; // file const readJSON = async (fn, defaultdata) => { try { return JSON.parse(await Deno.readTextFile(fn)); } catch (e) { return defaultdata; } }; const writeJSON = async (fn, data) => { await Deno.writeTextFile(fn, JSON.stringify(data)); }; // deno http const getHeaders = (headers) => { const res = {}; for (const name of headers.keys()) { res[name] = headers.get(name); } return res; } export { createApp, resHTML, resJSON, resText, resJPG, resTempRedirect, handleJSON, readJSON, writeJSON, getHeaders }; <filename>api/task.js const express = require('express'); const taskModel = require('../db/task'); const router = express.Router(); function checkAuth(req, res, next) { if (!req.user) { return res.sendStatus(403); } return next(); } router.get('/tasks', checkAuth, (req, res) => { return res.json(taskModel.find(req.user.id)); }); router.post('/tasks', checkAuth, (req, res) => { return res.json(taskModel.refresh(req.user.id, req.body)); }); module.exports = router; import { Redirect } from '@reach/router' import React from 'react' import SEO from 'react-seo-component' import { useSiteMetadata } from '../hooks/use-site-metadata' import { ogImageUrl } from '../util/build-og-image-url' const Giveaway = () => { const { title, siteUrl, twitterUsername, authorName, siteLanguage, siteLocale, } = useSiteMetadata() return ( <> <SEO title={`Giveaway`} titleTemplate={title} description={`Win a Wes Bos Advanced React and GraphQL course worth $139, draws made every Monday, Wednesday and Friday throughout February 2021`} image={ogImageUrl( authorName, '<EMAIL>', `Wes Bos > Advanced React and GraphQL - Giveaway` )} pathname={siteUrl} siteLanguage={siteLanguage} siteLocale={siteLocale} twitterUsername={twitterUsername} /> <Redirect from={`/giveaway`} to={`/newsletter/`} noThrow /> </> ) } export default Giveaway <reponame>yangsong158/chiner<filename>src/app/main/HeaderTool.js import React, { useState, forwardRef, useImperativeHandle } from 'react'; import {FormatMessage, GroupIcon, Icon, SearchSuggest, Slider, NumberInput} from 'components'; import { SketchPicker } from 'react-color'; import numeral from 'numeral'; const GroupIconGroup = GroupIcon.GroupIconGroup; export default React.memo(forwardRef(({currentPrefix, close, iconClick, colorChange, openModal, activeTab, resize, sliderChange, dataSource, jumpPosition, jumpDetail}, ref) => { const [isCellSelected, setIsCellSelected] = useState(false); const [scaleNumber, setScaleNumber] = useState(1); const [colorState, setColor] = useState({ fontColor: 'rgba(0, 0, 0, 0.65)', fillColor: '#ACDAFC', }); useImperativeHandle(ref, () => { return { setScaleNumber, setIsCellSelected, }; }, []); const _colorChange = (key, value) => { setColor((pre) => { return { ...pre, [key]: value.hex, }; }); colorChange && colorChange(key, value); }; return <div className={`${currentPrefix}-head`}> <div className={`${currentPrefix}-head-logo`}> <div className={`${currentPrefix}-head-logo-opt`}> <span> <Icon type='fa-angle-left' onClick={close}/> </span> <span>{dataSource.name}</span> </div> </div> <GroupIconGroup> <GroupIcon dropType='icon' groupKey='save' title={FormatMessage.string({id: 'toolbar.save'})} icon='icon-bianzu2' onClick={iconClick} dropMenu={[ /*{ key: 'save', name: FormatMessage.string({id: 'toolbar.save'})},*/ { key: 'saveAs', name: FormatMessage.string({id: 'toolbar.saveAs'})}, ]}/> <GroupIcon title={FormatMessage.string({id: 'toolbar.undo'})} onClick={() => iconClick(null, 'undo')} icon='icon-bianzu4' disable={activeTab?.type !== 'diagram'} hoverTitle={activeTab?.type !== 'diagram' ? FormatMessage.string({id: 'toolbar.relationEnableTitle'}) : ''} /> <GroupIcon onClick={() => iconClick(null, 'redo')} title={FormatMessage.string({id: 'toolbar.redo'})} icon='icon-bianzu3' disable={activeTab?.type !== 'diagram'} hoverTitle={activeTab?.type !== 'diagram' ? FormatMessage.string({id: 'toolbar.relationEnableTitle'}) : ''} /> {/* eslint-disable-next-line max-len */} {/*<GroupIcon title={FormatMessage.string({id: 'toolbar.opt'})} icon='opt.svg' dropMenu={[]}/>*/} </GroupIconGroup> <GroupIconGroup> <GroupIcon hoverTitle={activeTab?.type !== 'diagram' ? FormatMessage.string({id: 'toolbar.relationEnableTitle'}) : ''} title={FormatMessage.string({id: 'toolbar.emptyEntity'})} icon='icon-kongbiao' disable={activeTab?.type !== 'diagram'} style={{cursor: 'move'}} onMouseDown={e => iconClick(e, 'empty')} /> <GroupIcon className={`${currentPrefix}-head-db`} hoverTitle={activeTab?.type !== 'diagram' ? FormatMessage.string({id: 'toolbar.relationEnableTitle'}) : ''} title={FormatMessage.string({id: 'toolbar.group'})} icon='fa-object-group' style={{cursor: 'move'}} disable={activeTab?.type !== 'diagram'} onMouseDown={e => iconClick(e, 'group')} /> <GroupIcon hoverTitle={activeTab?.type !== 'diagram' ? FormatMessage.string({id: 'toolbar.relationEnableTitle'}) : ''} title={FormatMessage.string({id: 'toolbar.rect'})} style={{cursor: 'move'}} icon={<div className={`${currentPrefix}-head-rect`}> <span>{}</span> </div>} disable={activeTab?.type !== 'diagram'} onMouseDown={e => iconClick(e, 'rect')} /> <GroupIcon hoverTitle={activeTab?.type !== 'diagram' ? FormatMessage.string({id: 'toolbar.relationEnableTitle'}) : ''} title={FormatMessage.string({id: 'toolbar.round'})} style={{cursor: 'move'}} icon={<div className={`${currentPrefix}-head-rect`}> <Icon type='fa-square-o'/> </div>} disable={activeTab?.type !== 'diagram'} onMouseDown={e => iconClick(e, 'round')} /> <GroupIcon hoverTitle={activeTab?.type !== 'diagram' ? FormatMessage.string({id: 'toolbar.relationEnableTitle'}) : ''} title={FormatMessage.string({id: 'toolbar.fontColor'})} icon={<div className={`${currentPrefix}-head-font`}> <span><Icon type='icon-zitiyanse'/></span> </div>} dropMenuStyle={{ left: -59, top: 53, }} dropMenu={<SketchPicker disableAlpha presetColors={['#FFFFFF', '#BFBFBF', '#C00000', '#FFC000', '#F6941D', '#7030A0', '#136534', '#0070C0', '#0D0D0D','#6698CC', '#FA5A5A', '#FFD966', '#F8CBAD', '#CB99C5', '#9ACC98', '#093299']} color={colorState.fontColor} onChange={color => _colorChange('fontColor', color)} />} disable={activeTab?.type !== 'diagram' || !isCellSelected} /> <GroupIcon hoverTitle={activeTab?.type !== 'diagram' ? FormatMessage.string({id: 'toolbar.relationEnableTitle'}) : ''} title={FormatMessage.string({id: 'toolbar.fillColor'})} icon='icon-tianchongyanse' dropMenuStyle={{ left: -59, top: 53, }} dropMenu={<SketchPicker disableAlpha presetColors={['#FFFFFF', '#BFBFBF', '#C00000', '#FFC000', '#F6941D', '#7030A0', '#136534', '#0070C0', '#0D0D0D','#6698CC', '#FA5A5A', '#FFD966', '#F8CBAD', '#CB99C5', '#9ACC98', '#093299']} color={colorState.fillColor} onChange={color => _colorChange('fillColor', color)} />} disable={activeTab?.type !== 'diagram' || !isCellSelected} /> </GroupIconGroup> <GroupIconGroup> <GroupIcon hoverTitle={activeTab?.type !== 'diagram' ? FormatMessage.string({id: 'toolbar.relationEnableTitle'}) : ''} disable={activeTab?.type !== 'diagram'} title={FormatMessage.string({id: 'toolbar.scale'})} icon={<> <span className={`${currentPrefix}-head-scale ${currentPrefix}-head-scale-${activeTab?.type !== 'diagram' ? 'disable' : 'normal'}`}> <Icon type='fa-minus' onClick={() => resize(-0.1)}/> <span> <NumberInput readOnly={activeTab?.type !== 'diagram'} onBlur={e => sliderChange(numeral(e.target.value).divide(2).value())} min={0} max={200} value={parseInt(numeral(scaleNumber).multiply(100).value(), 10)} formatter={value => `${value}%`} parser={value => value.replace('%', '')} /> </span> <Icon type='fa-plus ' onClick={() => resize(0.1)}/> </span> <div> <Slider disable={activeTab?.type !== 'diagram'} onChange={sliderChange} value={numeral(scaleNumber).multiply(50).value()}/> </div> </>} /> <GroupIcon title={FormatMessage.string({id: 'toolbar.import'})} onClick={iconClick} icon={<Icon type='icon-daoru'/>} dropMenu={[ { key: 'pdman', name: FormatMessage.string({id: 'toolbar.importPDMan'}) }, { key: 'powerdesigner', name: FormatMessage.string({id: 'toolbar.importPowerDesigner'}) }, { key: 'db', name: FormatMessage.string({id: 'toolbar.importDb'}) }, ]} /> <GroupIcon onClick={iconClick} title={FormatMessage.string({id: 'toolbar.export'})} icon={<Icon type='icon-daochu'/>} dropMenu={[ {key: 'word', name: FormatMessage.string({id: 'toolbar.exportWord'})}, {key: 'sql', name: FormatMessage.string({id: 'toolbar.exportSql'})}, { key: 'img', name: FormatMessage.string({id: 'toolbar.exportImg'}), disable: activeTab?.type !== 'diagram', }, ]} /> <GroupIcon title={FormatMessage.string({id: 'toolbar.setting'})} icon='icon-shezhi' onClick={() => openModal('config')}/> <GroupIcon className={`${currentPrefix}-head-db`} title={FormatMessage.string({id: 'toolbar.dbConnect'})} icon='fa-database' onClick={() => openModal('dbConnect')}/> </GroupIconGroup> <div className={`${currentPrefix}-head-search`}> <SearchSuggest jumpPosition={jumpPosition} jumpDetail={jumpDetail} placeholder={FormatMessage.string({id: 'toolbar.search'})} dataSource={dataSource} /> </div> </div>; })); import templates from './templates' import fulfillments from './fulfillments' import toFacebook from './facebook_out' // import intrans from 'transformer/dialog-ui/dialogflow_in.js' reqHandler(async ({ parsedBody = {}, event, req }) => { let response = {} if (toChange) { toChange.forEach(param => { context[param] = '' }) response = { followupEvent: { name: parentAction, context } } } else if (action) { if (fulfillments[action]) { const { res, templateName = action, followupEvent, outputContext, profileUpdate // end_interaction, // session_entity_types } = await fulfillments[action]({ context, queryText, raw, event, slots, profile, confidence, parentAction, payload }) response.outputContext = outputContext response.profileUpdate = profileUpdate if (followupEvent) { response.followupEvent = followupEvent } else { response.fulfillmentMessages = await templates({ context, slots, confidence, profile, payload, templateName, parentAction, res }) } } else { response.fulfillmentMessages = await templates({ context, profile, slots, confidence, payload, templateName: action, parentAction }) } response.fulfillmentMessages = response.fulfillmentMessages ? response.fulfillmentMessages.map(toFacebook) : undefined } else { // fallback to default fullfillment messages response = { fulfillmentMessages } } const newResponse = new Response(JSON.stringify(response), { status: 200, statusText: 'OK', headers: { 'content-type': 'application/json' } }) return newResponse }) // @vendors import React from 'react' import '@testing-library/jest-dom/extend-expect' import { render, fireEvent } from '@testing-library/react' // @components import ControlPanel from './' // @testing test('testing ControlPanel component functionalities', () => { const onCommandTextMocked = jest.fn() const onSynonymousMocked = jest.fn() const component = render( <ControlPanel onSynonymous={onSynonymousMocked} onCommandText={onCommandTextMocked} /> ) const buttonCommand = component.getByText('B') fireEvent.click(buttonCommand.parentElement) expect(onCommandTextMocked).toBeCalledTimes(1) fireEvent.click(buttonCommand.parentElement) expect(onCommandTextMocked).toBeCalledTimes(2) const buttonSyn = component.getByText('Synonymous') fireEvent.click(buttonSyn.parentElement) expect(onSynonymousMocked).toHaveBeenCalled() }) import React, {Component} from "react"; import {Route, Switch, withRouter} from "react-router-dom"; import "./App.css"; import logo from "./Content/travlr02.jpg"; import Login from "./Components/Login"; import Signup from "./Components/Signup"; import Navbar from "./Components/Navbar"; import TripContainer from "./Components/TripContainer"; import CityShow from "./Components/CityShow"; class App extends Component { clickHandler = () => { localStorage.clear(); this.props.history.push("/login"); }; checkAuth = () => { if (localStorage.getItem("accessToken")) { return <TripContainer />; } else { return <Login />; } }; checkAuthSignUp = () => { if (localStorage.getItem("accessToken")) { return <TripContainer />; } else { return <Signup />; } }; checkAuthTrips = () => { if (localStorage.getItem("accessToken")) { return <TripContainer />; } else { return <Login />; } }; checkAuthTripsID = () => { if (localStorage.getItem("accessToken")) { return <CityShow />; } else { return <Login />; } }; render() { return ( <> <Navbar clickHandler={this.clickHandler} /> <div className="App"> <br /> <img className="animated zoomInLeft fade delay-2s" src={logo} alt="logo" /> <br /> <br /> <Switch> <Route exact path="/signup" render={() => this.checkAuthSignUp()} /> <Route path="/cities/:id" render={() => this.checkAuthTripsID()} /> <Route path="/trips" render={() => this.checkAuthTrips()} /> <Route path="/" render={() => this.checkAuth()} /> </Switch> </div> </> ); } } export default withRouter(App); ( function() { 'use strict'; describe( 'iscWidget component', function() { var suite; var sampleWidget = { templates : ['table'], sources : [{ type: 'Allergy', properties: [{ name: 'name', path: 'path' }] }, { type: 'Devices', properties: [{ name: 'name', path: 'path' }] }], id : 2 }; var interval; useDefaultModules( 'iscBento', 'api', 'fhir' ); var html = "<isc-widget widget='{id:2}'></isc-widget>"; beforeEach( inject( function( $rootScope, $compile, $httpBackend, api, widgetService, $q, $timeout, $interval ) { interval = jasmine.createSpy( 'interval', $interval ); suite = window.createSuite(); suite.$rootScope = $rootScope; suite.$httpBackend = $httpBackend; suite.api = api; suite.$timeout = $timeout; suite.widgetService = widgetService; suite.$scope = $rootScope.$new(); suite.element = $compile( html )( suite.$scope ); suite.$httpBackend.when( 'GET', /.html$/ ) .respond( 200, {} ); suite.$scope.$digest(); suite.$isolateScope = suite.element.isolateScope(); suite.ctrl = suite.$isolateScope.widgetCtrl; suite.ctrl.widget = angular.copy( sampleWidget ); suite.deferred = $q.defer(); suite.ctrl.patient = { id : 1 }; suite.ctrl.params = {}; } ) ); describe( 'set setup', function() { it( 'should have right dependencies', function() { expect( suite.$rootScope ).toBeDefined(); expect( suite.$scope ).toBeDefined(); expect( suite.element ).toBeDefined(); expect( suite.$isolateScope ).toBeDefined(); expect( suite.ctrl ).toBeDefined(); } ); } ); describe( 'init function', function() { it( 'should call getData and getOptions if no properties', function() { spyOn( suite.ctrl, 'getData' ); spyOn( suite.ctrl, 'makeConfig' ); suite.ctrl.data = null; suite.ctrl.$onInit(); expect( suite.ctrl.widget ).toBeDefined(); expect( suite.ctrl.loading ).toBeTruthy(); expect( suite.ctrl.getData ).toHaveBeenCalled(); expect( suite.ctrl.makeConfig ).toHaveBeenCalled(); } ); it( 'should call getData and makeConfig if properties exist', function() { spyOn( suite.ctrl, 'getData' ); spyOn( suite.ctrl, 'makeConfig' ); suite.ctrl.widget.sources = [{ type : 'me' }]; suite.ctrl.data = null; suite.ctrl.$onInit(); expect( suite.ctrl.widget ).toBeDefined(); expect( suite.ctrl.getData ).toHaveBeenCalled(); expect( suite.ctrl.makeConfig ).toHaveBeenCalled(); } ); } ); describe( 'deleteWidget function', function() { it( 'should emit event', function() { spyOn( suite.$rootScope, '$emit' ); suite.ctrl.deleteWidget(); expect( suite.$rootScope.$emit ).toHaveBeenCalledWith( 'deleteWidget', 2 ); } ); } ); describe( 'changeConfiguration function', function() { it( 'should emit editWidget event', function() { spyOn( suite.$rootScope, '$emit' ); suite.ctrl.changeConfiguration( 0 ); expect( suite.$rootScope.$emit ).toHaveBeenCalledWith( 'editWidget', sampleWidget, 0, jasmine.any( Function ) ); } ); } ); describe( 'hideEmpty function', function() { it( 'should emit event', function() { spyOn( suite.$rootScope, '$emit' ); suite.ctrl.hideEmpty(); expect( suite.$rootScope.$emit ).toHaveBeenCalledWith( 'hideEmpty' ); } ); } ); describe( 'saveWidget function', function() { it( 'should emit event', function() { spyOn( suite.$rootScope, '$emit' ); suite.ctrl.saveWidget(); expect( suite.$rootScope.$emit ).toHaveBeenCalledWith( 'saveWidget', sampleWidget ); } ); } ); describe( 'getData function', function() { it( 'should call the api getAndCombine and then set noData to false if no data', function() { spyOn( suite.widgetService, 'getWidgetData' ).and.returnValue( suite.deferred.promise ); spyOn( suite.ctrl, 'startCounter' ); suite.deferred.resolve( [] ); suite.ctrl.getData( sampleWidget ); suite.$scope.$apply(); expect( suite.ctrl.data ).toEqual( [] ); expect( suite.ctrl.widget.noData ).toEqual( true ); expect( suite.ctrl.loading ).toEqual( false ); expect( suite.ctrl.startCounter ).not.toHaveBeenCalled(); } ); it( 'should call the api getAndCombine and then set noData to true if there is data', function() { spyOn( suite.widgetService, 'getWidgetData' ).and.returnValue( suite.deferred.promise ); spyOn( suite.ctrl, 'startCounter' ); suite.ctrl.params = { patient: 1 }; suite.deferred.resolve( ['combined'] ); suite.ctrl.getData( sampleWidget ); suite.$scope.$apply(); expect( suite.ctrl.data ).toEqual( ['combined'] ); expect( suite.ctrl.widget.noData ).toEqual( false ); expect( suite.ctrl.loading ).toEqual( false ); expect( suite.ctrl.startCounter ).toHaveBeenCalled(); } ); it( 'should get the series and reflow the chart if it is a chart', function() { var sampleChart = _.cloneDeep( sampleWidget ); sampleChart.templates = ['chart']; spyOn( suite.widgetService, 'getWidgetData' ).and.returnValue( suite.deferred.promise ); spyOn( suite.widgetService, 'getSeries' ); spyOn( suite.$isolateScope, '$on' ); suite.ctrl.params = { patient: 1 }; suite.deferred.resolve( ['combined'] ); suite.ctrl.getData( sampleChart ); suite.$scope.$apply(); expect( suite.widgetService.getSeries ).toHaveBeenCalled(); } ); } ); describe( 'startCounter function', function() { it( 'should call the checkTime function and set lastUpdated', function() { var today = moment( '2017-01-01' ).toDate(); var resolveTime = moment( '2017-01-01' ); jasmine.clock().mockDate( today ); spyOn( suite.ctrl, 'checkTime' ); suite.ctrl.startCounter( resolveTime ) ; expect( suite.ctrl.checkTime ).toHaveBeenCalledWith( resolveTime, 'a few seconds ago' ); expect( suite.ctrl.lastUpdated ).toEqual( 'a few seconds ago' ); } ); } ); describe( 'makeConfig function', function() { it( 'should call the compileTable function from the service if its a table', function() { spyOn( suite.widgetService, 'compileTable' ).and.returnValue( 'tableConfig' ); suite.ctrl.makeConfig( sampleWidget ); expect( suite.widgetService.compileTable ).toHaveBeenCalledWith( sampleWidget ); expect( suite.ctrl.config ).toEqual( 'tableConfig' ); } ); it( 'should call the compileChart function from the service if its a chart', function() { var sampleChart = _.cloneDeep( sampleWidget ); sampleChart.templates = ['chart']; spyOn( suite.widgetService, 'compileChart' ).and.returnValue( 'chartConfig' ); suite.ctrl.makeConfig( sampleChart ); expect( suite.widgetService.compileChart ).toHaveBeenCalledWith( sampleChart ); expect( suite.ctrl.config ).toEqual( 'chartConfig' ); expect( suite.ctrl.selectedDirective.type ).toEqual( 'chart' ); } ); } ); } ); } )(); <reponame>DannyvanderJagt/portfolio import React from 'react'; import Telescope from 'telescope'; import Config from '../../../portfolio.config'; class Title extends Telescope.Component{ render(){ let id = this.props.title.toLowerCase(); id = id.replace(' ', '-'); return ( <h1 id={id}> {this.props.title} <span className='description'> {this.props.description} </span> </h1> ); } }; export default Title;const setupMenu = require("../components/Menu"); const checkPullRequests = require("../notifications/notifications"); const ls = require("../storage/LocalStorage"); window.addEventListener("DOMContentLoaded", async () => { setupMenu(); }); import React from 'react'; const Greeting = () => { return <div>Hey There!</div>; }; export default Greeting;'use strict'; // Requiring each JS page to test const fizzBuzz = require('../code/Practice/fizzBuzz.js'); const findMissingValue = require('../code/Practice/findMissingValue.js'); const reverseWord = require('../code/Practice/reverseStringWord.js'); const isFib = require('../code/Practice/isFib.js'); // Practice Question on FizzBuzz describe('FizzBuzz challenge. Print integers 1 to N, but print “Fizz” if an integer is divisible by 3, “Buzz” if an integer is divisible by 5, and “FizzBuzz” if an integer is divisible by both 3 and 5', () => { it('returns 1 when given 1 as an argument', () => { expect(fizzBuzz(1)).toEqual([1]); }); it('returns an array of [1, 2] when divisible by 2', () => { expect(fizzBuzz(2)).toEqual([1, 2]); }); it('returns an array of [1, 2, "Fizz"] when divisible by 3', () => { expect(fizzBuzz(3)).toEqual([1, 2, "Fizz"]); }); it('returns an array of [1, 2, "Fizz", 4, "Buzz"] when divisible by 5', () => { expect(fizzBuzz(5)).toEqual([1, 2, "Fizz", 4, "Buzz"]); }); it('returns an array of [1, 2, "Fizz", 4, "Buzz", "Fizz"] when divisible by 6', () => { expect(fizzBuzz(6)).toEqual([1, 2, "Fizz", 4, "Buzz", "Fizz"]); }); it('returns an array of [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz"] when divisible by 10', () => { expect(fizzBuzz(10)).toEqual([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz"]); }); it('returns an array of [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"] when divisible by 15', () => { expect(fizzBuzz(15)).toEqual([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]); }); }); // Testing Missing Value in array challenge describe('Given a sorted array with integers from 1 to 10, there is one number missing. Find that number', () => { it('Finds missing number 4 in sorted array', () => { let array = [1, 2, 3, 5, 6, 7, 8, 9, 10]; expect(findMissingValue(array)).toEqual([4]); }) it('Finds missing number 9 in sorted array', () => { let array = [1, 2, 3, 4, 5, 6, 7, 8, 10]; expect(findMissingValue(array)).toEqual([9]); }) it('Finds both missing number 4, 9 in sorted array', () => { let array = [1, 2, 3, 5, 6, 7, 8, 10]; expect(findMissingValue(array)).toEqual([4, 9]); }) }) // Testing reverse string word describe('reverseWord', () => { it('can reverse a string by the word', () => { let string = 'Hello my name is'; expect(reverseWord(string)).toEqual('is name my Hello') }) }) // Testing if number is apart of Fibonacci sequence return true describe('isFib', () => { it('Will return true if number is apart of the scequence of isFib', () => { expect(isFib(8)).toBeTruthy(); }) });(function($) { 'use strict'; $(document).ready(function(){ var $buscaRapida = $('.dave-busca-rapida').find('input[type="text"]'); $buscaRapida.select2({ minimumInputLength: 3, ajax: { url: "/api/usuarios", dataType: 'json', quietMillis: 250, data: function (term) { return { search: term }; }, results: function (data, page) { return { results: data }; } }, formatResult: function (usuario) { var markup = '<h4 class="text-left"><i class="fa fa-user"></i> '+usuario.nome+'</h4>'; return markup; }, formatSelection: function (usuario) { return usuario.nome; } }).on('change', function() { window.location = '/usuarios/'+this.value+'/editar'; }); }); })(window.jQuery);<filename>src/config.js /* global __CONFIG__ */ export default __CONFIG__; const PlaylistVM = can.DefineMap.extend("PlaylistVM", { init: function() { const self = this; self.on("googleAuth", function(ev, googleAuth) { self.signedIn = googleAuth.isSignedIn.get(); googleAuth.isSignedIn.listen(function(isSignedIn) { self.signedIn = isSignedIn; }); }); }, googleApiLoadedPromise: { default: googleApiLoadedPromise }, googleAuth: { get: function(lastSet, resolve) { this.googleApiLoadedPromise.then(function() { resolve(gapi.auth2.getAuthInstance()); }); } }, signedIn: "boolean", get givenName() { return this.googleAuth && this.googleAuth.currentUser.get().getBasicProfile().getGivenName(); }, searchQuery: { type: "string", default: "" }, get searchResultsPromise() { if (this.searchQuery.length > 2) { const results = gapi.client.youtube.search.list({ q: this.searchQuery, part: "snippet", type: "video" }).then(function(response) { console.info("Search results:", response.result.items); return response.result.items; }); return new Promise(function(resolve, reject) { results.then(resolve, reject); }); } }, videoDrag: function(drag) { drag.ghost().addClass("ghost"); } }); can.addJQueryEvents(jQuery); const vm = new PlaylistVM(); const template = can.stache.from("app-template"); const fragment = template(vm); document.body.appendChild(fragment); module.exports = (() => { 'use strict'; const mocks = require('mocks'); const qs = require('querystring'); const path = require('path'); class EndpointRequest { constructor(app, path, params) { this.app = app; this._path = path + (params ? `?${qs.stringify(params)}` : ''); } mock(method, body, callback) { let request = new mocks.http.ServerRequest(); let response = new mocks.http.ServerResponse(); request.setHeader = (header, value) => request.headers[header] = value; request.url = path.resolve('localhost', this._path); request.method = method; request.connection = { destroy: () => {}, remoteAddress: '::1' }; if (typeof body === 'object' && body !== null) { request.setHeader('Content-Type', request.getHeader('Content-Type') || 'application/json; charset=utf-8'); mockData.body = JSON.stringify(body); } else if (body instanceof Buffer) { request.setHeader('Content-Type', request.getHeader('Content-Type') || 'application/octet-steam'); mockData.body = body; } else if (body) { request.setHeader('Content-Type', 'x-www-form-urlencoded'); } this.app.router.delegate(this.app, request, response); body && request.emit('data', body); response.on('end', () => { let json = null; try { json = JSON.parse(response._body); } catch (e) { json = null; } callback(response._status, response._headers, response._body, json); }); setTimeout(() => request.emit('end'), 1); } get(callback) { this.mock('GET', null, callback); } del(callback) { this.mock('DELETE', null, callback); } post(body, callback) { this.mock('POST', body, callback); } put(body, callback) { this.mock('PUT', body, callback); } } return EndpointRequest; })(); <filename>src/plugins/myItems/createMyItemsIdentifier.js<gh_stars>1000+ export const MY_ITEMS_KEY = 'mine'; export function createMyItemsIdentifier(namespace = '') { return { key: MY_ITEMS_KEY, namespace }; } /*global module, exports*/ (function () { var hasOwnProperty = Object.prototype.hasOwnProperty; //these constructs contain variable scope (technically, there's catch scope and ES6 let) var SCOPE_TYPES = { FunctionDeclaration: 1, FunctionExpression: 1, Program: 1, }; //these have special meaning in PHP so we escape variables with these names var SUPER_GLOBALS = { GLOBALS: 1, _SERVER: 1, _GET: 1, _POST: 1, _FILES: 1, _COOKIE: 1, _SESSION: 1, _REQUEST: 1, _ENV: 1, }; // table of character substitutions var ESC_CHARS = { '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', $: '\\$', '\\': '\\\\', }; function toHex(code, prefix) { var hex = code.toString(16).toUpperCase(); if (hex.length === 1) { hex = '0' + hex; } if (prefix) { hex = prefix + hex; } return hex; } function toOctet(codePoint, shift, prefix) { return toHex(((codePoint >> shift) & 0x3f) | 0x80, prefix); } //encode unicode character to a set of escaped octets like \xC2\xA9 function encodeChar(ch, prefix) { var code = ch.charCodeAt(0); if ((code & 0xffffff80) == 0) { // 1-byte sequence return toHex(code, prefix); } var result = ''; if ((code & 0xfffff800) == 0) { // 2-byte sequence result = toHex(((code >> 6) & 0x1f) | 0xc0, prefix); } else if ((code & 0xffff0000) == 0) { // 3-byte sequence result = toHex(((code >> 12) & 0x0f) | 0xe0, prefix); result += toOctet(code, 6, prefix); } else if ((code & 0xffe00000) == 0) { // 4-byte sequence result = toHex(((code >> 18) & 0x07) | 0xf0, prefix); result += toOctet(code, 12, prefix); result += toOctet(code, 6, prefix); } result += toHex((code & 0x3f) | 0x80, prefix); return result; } function encodeString(string) { string = string.replace(/[\\"\$\x00-\x1F\u007F-\uFFFF]/g, function (ch) { return ch in ESC_CHARS ? ESC_CHARS[ch] : encodeChar(ch, '\\x'); }); return '"' + string + '"'; } function encodeVarName(name, suffix) { suffix = suffix || ''; if (!suffix && hasOwnProperty.call(SUPER_GLOBALS, name)) { suffix = '_'; } if (!suffix && name.slice(-1) === '_') { suffix = '_'; } name = name.replace(/[^a-z0-9_]/gi, function (ch) { return '«' + encodeChar(ch).toLowerCase() + '»'; }); return '$' + name + suffix; } function getParentScope(node) { var parent = node.parent; while (!(parent.type in SCOPE_TYPES)) { parent = parent.parent; } return parent.type === 'Program' ? parent : parent.body; } exports.encodeString = encodeString; exports.encodeVarName = encodeVarName; exports.getParentScope = getParentScope; })(); function TabModel() { this.thSel = ""; this.tbSel = ""; this.rowCount = 0; this.selCount = 0; } function eSelAll(tabModel) { initTabModel(tabModel); bindEvent(tabModel); } function initTabModel(tabModel) { tabModel.rowCount = $(tabModel.tbSel + " tr ").length; $.debug("initData rowCount: " + tabModel.rowCount); tabModel.selCount = $(tabModel.tbSel + " :checked ").length; $.debug("initData selCount: " + tabModel.selCount); } function bindEvent(tabModel) { $(tabModel.thSel).click(function () { $.debug("selAll click 前的selCount: " + tabModel.selCount); if ($(this).prop("checked")) { $(tbSel).prop("checked", true); tabModel.selCount = tabModel.rowCount; } else { $(tbSel).prop("checked", false); tabModel.selCount = 0; } $.debug("disAll click 后的selCount: " + tabModel.selCount); }); $(tabModel.tbSel).click(function () { $.debug("click 前的selCount: " + tabModel.selCount); if ($(this).prop("checked")) { $.debug($(this).prop("id") + "选中...."); tabModel.selCount++; if (tabModel.rowCount == tabModel.selCount) { $(thSel).prop("checked", true); } } else { $.debug($(this).prop("id") + "取消...."); tabModel.selCount--; if (tabModel.rowCount > tabModel.selCount) { $(thSel).prop("checked", false); } } ; $.debug("click 后的selCount: " + tabModel.selCount); }); } function a2t(tbsel, cloId, objs) { for (var i = 0; i < objs.length; i++) { var $lunRow = $(cloId).clone(true); $lunRow.attr("id", cloId + i); obj2rel($lunRow, objs[i]); $(tbsel).append($lunRow); $lunRow.show(); } } function obj2rel($tr, obj) { $tr.children("td").each(function (num, td) { if (!isEmpObj($(td).attr("name"))) { console.log($(td).attr("name")); if (isEmpObj(obj[$(td).attr("name")]) && obj[$(td).attr("name")] != false) { td.innerHTML = ""; td.title = ""; } else if ($(td).attr("name") == 'usedBy') { if (obj.usedType == "Datastore") { url = "../../../assets/images/Datastore.png"; td.innerHTML = "<img src=" + url + ">" + "  " + obj.usedBy; td.title = obj.usedBy; } else if (obj.usedType == "VirtualMachine") { url = "../../../assets/images/VirtualMachine.png"; td.innerHTML = "<img src=" + url + ">" + "  " + obj.usedBy; td.title = obj.usedBy; } else { td.innerHTML = obj.usedBy; td.title = obj.usedBy; } } else if ($(td).attr("name") == 'capacityUsage') { td.innerHTML = makeRateChart(obj.capacityUsage, $("#volCapUsage", parent.document)); td.title = "Total Capacity:" + obj.capacity + " Free Capacity: " + obj.capacity; } else if ($(td).attr("name") == 'storagePoolUsage') { td.innerHTML = makeRateChart(obj.storagePoolUsage , $("#poolCapUsage", parent.document)); td.title = "Total Capacity:" + obj.storagePoolCapactiy + " Free Capacity: " + obj.storagePoolFreeCap; } else if ($(td).attr("name") == 'status') { var status = obj.status; if (status.toLowerCase() == "normal") { url = "../../../assets/images/lun_status_normal.png"; td.innerHTML = "<img src=" + url + ">"+ "  " + status; td.title = status; } else if (status.toLowerCase() == "faulty") { url = "../../../assets/images/lun_status_unnormal.png"; td.innerHTML = "<img src=" + url + ">" + "  " + status; td.title = status; } else { } } else { td.innerHTML = obj[$(td).attr("name")]; td.title = td.innerHTML; } } }); } function t2a(tableId) { var objList = new Array(); $(tableId).find("tbody tr").each(function (nun, tr) { var length = $(tr).find(":checked").length; if (length > 0) { var obj = r2o(tr); objList.push(obj); } }); return objList; } function r2o(tr) { var obj = new Object(); $(tr).children("td").each( function (num, td) { if (!isEmpObj($(td).attr("name"))) { obj[$(td).attr("name")] = td.innerHTML; } }); return obj; }import React, { Component } from 'react' import classNames from 'classnames' import { removeNotification } from '../actions/notifications' class Notification extends Component { componentDidMount() { // Remove after some time if (this.props.delay > 0) { setTimeout(() => { this.props.onRemove(this.props.id); }, this.props.delay); } } render() { return ( <div className={classNames('pgn', 'pgn-' + this.props.style)}> <div className={classNames('alert', 'alert-' + this.props.type)}> {this.props.dismiss && <button onClick={() => this.props.onRemove(this.props.id)} className="close"> <span aria-hidden="true">×</span> <span className="sr-only">Zavřít</span> </button> } <span>{this.props.children}</span> </div> </div> ); } } Notification.propTypes = { id: React.PropTypes.number, delay: React.PropTypes.number, type: React.PropTypes.string, style: React.PropTypes.string, dismiss: React.PropTypes.bool, onRemove: React.PropTypes.func, children: React.PropTypes.any.isRequired }; Notification.defaultProps = { style: 'flip', type: 'success', dismiss: true, delay: 3000 }; export default Notificationvar _ = require('lodash'); var Q = require('q'); var log = require('./log'); var f = require('util').format; var chalk = require('chalk'); var db = require('./db')('codecollection'); var fs = require('fs'); var path = require('path'); var isBinaryFile = require('isbinaryfile'); // denodeify wasn't working here for some reason... // var readFile = Q.denodeify(fs.feadFile); var readFile = (function (fn) { return function (file, opts) { var deferred = Q.defer(); fn(file, opts, function (err, text) { if (err) return deferred.reject(err); deferred.resolve(text); }); return deferred.promise; }; })(fs.readFile); var isBinary = Q.denodeify(isBinaryFile); module.exports = function (folder, language) { log.info(f('Parsing %s...', chalk.yellow(folder))); walk(folder).then(function (files) { return Q.all(_.map(files, function (file) { return isBinary(file).then(function (isBin) { if (!isBin) return file; }); })).then(function (files) { // removes all binary files files = _.compact(files); return Q.all(_.map(files, function (file) { return readFile(file, 'utf-8').then(function (contents) { var entry = { language: language, ext: path.extname(file), filename: path.basename(file), code: contents.split("\n") }; // this is async, but we don't really need to wait db.save(entry); return entry; }, function (err) { // probably cuz it couldn't be opened, or // couldn't be opened as utf-8, which is fine! }); })); }); }).then(function(entries) { log.info(f('Parsed %s...', chalk.yellow(folder))); }).catch(function (err) { log.error(err.stack || err.message || err); process.exit(); }); // db.save(); return folder; }; // adapted from http://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search var walkAsync = function(dir, done) { if (dir[dir.length - 1] === '/') dir = dir.slice(0, dir.length - 1); var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var pending = list.length; if (!pending) return done(null, results); list.forEach(function(file) { file = dir + '/' + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { walk(file, function(err, res) { results = results.concat(res); if (!--pending) done(null, results); }); } else { results.push(file); if (!--pending) done(null, results); } }); }); }); }; var walk = Q.denodeify(walkAsync);// Discord bot invite link: https://discord.com/api/oauth2/authorize?client_id=959004457205637131&permissions=536988673&redirect_uri=http%3A%2F%2Fwww.theprojecthub.xyz%2Fdiscord&response_type=code&scope=identify%20bot%20applications.commands const path = require('path') const { Client, Intents } = require('discord.js') require('dotenv').config({ path: path.resolve(__dirname, '../.env') }) const { HandleCommand } = require('./CommandHandler') const { ChannelType } = require('discord-api-types/v10') const { Link } = require('./DiscordLinker') // token is the bots login credentials and needs to be kept confident const token = process.env.DISCORD_BOT_TOKEN const client = new Client({ intents: [Intents.FLAGS.GUILD_INVITES, Intents.FLAGS.GUILD_WEBHOOKS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILDS] }) client.on('interactionCreate', async interaction => { if (interaction.isCommand()) { await HandleCommand(interaction) } }) client.once('ready', () => { console.log('Discord Ready!') }) function StartBot () { try { require('./RegCommands') client.login(token) return client } catch (e) { console.log('failed to start bot: ' + e) } } async function LinkFromWeb (guildId) { await client.guilds.fetch() const guild = client.guilds.cache.get(guildId) await guild.channels.fetch() let channel = guild.channels.cache.filter(channel => channel.name.includes('general')).first() if (!channel) { channel = guild.channels.cache.filter(channel => channel.type === 'GUILD_TEXT').first() } return await Link(guild, channel) } module.exports = { StartBot, LinkFromWeb, client } // Create a new client instance (log into discord) // Intents(intentions/what do we wanna do): //https://discord.com/developers/docs/topics/gateway#list-of-intents import AsyncStorage from "@react-native-async-storage/async-storage"; import { applyMiddleware, createStore } from "redux"; import { composeWithDevTools } from "redux-devtools-extension"; import { persistStore, persistReducer } from "redux-persist"; import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2"; import thunk from "redux-thunk"; import reducer from "./rootReducer"; const persistConfig = { key: "root", storage: AsyncStorage, stateReconciler: autoMergeLevel2, debug: true, timeout: null, }; const pReducer = persistReducer(persistConfig, reducer); export const store = createStore( pReducer, composeWithDevTools(applyMiddleware(thunk)) ); export const persistor = persistStore(store); import React from 'react' import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './GoogleAd.css' class GoogleAd extends React.Component<IGoogleAd> { render() { return ( <div className={this.props.className}> <li className={`${s.LI_1}`}> <div className={s.DIV_2}> <a href="https://www.xfinity.com/learn/xfinity-internetplus-ned-nn" className={s.A_4} /> <h3 className={s.H3_5}> Xfinity® High Speed Internet | Limited Offer - $29.99/mo/1yr | xfinity.com‎ </h3><br className={s.BR_6} /> <div className={s.DIV_7}> <span className={s.SPAN_8}>Ad</span><cite className={s.CITE_9}>www.xfinity.com/Internet</cite>‎ </div> <div className={s.DIV_13}> </div> <div className={s.DIV_14}> <span className={s.SPAN_15}></span> </div> </div> <div className={s.DIV_16}> Get <b className={s.B_17}>Internet</b> Speeds You Want At A Price You'll Love. Sign Up With Xfinity Today! Fast <b className={s.B_18}>internet</b>. Norton™ security included. Millions of hotspots. Move service stress-free. Advanced security. Services: <b className={s.B_19}>Internet</b>, TV, Phone, WIFI Hotspots, X1 Entertainment System, Sports Packages. </div> </li> </div> ) } } export default withStyles(s)(GoogleAd) /** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Programación de Aplicaciones Interactivas 2021-2022 * * @author <NAME> * @author <NAME> * @since Apr 07 2022 * @desc This program emulates the use of the original code of a cart service * for a web * @see {@link https://github.com/ULL-ESIT-PAI-2021-2022/2021-2022-pai-design-patterns-pai-design-patterns} */ 'use strict'; import Cart from './original_cart'; /** This function exemplifies the use of the adapter pattern */ function main() { const myCart = new Cart(); const multiplication = myCart.operation(1, 2, 'multiplication'); console.log(`The multiplication: ${multiplication}`); const division = myCart.operation(10, 2, 'division'); console.log(`The division: ${division}`); } main(); //var util = require('util'); var SerialPort = require('serialport').SerialPort; var xbee_api = require('xbee-api'); var C = xbee_api.constants; var xbeeAPI = new xbee_api.XBeeAPI({ api_mode: 1 }); var serialport = new SerialPort("COM3", { baudrate: 38400, parser: xbeeAPI.rawParser() }); serialport.on("open", function() { var frame_obj = { // AT Request to be sent to type: C.FRAME_TYPE.AT_COMMAND, command: "NI", commandParameter: [], }; serialport.write(xbeeAPI.buildFrame(frame_obj)); }); // All frames parsed by the XBee will be emitted here xbeeAPI.on("frame_object", function(frame) { console.log(">>", frame); }); <filename>defaultSettings.js const ceta = require('./lib'); const cfgdir = new ceta.ConfigDir(); const path = require('path') module.exports = { modsetPath: path.join(cfgdir.platformPath(), 'Modsets'), nexusKey: 'NEXUS_API_KEY_HERE', gameDirectory: ceta.util.gameDir(true) } (function () { /** * Bind events from an XHR object to a Frumpy application * * @id Frumpy.xhr * @group plugins * @type Function * @param {Object} app - the Frumpy application to subscribe to XHR events * @return {Object} - a bound `XMLHttpRequest` object * @signal xhr:load an XHR request is completed, regardless of status * @signal xhr:error an XHR request failed to connect to the remote host * * var app = new Frumpy(state0, [ * [ 'xhr:load', [onXhrLoad] ], * [ 'xhr:error', [onXhrError] ] * ]); * * function onXhrLoad (model, req) { * console.log(req.status); * } * * function onXhrError (model, xhr) { * console.log('failed establishing connection'); * } * * var xhr = Frumpy.xhr(app); * xhr.open('post', '/items'); * xhr.send({ foo: 'bar' }); * */ Frumpy.xhr = function (app) { // Clean up handlers var unbind = function (req) { req.removeEventListener('load', _onLoad); req.removeEventListener('error', _onError); }; var _onError = function (evt) { var req = evt.target; unbind(req); app.trigger('xhr:error', evt.target); }; var _onLoad = function (evt) { var req = evt.target; unbind(req); app.trigger('xhr:load', evt.target); }; var request = new XMLHttpRequest(); request.addEventListener('load', _onLoad); request.addEventListener('error', _onError); return request; }; })(); // A palavra-chave this let user = { name: 'João', age:31, email:'<EMAIL>', city:'São Paulo', blogPosts: ['Empadão de frango', '4 receitas de purê de batata'], login: function () { console.log('Usuário logado') }, logout: function () { console.log('Usuário deslogado') // function declaration }, logBlogPosots () { // shortcut para function declaration. console.log(`${this.name} escreveu os seguintes posts:`) this.blogPosts.forEach( post => { console.log(post) }) // Objeto de contexto // não usar o arrow fuction ficar atento ao contexto } } user.login() user.logout() user.logBlogPosots()<reponame>ailabteam/Daily-Working<filename>GO-practices/blockchain/app_python/client/src/components/VisionDegree.js import React from 'react'; class VisionDegree extends React.Component { render() { const student = this.props.student; return ( <div className="vision-degree"> <h5 className="vision-degree__title">Chứng chỉ đại học bạn {student.studentName}</h5> <div className="vision-degree__content"> <h2>{student.studentName}</h2> <div className="vision-degree__content--info"> <p>{student.bornOn}</p> <p>{student.majoy}</p> <p>{student.ranking}</p> <p>{student.modeOfStudy}</p> </div> <div className="vision-degree__content--number"> <a id="serial-number" href="https://www.uit.edu.vn/tra-cuu/van-bang" target="_blank" rel="noopener noreferrer">{student.serialNumber}</a> <a id="reference-number">{student.referenceNumber}</a> </div> </div> </div> ); } } export default VisionDegree;<reponame>Merwer/merwer.github.io /*global jQuery*/ (function PersonalResume($) { "use strict"; var stageSelectJumpTarget; var stageFlashTimer; var flashTimeDuration = 150; // Experimental values based on trial & error var timeInWhite = flashTimeDuration / 7; var timeInLines = flashTimeDuration * (2 / 3); function jump(element, callback) { var start = element.offset(); var bezier_params = { start: { x: start.left, y: start.top }, end: { x: window.stageSelectJumpTarget.left, y: window.stageSelectJumpTarget.top } }; element.animate({ path: new $.path.bezier(bezier_params) }, 1000, 'linear', callback); } function resetSelectScreen(callback) { // Return to original screen $('div.lightblue .text').html(''); // Clear the text for next time $('.flashscreen').hide(); $('.main').show(); if (callback && typeof callback === 'function') { callback(); } } function writeText(text, callback) { // Update the text var p = text.clone(); p.css('margin', '0').css('display', 'none'); $('div.lightblue .text').append(p); p.fadeIn(1000); // TODO: Typewriter effect // Set up next click to return to previous page $('.flashscreen').one('click', function () { resetSelectScreen(callback); }); } function makeCopy(ele) { var pos = ele.offset(); var copy = ele.clone(); // Update the element to have an absolute top/left coordinates // in CSS so that the animations will work properly. copy.css('top', pos.top); copy.css('left', pos.left); copy.css('margin', 0); copy.css('position', 'absolute'); copy.appendTo('.flashscreen'); return copy; } function toggleFlashView() { $('.flashscreen').toggleClass('flashed'); } function stageFlash(toggle) { if (toggle) { $('.main').hide(); $('.flashscreen').show(); toggleFlashView(); window.stageFlashTimer = window.setInterval(toggleFlashView, flashTimeDuration); } else { $('.flashscreen').removeClass('flashed'); // Make sure we end on the lines window.clearInterval(window.stageFlashTimer); } } function stageSelected(source) { var divTarget = source.currentTarget; var img = $('.selectbox img', divTarget); var text = $('p.descriptivetext', divTarget); if (img === null || img === undefined || img.length === 0) { return; //TODO This is an error - handle it better } var copy = makeCopy(img); stageFlash(true); // Start the flashing $('.selectbox', divTarget).addClass('completed'); // Mark the element as being seen jump(copy, function () { stageFlash(false); writeText(text, function () { copy.remove(); }); }); } $(document).ready(function () { var targetImage = $('.main .row:nth-child(2) .selectbox img'); $('.stage').on('click', stageSelected); window.stageSelectJumpTarget = {}; window.stageSelectJumpTarget.left = targetImage.offset().left * 1.03; window.stageSelectJumpTarget.top = targetImage.offset().top + 10; $('.flashscreen').width($('.main').width()); $('.flashscreen').height($('.main').height()); }); }(jQuery));/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2021 Liberty Global B.V. * * 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 { Lightning } from '@lightningjs/sdk' import constants from './constants' import theme from '@/themes/default' import { getPlatformNiceName } from '@/services/RDKServices' export default class DeviceLabel extends Lightning.Component { static _template() { return { DeviceLabel: { x: constants.DEVICELABEL_LEFT, y: constants.DEVICELABEL_TOP, zIndex: constants.DEVICELABEL_ZINDEX } } } async _init() { this.tag('DeviceLabel').text = await getPlatformNiceName() } } import MyInfo from '../components/MyInfo.js' import { Grid } from 'react-bootstrap' import Portfolio from '../components/Portfolio.js'; import Layout from '../components/Shared/Layout.js'; const Index = () => <Layout> <div> <Grid> <MyInfo/> <Portfolio/> </Grid> </div> </Layout> export default Index<filename>data/js/00/50/c2/46/60/00.36.js macDetailCallback("0050c2466000/36",[{"a":"5 Fleet Place London GB EC4M 7RD","o":"LONAP Limited","d":"2008-07-30","t":"add","s":"ieee","c":"GB"}]); import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import {COMMON} from './constants' import theme from './theme' import sx from './sx' function IconWrapper({icon: IconComponent, className, ...rest}) { return <IconComponent className={className} {...rest} /> } const StyledOcticon = styled(IconWrapper)` ${COMMON} ${sx} ` StyledOcticon.defaultProps = { theme, size: 16, } StyledOcticon.propTypes = { ...COMMON.propTypes, ...sx.propTypes, icon: PropTypes.elementType.isRequired, size: PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['small', 'medium', 'large'])]), theme: PropTypes.object, verticalAlign: PropTypes.oneOf(['middle', 'text-bottom', 'text-top', 'top']), } export default StyledOcticon <reponame>ludicast/tower Tower.HTTP.Request = (function() { function Request(data) { if (data == null) data = {}; this.url = data.url; this.location = data.location; this.pathname = this.location.path; this.query = this.location.query; this.title = data.title; this.title || (this.title = typeof document !== "undefined" && document !== null ? document.title : void 0); this.body = data.body || {}; this.headers = data.headers || {}; this.method = data.method || "GET"; } return Request; })(); module.exports = Tower.HTTP.Request; var demand = require('must'); exports.initList = function (List) { List.add({ bool: Boolean, }); }; exports.getTestItems = function () { return [ { bool: undefined }, { bool: true }, { bool: false }, ]; }; exports.testFilters = function (List, filter) { it('should filter true values', function (done) { filter({ bool: { value: 'true', }, }, 'bool', function (results) { demand(results).eql([ true, ]); done(); }); }); it('should filter falsy values', function (done) { filter({ bool: { value: 'false', }, }, 'bool', function (results) { demand(results).eql([ false, false, ]); done(); }); }); }; const meta = { requiresAuth: true } export default { path: 'admin', name: 'admin', meta: { meta, title: '管理员' }, component: () => import('@/pages/admin'), children: (pre => [ { path: 'webconfig', name: `${pre}webconfig`, component: () => import('@/pages/admin/webconfig/index'), meta: { meta, title: '网站管理' }, children: (pre => [ { path: 'index1', name: `${pre}index1`, component: () => import('@/pages/admin/webconfig/index1'), meta: { meta, title: '网站配置' } } ])('admin-webconfig-') }, { path: 'usermanagement', name: `${pre}usermanagement`, component: () => import('@/pages/admin/usermanagement/index'), meta: { meta, title: '用户管理' }, children: (pre => [ { path: 'index1', name: `${pre}index1`, component: () => import('@/pages/admin/usermanagement/index1'), meta: { meta, title: '账号管理' } } ])('admin-usermanagement-') } ])('admin-') } var mongoose = require('mongoose'); var Schema = mongoose.Schema; var porta = new Schema({ porta: { type: Number, required: true, index: { unique: true, } }, apelido: { type: String, required: true }, estado: { type: Boolean, required: true }, ativo: { type: Boolean, required: true } }) var portaModelo = mongoose.model('porta', porta, 'portas'); module.exports = { portaModelo };<filename>src/pages/thanks.js<gh_stars>0 import React from "react" import { Link } from "gatsby" import Layout from "../components/layout" import SEO from "../components/seo" const SecondPage = props => ( <Layout location={props.location.pathname}> <SEO title="Thanks" /> Thank you! You should get your first email soon! <Link to="/">Go back to the homepage</Link> </Layout> ) export default SecondPage import Dropzone from 'dropzone/dist/min/dropzone.min'; Dropzone.autoDiscover = false; const IE = navigator.appName == 'Microsoft Internet Explorer' || !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie == 1); const dropzoneFields = document.querySelectorAll('.field.dropzone-field'); for (let dropzoneField of dropzoneFields) { if (!IE ) { dropzoneField.classList.add('dropzone-field--supported'); const field = dropzoneField.querySelector('.dropzone'); const input = dropzoneField.querySelector('input[type="file"]'); const config = JSON.parse(input.attributes['dropzone-config'].value); const schema = JSON.parse(input.attributes['data-schema'].value); const state = JSON.parse(input.attributes['data-state'].value); const dropzone = new Dropzone(field, config); dropzone.on("removedfile", file => { // empty hiddenfields in dropzone-items dropzoneField.querySelector('.dropzone-items').innerHTML = ""; }); if (typeof state.data.files !== 'undefined' && state.data.files.length > 0) { let file = state.data.files[0]; dropzone.displayExistingFile(file, file.thumbnail); } dropzone.on('success', (file, response) => { const input = document.createElement('input'); input.type = 'hidden'; input.name = `${schema.name}[Files][]`; input.value = response[0].id; dropzoneField.appendChild(input); }); } } <gh_stars>100-1000 import __toString from './_Utility.js'; function FileParser(buffer) { this.uint8 = new Uint8Array(buffer); this.offset = 0; }; FileParser.prototype.Math = Math; /** * -- sample -- * FileParser.prototype._VERTEX_STRUCTURE = { * position: {type: 'float', isArray: true, size: 3}, * normal: {type: 'float', isArray: true, size: 3}, * uv: {type: 'float', isArray: true, size: 2}, * boneIndices: {type: 'uint16', isArray: true, size: 2}, * boneWeight: {type: 'uint8'}, * edgeFlag: {type: 'uint8'} * }; */ /** * Note: override this method in a child class */ FileParser.prototype.parse = function() { return {}; }; FileParser.prototype._parseObject = function(obj, s) { var o = this.offset; for(var key in s) { obj[key] = this._getValue(s[key], this.offset); // TODO: this can waste time when this function is called in loop this.offset += this._sizeof(s[key]); } }; FileParser.prototype._getValue = function(param, offset) { return (param.isArray === undefined) ? this._getValueScalar(param, offset) : this._getValueArray(param, offset); }; /** * TODO: you may use DataView. */ FileParser.prototype._getValueScalar = function(param, offset) { switch(param.type) { case 'char': return this._getChars(offset, 1); case 'strings': return this._getStrings(offset, 1); case 'uint8': return this._getUint8(offset); case 'uint16': return this._getUint16(offset); case 'uint32': return this._getUint32(offset); case 'float': return this._getFloat(offset); default: // TODO: to be specific throw 'error: undefined type' + param; } }; FileParser.prototype._getValueArray = function(param, offset) { if(param.type == 'char') { return this._getChars(offset, param.size); } if(param.type == 'strings') { return this._getStrings(offset, param.size); } var array = []; var size = this._sizeofScalar(param); for(var i = 0; i < param.size; i++) { array[i] = this._getValueScalar(param, offset); offset += size; } return array; }; FileParser.prototype._sizeof = function(param) { return (param.isArray === undefined) ? this._sizeofScalar(param) : this._sizeofArray(param); }; FileParser.prototype._sizeofScalar = function(param) { switch(param.type) { case 'char': return 1; case 'strings': return 1; case 'uint8': return 1; case 'uint16': return 2; case 'uint32': return 4; case 'float': return 4; default: // TODO: to be specific throw 'error: undefined type ' + param + ' ' + param.type; } }; FileParser.prototype._sizeofArray = function(param) { return this._sizeofScalar(param) * param.size; }; FileParser.prototype._sizeofObject = function(o) { var size = 0; for(var key in o) { size += this._sizeof(o[key]); } return size; }; FileParser.prototype._getUint8 = function(pos) { return this.uint8[pos]; }; FileParser.prototype._getUint16 = function(pos) { return this._getValueWithReverseByteOrder(pos, 2); }; FileParser.prototype._getUint32 = function(pos) { return this._getValueWithReverseByteOrder(pos, 4); }; FileParser.prototype._getFloat = function(pos) { return this._toBinary32(this._getValueWithReverseByteOrder(pos, 4)); }; FileParser.prototype._getValueWithReverseByteOrder = function(pos, size) { var value = 0; for(var i = 0; i < size; i++) { value = (value << 8) | this.uint8[pos+size-i-1]; } return value; }; FileParser.prototype._toBinary32 = function(uint32) { var sign = (uint32 >> 31) & 1; var exponent = (uint32 >> 23) & 0xFF; var fraction = uint32 & 0x7FFFFF; if(exponent == 0 && fraction == 0) return 0.0; if(exponent == 255 && fraction == 0) return Infinity; if(exponent == 255 && fraction != 0) return NaN; var tmp = 1; if(exponent == 0 && fraction != 0) { exponent = 1; tmp = 0; } for(var i = 0; i < 23; i++) { if((fraction >> (22-i)) & 1) { tmp += this.Math.pow(2, -(i+1)); } } tmp = tmp * this.Math.pow(2, (exponent-127)); if(sign) tmp = -tmp; return tmp; }; FileParser.prototype._getChars = function(pos, size) { var str = ''; for(var i = 0; i < size; i++) { var index = pos + i; if(this.uint8[index] == 0) break; // TODO: temporal str += String.fromCharCode(this.uint8[index]); } return str; }; FileParser.prototype._getStrings = function(pos, size) { var str = ''; for(var i = 0; i < size; i++) { var index = pos + i; if(this.uint8[index] == 0) break; // TODO: temporal str += __toString(16, this.uint8[index], 2); } return str; }; FileParser.prototype.dump = function() { var array = this.uint8; var figure = 0; var tmp = array.length; while(tmp > 0) { figure++; tmp = (tmp/16) | 0; } var dump = ''; var charDump = ''; for(var i = 0; i < array.length; i++) { if(i%16 == 0) { dump += __toString(16, i, figure); dump += ' '; } dump += __toString(16, array[i], 2); dump += ' '; if(array[i] >= 0x20 && array[i] <= 0x7E) charDump += String.fromCharCode(array[i]); else charDump += '.'; if(i%16 == 15) { dump += ' '; dump += charDump; dump += '\n'; charDump = ''; } } return dump; }; module.exports = FileParser; <gh_stars>0 import React, { Component } from "react"; import Article from "./article"; class ListArticles extends Component { render() { const { articles, handleDelete, user,auth,strings } = this.props; return ( <div> {articles && articles.map(article => { return (article = ( <Article key={article.id} article={article} handleDelete={handleDelete} user={user} auth={auth} strings={strings} /> )); })} </div> ); } } export default ListArticles; const outputPath = './list.txt' const fs = require('fs') let finalList = [] // Parse adjectives const adjectives = fs.readFileSync('./Wordlist-Adjectives-All.txt') .toString() .split('\n') .filter(adj => adj.length >= 4 && adj.length <= 15) .map(adj => adj.toUpperCase()) finalList.push(...adjectives) // Parse nouns const nouns = fs.readFileSync('./Wordlist-Nouns-All.txt') .toString() .split('\n') .filter(noun => noun.length >= 5 && noun.length <= 13) .map(noun => noun.toUpperCase()) finalList.push(...nouns) // Parse verbs const verbs = fs.readFileSync('./Wordlist-Verbs-All.txt') .toString() .split('\n') .map(verb => verb.toUpperCase()) .filter(verb => verb.indexOf('ING') === verb.length - 3 && verb.length > 3 && verb.length <= 15) finalList.push(...verbs) // Polish finalList and save to disk // Most of the time is probably spent in this filter // could be optimized with Set instead of Array // not gonna bother (for now) finalList = finalList.filter((word, idx) => finalList.indexOf(word) === idx) finalList = shuffle(finalList) fs.writeFileSync(outputPath, finalList.join('\n')) /** * Shuffles array in place. ES6 version * @param {Array} a items An array containing the items. */ function shuffle(a) { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }import React, { useContext } from "react"; import { Platform } from "react-native"; import { Container } from "native-base"; import { UserUpdatePassword } from "../ui/User"; import { AuthContext } from "../ui/Provider/Native"; export default function UserUpdate({ navigation }) { const { user } = useContext(AuthContext); return ( <Container w="container.lg" margin="auto" mt={Platform.OS === "web" ? "64px" : "0"} maxW="full" px="8px" > <UserUpdatePassword user={user} /> </Container> ); } export const featureServiceURI = "https://www.portlandmaps.com/arcgis/rest/services/Public/BDS_Permit/FeatureServer/22"; export const mapboxGeocoderURI = "https://api.mapbox.com/geocoding/v5/mapbox.places"; export const pdxBoundaryURI = "https://nca-toolkit.s3-us-west-2.amazonaws.com/pdx_boundary_simple.geojson"; /** * Testing our Sup component */ import React from 'react'; import { mount } from 'enzyme'; import BootstrapProvider from '@bootstrap-styled/provider/lib/BootstrapProvider'; import Sup from '../index'; const children = 'Test'; const renderComponent = (props = {}) => mount( <Sup {...props} /> ); const renderComponentUsingTheme = (props = {}) => mount( <BootstrapProvider> <Sup {...props} /> </BootstrapProvider> ); describe('<Sup />', () => { it('should render an <Sup> tag without a theme', () => { const renderedComponent = renderComponent({ children, }); expect(renderedComponent.find('sup').length).toBe(1); }); it('should render a <sup> tag with a theme', () => { const renderedComponent = renderComponentUsingTheme({ children, }); expect(renderedComponent.find('sup').length).toBe(1); }); }); <reponame>jngo2013/gameWebsite import React, { Component } from 'react'; import NavBar from './../../components/Navbar'; import ScrollToTop from './../../components/ScrollToTop'; import LegacyGames from './../../containers/LegacyGames'; import ShortTermGames from './../../containers/ShortTermGames'; import ShortTermDetails from './../ShortTermDetails'; import LegacyDetails from './../LegacyDetails'; import SignIn from './../SignIn'; import SignOut from './../SignOut'; import EventCalendar from './../Calendar'; import Search from './../Search'; import PageNotFound from './../../components/PageNotFound'; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Footer from './../../components/Footer'; import Container from 'react-bootstrap/Container'; import Home from "../Home"; import AboutUs from '../AboutUs'; import "./style.css"; class App extends Component { state = { authenticated : false, searchResults: "", } componentDidMount(){ if( localStorage.getItem('token') !== null){ this.setState({authenticated : true}) } } render() { return ( <div className="App" > <Container fluid className="background"> <Router> <ScrollToTop /> <NavBar authenticated={this.state.authenticated} passToSearch={this.passToSearch} /> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/AboutUs" component={AboutUs} /> <Route exact path="/LegacyGames" component={LegacyGames} /> <Route exact path="/ShortTermGames" component={ShortTermGames} /> <Route exact path="/ShortTermGames/:id" component={ShortTermDetails} /> <Route exact path="/ShortTermGames/game/:id" component={ShortTermDetails} /> <Route exact path="/LegacyGames/:id" component={LegacyDetails} /> <Route exact path="/Calendar" component={EventCalendar} /> <Route exact path="/SignIn" component={SignIn} /> <Route exact path='/SignOut' component={SignOut} /> <Route exact path="/notfound" render={() => <PageNotFound message="Sorry! That game doesn't exist." />} /> <Route exact path="/search/:searchinput" component={Search} /> <Route render={() => <PageNotFound message="Sorry! That page doesn't exist."/>} /> </Switch> <Footer /> </Router> </Container> </div> ); } } export default App; /* eslint-disable no-console */ // ref: https://github.com/jantimon/html-webpack-plugin const fs = require('fs-extra'); const path = require('path'); // ============================================================================ /** * Webpack 插件 - 生成 SPA 主页面文件 * @class ModifyServerBundlePlugin * @classdesc Webpack 插件 - 生成 SPA 主页面文件 * @property {String} localeId */ class ModifyServerBundlePlugin { constructor(settings = {}) { this.isServerless = settings.isServerless; } apply(compiler) { // const { isServerless = false } = this; if (process.env.WEBPACK_BUILD_ENV === 'prod') { compiler.hooks.afterEmit.tapAsync.bind( compiler.hooks.afterEmit, 'ModifyServerBundlePlugin' )(async (compilation, callback) => { const { outputPath, assetsByChunkName, } = compilation.getStats().toJson(); for (const files of Object.values(assetsByChunkName)) { for (const filename of files) { if (path.extname(filename) === '.js') { await prependDistDir( path.resolve(outputPath, filename) ); } } } callback(); }); } } } module.exports = ModifyServerBundlePlugin; // ============================================================================ const prependDistDir = async (file) => { await fs.writeFile( file, 'if (typeof global.KOOT_DIST_DIR === "undefined") {\n' + ' global.KOOT_DIST_DIR = require("path").resolve(__dirname, "../");\n' + '}\n\n' + // 'console.log(global.KOOT_DIST_DIR);\n\n' + (await fs.readFile(file, 'utf-8')), 'utf-8' ); }; // extend the class Photowall.prototype.Main = function(config, context) { // PROPERTIES this.config = config; this.context = context; this.element = config.element; // METHODS this.init = function() { // find all the links var photos = this.element.getElementsByTagName('img'); // process all photos for (var a = 0, b = photos.length; a < b; a += 1) { // move the image to the tile's background photos[a].style.visibility = 'hidden'; photos[a].parentNode.style.backgroundImage = "url('" + photos[a].getAttribute('src') + "')"; } // return the object return this; }; this.init(); }; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.angleDoubleLeft = void 0; var angleDoubleLeft = { "viewBox": "0 0 1024 1792", "children": [{ "name": "path", "attribs": { "d": "M627 1376q0 13-10 23l-50 50q-10 10-23 10t-23-10l-466-466q-10-10-10-23t10-23l466-466q10-10 23-10t23 10l50 50q10 10 10 23t-10 23l-393 393 393 393q10 10 10 23zM1011 1376q0 13-10 23l-50 50q-10 10-23 10t-23-10l-466-466q-10-10-10-23t10-23l466-466q10-10 23-10t23 10l50 50q10 10 10 23t-10 23l-393 393 393 393q10 10 10 23z" } }] }; exports.angleDoubleLeft = angleDoubleLeft;import Ember from 'ember'; export default Ember.Controller.extend({ breadCrumb: 'Participants', }); var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", '../../spec/testfiles/basic.json', false ); // false for synchronous request xmlHttp.send( null ); var testJSON = JSON.parse(xmlHttp.responseText); describe("Null Tests", function() { it("check there's no issues where the json has not been specified", function() { var cfg = new JsonConfig.JsonConfig(); expect(cfg.getValue('customer/firstname', 'Jimmy')).toBe('Jimmy'); }); });import technologyFixture from '../fixtures/technology.json'; import * as locales from '../../packages/web/public/static/locales'; const defaultUserEmail = '<EMAIL>'; const defaultUserPassword = '<PASSWORD>'; Cypress.Commands.add( 'signIn', ({ email = defaultUserEmail, password = <PASSWORD>, redirectTo = '', inline = false, } = {}) => { cy.intercept('POST', '**/auth/login').as('signIn'); cy.location().then((location) => { if (location.pathname !== '/entrar' && !inline) cy.visit(`/entrar${redirectTo ? `?redirect=${redirectTo}` : ''}`); }); cy.get('#email') .type(email) .get('#password') .type(password); cy.get('[data-cy="signin-form"]').within(() => { cy.findByRole('button', { name: /entrar/i }).click(); }); cy.wait('@signIn') .its('response.statusCode') .should('eq', 200); }, ); /** * Custom command to register a new user * * @param {object} options * @param {string} options.email User e-mail * @param {string} options.password User password * @param {string} options.name User name * @param {string} options.phone User phone * @param {boolean} options.openWizard If true, will access register page and fill wizard form, otherwise will register using API requests */ Cypress.Commands.add( 'register', ({ openWizard = true, name = '', phone = '', email = '', password = '' } = {}) => { if (openWizard) { cy.findByRole('button', { name: /utilizando o e-mail/i }).click(); cy.inputType({ name: 'email' }, email); cy.inputType({ name: 'password' }, password); cy.inputType({ name: 'passwordConfirm' }, password); cy.findByLabelText( /Concordo com os termos de uso e política de privacidade da Plataforma Sabiá/i, ).click({ force: true }); cy.findAllByRole('button') .eq(0) .click(); return; } const registerRequest = () => cy.request({ method: 'POST', url: 'http://localhost:3334/auth/register', body: { scope: 'web', email, password, disclaimers: Array.from(Array(10).keys()), }, }); const confirmAccountRequest = (verificationCode) => cy.request({ method: 'POST', url: 'http://localhost:3334/auth/confirm-account', body: { email, token: verificationCode, }, }); const updateUserRequest = (userId, token) => cy.request({ method: 'PUT', url: `http://localhost:3334/users/${userId}`, body: { full_name: name, phone, }, headers: { Authorization: `Bearer ${token}`, }, }); registerRequest().then((registerResponse) => { cy.getLastReceivedEmail(email) .then(cy.wrap) .invoke('match', /(?<code>\w+) Siga-nos/i) .its('groups.code') .then((verificationCode) => { confirmAccountRequest(verificationCode).then((verificationResponse) => { cy.resetReceivedEmails(); updateUserRequest( registerResponse.body.id, verificationResponse.body.token, ); }); }); }); }, ); Cypress.Commands.add('authenticate', (options = {}) => { const email = options.email ?? defaultUserEmail; const password = options.password ?? <PASSWORD>; cy.request('POST', 'http://localhost:3334/auth/login', { email, password, }).then((response) => { if (response.status === 200) { cy.setCookie('token', response.body.token); } }); }); /** * Cypress commands that selects the nth option (defaults to first option) in a react-select component. */ Cypress.Commands.add('select', (id, options = {}) => { const exactMatch = options.exactMatch || false; const idSelector = exactMatch ? `[id='${id}']` : `[id*='${id}']`; const position = options.position || 0; cy.get(`div.react-select-container${idSelector}`).within(($el) => { cy.wrap($el) .click() .get('div[class*="react-select__option"]') .eq(position) .click(); }); }); Cypress.Commands.add('technologyFormFillInNResponsible', (parameters = { count: 1 }) => { const { count } = parameters; for (let index = 0; index < count; index += 1) { if (index > 0) { cy.get('[name="technologyResponsibles.users_add_button"]').click(); } cy.get(`[name='technologyResponsibles.users.${index}.phone_number']`).type( technologyFixture.responsible[index].phone, ); cy.get(`[name='technologyResponsibles.users.${index}.email']`).type( technologyFixture.responsible[index].email, ); cy.get(`[name='technologyResponsibles.users.${index}.full_name']`).type( technologyFixture.responsible[index].fullName, ); } }); /** * Command that types text in an input * It receives a selector that can be a string or an object * If it's an object it'll use the key as selector attribute and value as the selector value * If the selector is a Regex, then it'll use testing-library findByLabelText method * * i.e. cy.inputType({ name: 'fieldname' }, 'text value') will try to find input with name 'fieldname' and type 'text value' into it * cy.inputType('[name="fieldname"]', 'text value) has the same output */ Cypress.Commands.add('inputType', (selector, text, options = { clearField: true }) => { let getterMethod = 'findByLabelText'; let selectorText = selector; if (!(selector instanceof RegExp)) { const selectorEntries = Object.entries(selector); getterMethod = 'get'; selectorText = typeof selector === 'string' || selector instanceof String ? selector : `[${selectorEntries[0][0]}="${selectorEntries[0][1]}"]`; } if (options.clearField) { cy[getterMethod](selectorText).clear(); } return cy[getterMethod](selectorText).type(text); }); Cypress.Commands.add('resetReceivedEmails', () => { return cy.task('resetEmails'); }); Cypress.Commands.add('getLastReceivedEmail', (email, options = {}) => { cy.waitUntil(() => cy.task('getLastEmail', email), { errorMsg: 'Could not get last received e-mail', interval: 1000, timeout: 15000, ...options, }); }); Cypress.Commands.add('getByDataCy', (selector, ...args) => { cy.get(`[data-cy="${selector}"]`, ...args); }); /** * Returns translations from namespace and key * * @param {string} param Namespace and key separated by colon * @returns {RegExp} Regex with translations */ const getTranslation = (param) => { const [namespace, key] = param.split(':'); const values = Object.keys(locales).map((locale) => { const localeValue = locales[locale][namespace][key]; if (typeof localeValue === 'undefined') { throw new Error('Locale not found'); } return localeValue; }); const value = values.join('|').toLowerCase(); return new RegExp(`^(${value})$`, 'i'); }; Cypress.Commands.add('getTranslation', getTranslation); Cypress.Commands.add('findByTranslation', (value) => cy.findByText(getTranslation(value))); Cypress.Commands.add('findAllByTranslation', (value) => cy.findAllByText(getTranslation(value))); <reponame>Dinoshauer/actions #!/usr/bin/env node const { spawn } = require('child_process'); const fs = require('fs'); require('dotenv').config() const args = process.argv.slice(2); const update = args.length > 0 && args[0] === 'true'; let command = `act \ -W .github/workflows/examples_test.yml \ -s GITHUB_TOKEN=$GITHUB_TOKEN \ -s GIT_SSH_KEY="$GIT_SSH_KEY" \ -s INFRACOST_API_KEY=$(infracost configure get api_key) \ -s TFC_TOKEN=$TFC_TOKEN \ --artifact-server-path=.act/artifacts`; if (update) { command += ` --env UPDATE_GOLDEN_FILES=true -b`; } console.log(`Running ${command}`); const child = spawn('bash', ['-c', command], { env: process.env }); child.stdout.on('data', (data) => { process.stdout.write(data.toString()); }); child.stderr.on('data', (data) => { process.stderr.write(data.toString()); }); child.on('exit', () => { // Cleanup if (update) { for (const dir of ['.ssh', 'workflow']) { try { console.log(`Cleaning up: ${dir}`) if (fs.existsSync(dir)) { fs.rmSync(dir, { recursive: true }); } } catch (err) { console.error(`Error while deleting ${dir}: ${err}`); } } } }); <gh_stars>1-10 module.exports = new Date(2011, 4, 27) const UserEditableProperties = { name: { type: 'string', }, englishLevel: { $ref: '#/components/schemas/EnglishLevel', }, technicalKnowledge: { type: 'string', }, cvLink: { type: 'string', format: 'hostname', }, }; module.exports = { EnglishLevel: { type: 'string', enum: ['A1', 'A2', 'B1', 'B2', 'C1', 'C2'], }, Credentials: { type: 'object', required: ['email', 'password'], properties: { email: { type: 'string', format: 'email' }, password: { type: 'string', format: 'password' }, }, }, User: { type: 'object', properties: { id: { $ref: '#/components/schemas/Id', }, email: { type: 'string', format: 'email', }, ...UserEditableProperties, role: { type: 'string', description: 'The role of the user', }, roleId: { type: 'integer', description: 'The numeric representation of the role', }, }, }, NewUserInput: { type: 'object', required: ['email', 'name', 'password'], properties: { email: { type: 'string', format: 'email', }, password: { type: 'string', format: 'password', }, ...UserEditableProperties, roleId: { type: 'integer', minimum: 2, description: 'The role that will be assigned the user', }, }, }, UpdateUserInput: { type: 'object', properties: { ...UserEditableProperties, }, }, }; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';\n', }, all: { src: ['src/modules/**/*.js'], dest: 'src/js/<%= pkg.name %>.min.js', } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, dist: { src: 'src/js/<%= pkg.name %>.min.js', dest: 'dist/js/<%= pkg.name %>.min.js' } }, sass: { all: { options: { style: 'expanded' }, files: { 'src/styles/main.css': 'src/styles/main.scss' } } }, copy: { all: { files: [ {expand: true, cwd:'src/js/', src: ['**/*.js'], dest: 'dist/js/'}, {expand: true, cwd:'src/styles/', src: ['**/*.css'], dest: 'dist/styles/'}, {expand: true, cwd:'src/data/', src: ['**'], dest: 'dist/data/'}, {expand: true, cwd:'src/img/', src: ['**'], dest: 'dist/img/'}, {expand: true, cwd:'src/templates/', src: ['**'], dest: 'dist/templates/'}, {expand: true, cwd:'src/', src: ['index.html'], dest: 'dist/'} ] }, dev: { files: [ {expand: true, cwd:'src/js/', src: ['**/*.map'], dest: 'dist/js/'}, {expand: true, cwd:'src/styles/', src: ['**/*.map', '**/*.scss'], dest: 'dist/styles/'} ] } }, clean: { all: ['dist/*'], allpost: ['src/styles/main.css'], distpost: ['src/js/<%= pkg.name %>.js'], commitpre: ['src/js/<%= pkg.name %>.min.js', 'src/styles/main.css.map'] }, 'http-server': { dev: { root: 'dist', port: 8081, host: '0.0.0.0', ext: 'html', runInBackground: false, openBrowser : true } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-http-server'); grunt.registerTask('dev', ['clean:all', 'concat', 'sass', 'copy:all', 'copy:dev', 'clean:allpost']); grunt.registerTask('dist', ['clean:all', 'concat', 'uglify', 'sass', 'copy:all', 'clean:allpost', 'clean:distpost']); grunt.registerTask('start-server', ['http-server']); grunt.registerTask('prepare-commit', ['clean']); grunt.registerTask('default', ['dist']); }; <reponame>glihui/larabbs<gh_stars>1-10 export default { props: { chartData: { required: true, }, }, watch: { chartData: { handler(newData, oldData) { if (oldData) { let chart = this._chart; // Get new and old DataSet Labels let newDatasetLabels = newData.datasets.map(dataset => { return dataset.label; }); let oldDatasetLabels = oldData.datasets.map(dataset => { return dataset.label; }); // Stringify 'em for easier compare const oldLabels = JSON.stringify(oldDatasetLabels); const newLabels = JSON.stringify(newDatasetLabels); // Check if Labels are equal and if dataset length is equal if ( newLabels === oldLabels && oldData.datasets.length === newData.datasets.length ) { newData.datasets.forEach((dataset, i) => { chart.data.datasets[i] = dataset; }); chart.data.labels = newData.labels; chart.update(); } else { chart.destroy(); this.renderChart(this.chartData, this.options); } } }, }, }, }; export * from './object-size'; /* globals WebAuthnHelpers, Msg, ServerResponse, CreateOptionsRequest, CreateOptions, CredentialAttestation, GetOptionsRequest, GetOptions, CredentialAssertion, WebAuthnOptions */ "use strict"; // messages for sending / receiving // registration: // 1a. client >>> CreateOptionsRequest >>> server // 1b. client <<< CreateOptions <<< server // 2a. client >>> CredentialAttestation >>> server // 2b. client <<< ServerResponse <<< server // authentication: // 1a. client >>> GetOptionsRequest >>> server // 1b. client <<< GetOptions <<< server // 2a. client >>> CredentialAssertion >>> server // 2b. client <<< ServerResponse <<< server (function() { /** * Virtual class for messages that serves as the base * for all other messages. */ class Msg { constructor() { /** @type {Array} The list of "official" properties that are managed for this object and sent over the wire. */ this.propList = []; } /** * Converts the `Msg` to an `Object` containing all the properties in `propList` that have been defined on the `Msg` * @return {Object} An `Object` that contains all the properties to be sent over the wire. */ toObject() { var obj = {}; copyPropList(this, obj, this.propList); return obj; } /** * Converts the `Msg` to a JSON string containing all the properties in `propList` that have been defined on the `Msg` * @return {String} A JSON `String` that contains all the properties to be sent over the wire. */ toString() { return JSON.stringify(this.toObject()); } /** * Converts the `Msg` to a human-readable string. Useful for debugging messages as they are being sent / received. * @return {String} The human-readable message, probably multiple lines. */ toHumanString() { var constructMe = Object.getPrototypeOf(this).constructor; var retObj = constructMe.from(this); retObj.decodeBinaryProperties(); retObj = retObj.toObject(); var ret = `[${constructMe.name}] ` + stringifyObj(retObj, 0); return ret; } /** * Converts the provided `obj` to this class and then returns a human * readable form of the object as interpreted by that class. * @param {Object} obj Any object * @return {String} A human-readable string as interpreteed by this class. */ static toHumanString(obj) { var retObj = this.from(obj); retObj.decodeBinaryProperties(); retObj = retObj.toObject(); var ret = `[${this.name}] ` + stringifyObj(retObj, 0); return ret; } /** * Converts the `Msg` to a human-readable string (via {@link toHumanString}) and then replaces whitespace (" " and "\n") with * HTML compatible interpetations of whitespace (" " and "<br>"). * @return {String} The HTML compatible representation of this Msg that should be easy for people to read */ toHumanHtml() { return this.toHumanString().replace(/ /g, " ").replace(/\n/g, "<br>"); } /** * Ensures that all the required properties in the object are defined, and all defined properties are of the correct format. * @throws {Error} If any required field is undefined, or any defined field is of the wrong format. */ validate() { throw new Error("not implemented"); } /** * Any fields that are known to be encoded as `base64url` are decoded to an `ArrayBuffer` */ decodeBinaryProperties() { // throw new Error("not implemented"); } /** * Any fields that are known to be encoded as an `ArrayBuffer` are encoded as `base64url` */ encodeBinaryProperties() { // throw new Error("not implemented"); } /** * Creates a new `Msg` object from the specified parameter. Note that the resulting `Msg` is not validated * and all fields are their original values (call {@link decodeBinaryProperties} to convert fields to ArrayBuffers) * if needed. * @param {String|Object} json The JSON encoded string, or already parsed JSON message in an `Object` * @return {Msg} The newly created message from the Object. */ static from(json) { var obj; if (typeof json === "string") { try { obj = JSON.parse(json); } catch (err) { throw new TypeError("error parsing JSON string"); } } if (typeof json === "object") { obj = json; } if (typeof obj !== "object") { throw new TypeError("could not coerce 'json' argument to an object: '" + json + "'"); } var msg = new this.prototype.constructor(); copyPropList(obj, msg, msg.propList); if (obj.preferences) { msg.preferences = WebAuthnOptions.from(obj.preferences); } return msg; } } /** * Generic {@link Msg} from server to indicate success or failure. Used by * itself for simple responses, or extended for more complex responses. * @extends {Msg} */ class ServerResponse extends Msg { constructor() { super(); this.propList = [ "status", "errorMessage", "debugInfo" ]; } validate() { switch (this.status) { case "ok": if (this.errorMessage === undefined) { this.errorMessage = ""; } // if status is "ok", errorMessage must be "" checkTrue(this.errorMessage === "", "errorMessage must be empty string when status is 'ok'"); checkOptionalType(this, "debugInfo", "object"); break; case "failed": // if status is "failed", errorMessage must be non-zero-length string checkType(this, "errorMessage", "string"); checkTrue( this.errorMessage.length > 0, "errorMessage must be non-zero length when status is 'failed'" ); checkOptionalType(this, "debugInfo", "object"); break; // status is string, either "ok" or "failed" default: throw new Error("'expected 'status' to be 'string', got: " + this.status); } } decodeBinaryProperties() { function decodeAb(obj, key) { obj[key] = coerceToArrayBuffer(obj[key], key); } function decodeOptionalAb(obj, key) { if (obj[key] !== undefined) decodeAb(obj, key); } function objToMap(o) { var m = new Map(); Object.keys(o).forEach((k) => { m.set(k, o[k]); }); return m; } if (typeof this.debugInfo === "object") { decodeAb(this.debugInfo.clientData, "rawId"); decodeAb(this.debugInfo.authnrData, "rawAuthnrData"); decodeAb(this.debugInfo.authnrData, "rpIdHash"); decodeOptionalAb(this.debugInfo.authnrData, "aaguid"); decodeOptionalAb(this.debugInfo.authnrData, "credId"); decodeOptionalAb(this.debugInfo.authnrData, "credentialPublicKeyCose"); decodeOptionalAb(this.debugInfo.authnrData, "sig"); decodeOptionalAb(this.debugInfo.authnrData, "attCert"); this.debugInfo.clientData.rawClientDataJson = str2ab(this.debugInfo.clientData.rawClientDataJson); this.debugInfo.authnrData.flags = new Set([...this.debugInfo.authnrData.flags]); this.debugInfo.audit.warning = objToMap(this.debugInfo.audit.warning); this.debugInfo.audit.info = objToMap(this.debugInfo.audit.info); } } encodeBinaryProperties() { function encodeAb(obj, key) { obj[key] = coerceToBase64Url(obj[key], key); } function encodeOptionalAb(obj, key) { if (obj[key] !== undefined) encodeAb(obj, key); } if (typeof this.debugInfo === "object") { encodeAb(this.debugInfo.clientData, "rawId"); encodeAb(this.debugInfo.authnrData, "rawAuthnrData"); encodeAb(this.debugInfo.authnrData, "rpIdHash"); encodeOptionalAb(this.debugInfo.authnrData, "aaguid"); encodeOptionalAb(this.debugInfo.authnrData, "credId"); encodeOptionalAb(this.debugInfo.authnrData, "credentialPublicKeyCose"); encodeOptionalAb(this.debugInfo.authnrData, "sig"); encodeOptionalAb(this.debugInfo.authnrData, "attCert"); this.debugInfo.clientData.rawClientDataJson = ab2str(this.debugInfo.clientData.rawClientDataJson, "clientData.rawClientDataJson"); this.debugInfo.authnrData.flags = [...this.debugInfo.authnrData.flags]; this.debugInfo.audit.warning = mapToObj(this.debugInfo.audit.warning); this.debugInfo.audit.info = mapToObj(this.debugInfo.audit.info); } } } /** * A {@link Msg} object that the browser sends to the server to request * the options to be used for the WebAuthn `create()` call. * @extends {Msg} */ class CreateOptionsRequest extends Msg { constructor() { super(); this.propList = [ "username", "displayName", "authenticatorSelection", "attestation" ]; } validate() { checkFormat(this, "username", "non-empty-string"); checkFormat(this, "displayName", "non-empty-string"); checkAuthenticatorSelection(this); checkAttestation(this); } decodeBinaryProperties() {} encodeBinaryProperties() {} } /** * The options to be used for WebAuthn `create()` * @extends {ServerResponse} */ class CreateOptions extends ServerResponse { constructor() { super(); this.propList = this.propList.concat([ "rp", "user", "challenge", "pubKeyCredParams", "timeout", "excludeCredentials", "authenticatorSelection", "attestation", "extensions" ]); } validate() { super.validate(); // check types checkType(this, "rp", Object); checkFormat(this.rp, "name", "non-empty-string"); checkOptionalFormat(this.rp, "id", "non-empty-string"); checkOptionalFormat(this.rp, "icon", "non-empty-string"); checkType(this, "user", Object); checkFormat(this.user, "name", "non-empty-string"); checkFormat(this.user, "id", "base64url"); checkFormat(this.user, "displayName", "non-empty-string"); checkOptionalFormat(this.user, "icon", "non-empty-string"); checkFormat(this, "challenge", "base64url"); checkType(this, "pubKeyCredParams", Array); this.pubKeyCredParams.forEach((cred) => { checkType(cred, "alg", "number"); checkTrue(cred.type === "public-key", "credential type must be 'public-key'"); }); checkOptionalFormat(this, "timeout", "positive-integer"); checkOptionalType(this, "excludeCredentials", Array); if (this.excludeCredentials) checkCredentialDescriptorList(this.excludeCredentials); checkAuthenticatorSelection(this); checkAttestation(this); checkOptionalType(this, "extensions", Object); } decodeBinaryProperties() { if (this.user && this.user.id) { this.user.id = coerceToArrayBuffer(this.user.id, "user.id"); } this.challenge = coerceToArrayBuffer(this.challenge, "challenge"); if (this.excludeCredentials) { this.excludeCredentials.forEach((cred, idx) => { cred.id = coerceToArrayBuffer(cred.id, "excludeCredentials[" + idx + "].id"); }); } } encodeBinaryProperties() { if (this.user && this.user.id) { this.user.id = coerceToBase64Url(this.user.id, "user.id"); } this.challenge = coerceToBase64Url(this.challenge, "challenge"); if (this.excludeCredentials) { this.excludeCredentials.forEach((cred, idx) => { cred.id = coerceToBase64Url(cred.id, "excludeCredentials[" + idx + "].id"); }); } } } /** * This is the `PublicKeyCredential` that was the result of the `create()` call. * @extends {Msg} */ class CredentialAttestation extends Msg { constructor() { super(); this.propList = [ "rawId", "id", "response" ]; } static from(obj) { obj = super.from(obj); // original response object is probably read-only if (typeof obj.response === "object") { var origResponse = obj.response; obj.response = { clientDataJSON: origResponse.clientDataJSON, attestationObject: origResponse.attestationObject, }; } return obj; } validate() { checkFormat(this, "rawId", "base64url"); checkOptionalFormat(this, "id", "base64url"); checkType(this, "response", Object); checkFormat(this.response, "attestationObject", "base64url"); checkFormat(this.response, "clientDataJSON", "base64url"); } decodeBinaryProperties() { this.rawId = coerceToArrayBuffer(this.rawId, "rawId"); if (this.id) this.id = coerceToArrayBuffer(this.id, "id"); this.response.attestationObject = coerceToArrayBuffer(this.response.attestationObject, "response.attestationObject"); this.response.clientDataJSON = coerceToArrayBuffer(this.response.clientDataJSON, "response.clientDataJSON"); } encodeBinaryProperties() { this.rawId = coerceToBase64Url(this.rawId, "rawId"); if (this.id) this.id = coerceToBase64Url(this.id, "id"); this.response.attestationObject = coerceToBase64Url(this.response.attestationObject, "response.attestationObject"); this.response.clientDataJSON = coerceToBase64Url(this.response.clientDataJSON, "response.clientDataJSON"); } } function stringifyObj(obj, depth) { var str = ""; // opening bracket str += "{\n"; depth++; // print all properties for (let key of Object.keys(obj)) { // add key str += indent(depth) + key + ": "; // add value str += stringifyType(obj, key, depth) + ",\n"; } // closing bracket depth--; str += indent(depth) + "}"; return str; } function stringifyArr(arr, depth) { var str = ""; // opening brace str += "[\n"; depth++; // print all properties for (let i = 0; i < arr.length; i++) { // add value str += indent(depth) + stringifyType(arr, i, depth) + ",\n"; } // closing brace depth--; str += indent(depth) + "]"; return str; } function stringifyType(obj, key, depth) { // handle native types switch (typeof obj[key]) { case "object": break; case "undefined": return "undefined"; // case "string": return "\"" + obj[key].replace(/\n/g, "\\n\"\n" + indent(depth + 1) + "\"") + "\""; case "string": return "\"" + obj[key].replace(/\n/g, "\n" + indent(depth + 1)) + "\""; case "number": return obj[key].toString(); case "boolean": return obj[key].toString(); case "symbol": return obj[key].toString(); default: throw new TypeError("unknown type in stringifyType: " + typeof obj[key]); } // handle objects switch (true) { case obj[key] instanceof ArrayBuffer: return abToHumanStr(obj[key], (depth + 1)); case obj[key] instanceof Array: return stringifyArr(obj[key], depth); case obj[key] instanceof Set: return stringifyArr([...obj[key]], depth); case obj[key] instanceof Map: return stringifyObj(mapToObj(obj[key]), depth); default: return stringifyObj(obj[key], depth); } } function indent(depth) { var ret = ""; for (let i = 0; i < depth * 4; i++) { ret += " "; } return ret; } // printHex function abToHumanStr(buf, depth) { var ret = ""; // if the buffer was a TypedArray (e.g. Uint8Array), grab its buffer and use that if (ArrayBuffer.isView(buf) && buf.buffer instanceof ArrayBuffer) { buf = buf.buffer; } // check the arguments if ((typeof depth != "number") || (typeof buf != "object")) { throw new TypeError("Bad args to abToHumanStr"); } if (!(buf instanceof ArrayBuffer)) { throw new TypeError("Attempted abToHumanStr with non-ArrayBuffer:", buf); } // print the buffer as a 16 byte long hex string var arr = new Uint8Array(buf); var len = buf.byteLength; var i, str = ""; ret += `[ArrayBuffer] (${buf.byteLength} bytes)\n`; for (i = 0; i < len; i++) { var hexch = arr[i].toString(16); hexch = (hexch.length == 1) ? ("0" + hexch) : hexch; str += hexch.toUpperCase() + " "; if (i && !((i + 1) % 16)) { ret += indent(depth) + str.replace(/.$/, "\n"); str = ""; } } // print the remaining bytes if ((i) % 16) { ret += indent(depth) + str.replace(/.$/, "\n"); } // remove final newline ret = ret.replace(/\n$/, ""); return ret; } /** * A {@link Msg} object that the browser sends to the server to request * the options to be used for the WebAuthn `get()` call. * @extends {Msg} */ class GetOptionsRequest extends Msg { constructor() { super(); this.propList = [ "username", "displayName" ]; } validate() { checkFormat(this, "username", "non-empty-string"); checkFormat(this, "displayName", "non-empty-string"); } decodeBinaryProperties() {} encodeBinaryProperties() {} } /** * The options to be used for WebAuthn `get()` * @extends {ServerResponse} */ class GetOptions extends ServerResponse { constructor() { super(); this.propList = this.propList.concat([ "challenge", "timeout", "rpId", "allowCredentials", "userVerification", "extensions" ]); } validate() { super.validate(); checkFormat(this, "challenge", "base64url"); checkOptionalFormat(this, "timeout", "positive-integer"); checkOptionalFormat(this, "rpId", "non-empty-string"); checkOptionalType(this, "allowCredentials", Array); if (this.allowCredentials) checkCredentialDescriptorList(this.allowCredentials); if (this.userVerification) checkUserVerification(this.userVerification); checkOptionalType(this, "extensions", Object); } decodeBinaryProperties() { this.challenge = coerceToArrayBuffer(this.challenge, "challenge"); if (this.allowCredentials) { this.allowCredentials.forEach((cred) => { cred.id = coerceToArrayBuffer(cred.id, "cred.id"); }); } } encodeBinaryProperties() { this.challenge = coerceToBase64Url(this.challenge, "challenge"); if (this.allowCredentials) { this.allowCredentials.forEach((cred, idx) => { cred.id = coerceToBase64Url(cred.id, "allowCredentials[" + idx + "].id"); }); } } } /** * This is the `PublicKeyCredential` that was the result of the `get()` call. * @extends {Msg} */ class CredentialAssertion extends Msg { constructor() { super(); this.propList = [ "rawId", "id", "response" ]; } static from(obj) { obj = super.from(obj); // original response object is probably read-only if (typeof obj.response === "object") { var origResponse = obj.response; obj.response = { clientDataJSON: origResponse.clientDataJSON, authenticatorData: origResponse.authenticatorData, signature: origResponse.signature, userHandle: origResponse.userHandle, }; } return obj; } validate() { checkFormat(this, "rawId", "base64url"); checkOptionalFormat(this, "id", "base64url"); checkType(this, "response", Object); checkFormat(this.response, "authenticatorData", "base64url"); checkFormat(this.response, "clientDataJSON", "base64url"); checkFormat(this.response, "signature", "base64url"); checkOptionalFormat(this.response, "userHandle", "nullable-base64"); } decodeBinaryProperties() { this.rawId = coerceToArrayBuffer(this.rawId, "rawId"); if (this.id) this.id = coerceToArrayBuffer(this.id, "id"); this.response.clientDataJSON = coerceToArrayBuffer(this.response.clientDataJSON, "response.clientDataJSON"); this.response.signature = coerceToArrayBuffer(this.response.signature, "response.signature"); this.response.authenticatorData = coerceToArrayBuffer(this.response.authenticatorData, "response.authenticatorData"); if (this.response.userHandle) { this.response.userHandle = coerceToArrayBuffer(this.response.userHandle, "response.authenticatorData"); } if (this.response.userHandle === null) { this.response.userHandle = new ArrayBuffer(); } } encodeBinaryProperties() { this.rawId = coerceToBase64Url(this.rawId, "rawId"); if (this.id) this.id = coerceToBase64Url(this.id, "id"); this.response.clientDataJSON = coerceToBase64Url(this.response.clientDataJSON, "response.clientDataJSON"); this.response.signature = coerceToBase64Url(this.response.signature, "response.signature"); this.response.authenticatorData = coerceToBase64Url(this.response.authenticatorData, "response.authenticatorData"); if (this.response.userHandle) { if (this.response.userHandle.byteLength > 0) this.response.userHandle = coerceToBase64Url(this.response.userHandle, "response.authenticatorData"); else this.response.userHandle = null; } } } class WebAuthnOptions extends Msg { constructor() { super(); this.propList = [ "timeout" ]; } merge(dst, preferDst) { var i; for (i = 0; i < this.propList.length; i++) { var prop = this.propList[i]; // copy property if it isn't set if (this[prop] === undefined) this[prop] = dst[prop]; // if the destination is set and we prefer that, copy it over if (preferDst && dst[prop] !== undefined) this[prop] = dst[prop]; } } } // these get defined different depending on whether we're running in a browser or node.js var exp, coerceToBase64Url, coerceToArrayBuffer; // running in node.js if (typeof module === "object" && module.exports) { exp = module.exports; coerceToBase64Url = function(thing, name) { name = name || "''"; // Array to Uint8Array if (Array.isArray(thing)) { thing = Uint8Array.from(thing); } // Uint8Array, etc. to ArrayBuffer if (typeof thing === "object" && thing.buffer instanceof ArrayBuffer && !(thing instanceof Buffer)) { thing = thing.buffer; } // ArrayBuffer to Buffer if (thing instanceof ArrayBuffer && !(thing instanceof Buffer)) { thing = new Buffer(thing); } // Buffer to base64 string if (thing instanceof Buffer) { thing = thing.toString("base64"); } if (typeof thing !== "string") { throw new Error(`could not coerce '${name}' to string`); } // base64 to base64url // NOTE: "=" at the end of challenge is optional, strip it off here so that it's compatible with client thing = thing.replace(/\+/g, "-").replace(/\//g, "_").replace(/=*$/g, ""); return thing; }; coerceToArrayBuffer = function(buf, name) { name = name || "''"; if (typeof buf === "string") { // base64url to base64 buf = buf.replace(/-/g, "+").replace(/_/g, "/"); // base64 to Buffer buf = Buffer.from(buf, "base64"); } // Buffer or Array to Uint8Array if (buf instanceof Buffer || Array.isArray(buf)) { buf = new Uint8Array(buf); } // Uint8Array to ArrayBuffer if (buf instanceof Uint8Array) { buf = buf.buffer; } // error if none of the above worked if (!(buf instanceof ArrayBuffer)) { throw new TypeError(`could not coerce '${name}' to ArrayBuffer`); } return buf; }; } // running in browser if (isBrowser()) { exp = window; coerceToBase64Url = function(thing, name) { // Array or ArrayBuffer to Uint8Array if (Array.isArray(thing)) { thing = Uint8Array.from(thing); } if (thing instanceof ArrayBuffer) { thing = new Uint8Array(thing); } // Uint8Array to base64 if (thing instanceof Uint8Array) { var str = ""; var len = thing.byteLength; for (var i = 0; i < len; i++) { str += String.fromCharCode(thing[i]); } thing = window.btoa(str); } if (typeof thing !== "string") { throw new Error("could not coerce '" + name + "' to string"); } // base64 to base64url // NOTE: "=" at the end of challenge is optional, strip it off here thing = thing.replace(/\+/g, "-").replace(/\//g, "_").replace(/=*$/g, ""); return thing; }; coerceToArrayBuffer = function(thing, name) { if (typeof thing === "string") { // base64url to base64 thing = thing.replace(/-/g, "+").replace(/_/g, "/"); // base64 to Uint8Array var str = window.atob(thing); var bytes = new Uint8Array(str.length); for (var i = 0; i < str.length; i++) { bytes[i] = str.charCodeAt(i); } thing = bytes; } // Array to Uint8Array if (Array.isArray(thing)) { thing = new Uint8Array(thing); } // Uint8Array to ArrayBuffer if (thing instanceof Uint8Array) { thing = thing.buffer; } // error if none of the above worked if (!(thing instanceof ArrayBuffer)) { throw new TypeError("could not coerce '" + name + "' to ArrayBuffer"); } return thing; }; } function ab2str(buf) { return String.fromCharCode.apply(null, new Uint8Array(buf)); } function str2ab(str) { var buf = new ArrayBuffer(str.length); var bufView = new Uint8Array(buf); for (var i = 0, strLen = str.length; i < strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; } function copyProp(src, dst, prop) { if (src[prop] !== undefined) dst[prop] = src[prop]; } function copyPropList(src, dst, propList) { var i; for (i = 0; i < propList.length; i++) { copyProp(src, dst, propList[i]); } } function checkType(obj, prop, type) { switch (typeof type) { case "string": if (typeof obj[prop] !== type) { throw new Error("expected '" + prop + "' to be '" + type + "', got: " + typeof obj[prop]); } break; case "function": if (!(obj[prop] instanceof type)) { throw new Error("expected '" + prop + "' to be '" + type.name + "', got: " + obj[prop]); } break; default: throw new Error("internal error: checkType received invalid type"); } } function checkOptionalType(obj, prop, type) { if (obj === undefined || obj[prop] === undefined) return; checkType(obj, prop, type); } function checkFormat(obj, prop, format) { switch (format) { case "non-empty-string": checkType(obj, prop, "string"); checkTrue( obj[prop].length > 0, "expected '" + prop + "' to be non-empty string" ); break; case "base64url": checkType(obj, prop, "string"); checkTrue( isBase64Url(obj[prop]), "expected '" + prop + "' to be base64url format, got: " + obj[prop] ); break; case "positive-integer": checkType(obj, prop, "number"); var n = obj[prop]; checkTrue( n >>> 0 === parseFloat(n), "expected '" + prop + "' to be positive integer" ); break; case "nullable-base64": var t = typeof obj[prop]; if (obj[prop] === null) t = "null"; checkTrue( ["null", "string", "undefined"].includes(t), "expected '" + prop + "' to be null or string" ); if (!obj[prop]) return; checkTrue( isBase64Url(obj[prop]), "expected '" + prop + "' to be base64url format, got: " + obj[prop] ); break; default: throw new Error("internal error: unknown format"); } } function checkOptionalFormat(obj, prop, format) { if (obj === undefined || obj[prop] === undefined) return; checkFormat(obj, prop, format); } function isBase64Url(str) { return !!str.match(/^[A-Za-z0-9\-_]+={0,2}$/); } function checkTrue(truthy, msg) { if (!truthy) { throw Error(msg); } } function checkUserVerification(val) { checkTrue( ["required", "preferred", "discouraged"].includes(val), "userVerification must be 'required', 'preferred' or 'discouraged'" ); } function checkAuthenticatorSelection(obj) { checkOptionalType(obj, "authenticatorSelection", Object); if (obj.authenticatorSelection && obj.authenticatorSelection.authenticatorAttachment) { checkTrue( ["platform", "cross-platform"].includes(obj.authenticatorSelection.authenticatorAttachment), "authenticatorAttachment must be either 'platform' or 'cross-platform'" ); } if (obj.authenticatorSelection && obj.authenticatorSelection.userVerification) { checkUserVerification(obj.authenticatorSelection.userVerification); } checkOptionalType(obj.authenticatorSelection, "requireResidentKey", "boolean"); } function checkCredentialDescriptorList(arr) { arr.forEach((cred) => { checkFormat(cred, "id", "base64url"); checkTrue(cred.type === "public-key", "credential type must be 'public-key'"); checkOptionalType(cred, "transports", Array); if (cred.transports) cred.transports.forEach((trans) => { checkTrue( ["usb", "nfc", "ble"].includes(trans), "expected transport to be 'usb', 'nfc', or 'ble', got: " + trans ); }); }); } function checkAttestation(obj) { if (obj.attestation) checkTrue( ["direct", "none", "indirect"].includes(obj.attestation), "expected attestation to be 'direct', 'none', or 'indirect'" ); } function mapToObj(mapObj) { var m = {}; mapObj.forEach((v, k) => { m[k] = v; }); return m; } function isBrowser() { try { if (!window) return false; } catch (err) { return false; } return true; } /** * The main class for registering and logging in via WebAuthn. This class wraps all server communication, * as well as calls to `credentials.navigator.create()` (registration) and `credentials.navigator.get()` (login) * * @param {Object} config The configuration object for WebAuthnApp */ class WebAuthnApp { constructor(config) { // check for browser; throw error and fail if not browser if (!WebAuthnHelpers.utils.isBrowser()) throw new Error("WebAuthnApp must be run from a browser"); // check for secure context if (!window.isSecureContext) { fireNotSupported("This web page was not loaded in a secure context (https). Please try loading the page again using https or make sure you are using a browser with secure context support."); return null; } // check for WebAuthn CR features if (window.PublicKeyCredential === undefined || typeof window.PublicKeyCredential !== "function" || typeof window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable !== "function") { //console.log("PublicKeyCredential undefined:", window.PublicKeyCredential === undefined); //console.log("PublicKeyCredential is function:", window.PublicKeyCredential === "function"); //console.log("PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable is function", window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable === "function"); fireNotSupported("WebAuthn is not currently supported by this browser. See this webpage for a list of supported browsers: <a href=https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API#Browser_compatibility>Web Authentication: Browser Compatibility</a>"); return null; } // Useful constants for working with COSE key objects const coseAlgECDSAWithSHA256 = -7; // configure or defaults config = config || {}; this.registerChallengeEndpoint = config.registerChallengeEndpoint || WebAuthnHelpers.defaultRoutes.attestationOptions; this.registerResponseEndpoint = config.registerResponseEndpoint || WebAuthnHelpers.defaultRoutes.attestationResult; this.loginChallengeEndpoint = config.loginChallengeEndpoint || WebAuthnHelpers.defaultRoutes.assertionOptions; this.loginResponseEndpoint = config.loginResponseEndpoint || WebAuthnHelpers.defaultRoutes.assertionResult; this.registerChallengeMethod = config.registerChallengeMethod || "POST"; this.registerResponseMethod = config.registerResponseMethod || "POST"; this.loginChallengeMethod = config.loginChallengeMethod || "POST"; this.loginResponseMethod = config.loginResponseMethod || "POST"; this.timeout = config.timeout || 60000; // one minute this.alg = config.alg || coseAlgECDSAWithSHA256; this.binaryEncoding = config.binaryEncoding; // TODO: relying party name this.appName = config.appName || window.location.hostname; this.username = config.username; } /** * Perform WebAuthn registration, including getting options from the server * calling `navigator.credentials.create()`, sending the result to the server, * and validating the end result. Note that this is a convenience wrapper around * {@link requestRegisterOptions}, {@link create}, and {@link sendRegisterResult}. * Each of those classes fires events for various state changes or errors that * can be captured for more advanced applications. * * @return {Promise.<ServerResponse|Error>} Returns a promise that resolves to * a {@link ServerResponse} on success, or rejects with an `Error` on failure. */ register() { fireRegister("start"); // get challenge return this.requestRegisterOptions() .then((serverMsg) => this.create(serverMsg)) .then((newCred) => this.sendRegisterResult(newCred)) .then((msg) => { fireRegister("success"); return msg; }) .catch((err) => { fireRegister("error", err); return Promise.reject(err); }); } /** * Perform WebAuthn authentication, including getting options from the server * calling `navigator.credentials.get()`, sending the result to the server, * and validating the end result. Note that this is a convenience wrapper around * {@link requestLoginOptions}, {@link get}, and {@link sendLoginResult}. * Each of those classes fires events for various state changes or errors that * can be captured for more advanced applications. * * @return {Promise.<ServerResponse|Error>} Returns a promise that resolves to * a {@link ServerResponse} on success, or rejects with an `Error` on failure. */ login() { fireLogin("start"); var self = this; // get challenge return this.requestLoginOptions() .then((serverMsg) => self.get(serverMsg)) .then((assn) => self.sendLoginResult(assn)) .then((msg) => { fireLogin("success"); return msg; }) .catch((err) => { fireLogin("error", err); return Promise.reject(err); }); } /** * A wrapper around a call to `navigator.credentials.create()`, * which is WebAuthn's way of registering a new device with a service. * * @param {CreateOptions} options The desired options for the `navigator.credentials.create()` * call. May be the return value from {@link requestRegisterOptions} or a modified version thereof. * Note that this object contains a `challenge` property which MUST come from the server and that * the server will use to make sure that the credential isn't part of a replay attack. * @return {Promise.<PublicKeyCredentialAttestation|Error>} Returns a Promise that resolves to a * {@link PublicKeyCredentialAttestation} on success (i.e. - the actual return value from `navigator.credentials.create()`), * or rejects with an Error on failure. * @fires WebAuthnApp#userPresenceEvent */ create(options) { if (!(options instanceof CreateOptions)) { throw new Error("expected 'options' to be instance of CreateOptions"); } options.decodeBinaryProperties(); var args = { publicKey: options.toObject() }; args.publicKey.attestation = args.publicKey.attestation || "direct"; delete args.publicKey.status; delete args.publicKey.errorMessage; fireDebug("create-options", args); fireUserPresence("start"); return navigator.credentials.create(args) .then((res) => { fireUserPresence("done"); fireDebug("create-result", res); return res; }) .catch((err) => { fireUserPresence("done"); fireDebug("create-error", err); return Promise.reject(err); }); } /** * A wrapper around a call to `navigator.credentials.get()`, * which is WebAuthn's way of authenticating a user to a service. * * @param {GetOptions} options The desired options for the `navigator.credentials.get()` * call. May be the return value from {@link requestLoginOptions} or a modified version thereof. * Note that this object contains a `challenge` property which MUST come from the server and that * the server will use to make sure that the credential isn't part of a replay attack. * @return {Promise.<PublicKeyCredentialAssertion|Error>} Returns a Promise that resolves to a * {@link PublicKeyCredentialAssertion} on success (i.e. - the actual return value from `navigator.credentials.get()`), * or rejects with an Error on failure. * @fires WebAuthnApp#userPresenceEvent */ get(options) { if (!(options instanceof GetOptions)) { throw new Error("expected 'options' to be instance of GetOptions"); } options.decodeBinaryProperties(); var args = { publicKey: options.toObject() }; delete args.publicKey.status; delete args.publicKey.errorMessage; fireDebug("get-options", args); fireUserPresence("start"); return navigator.credentials.get(args) .then((res) => { fireUserPresence("done"); fireDebug("get-result", res); return res; }) .catch((err) => { fireUserPresence("done"); fireDebug("get-error", err); return Promise.reject(err); }); } /** * Requests the registration options to be used from the server, including the random * challenge to be used for this registration request. * * @return {CreateOptions} The options to be used for creating the new * credential to be registered with the server. The options returned will * have been validated. */ requestRegisterOptions() { var sendData = CreateOptionsRequest.from({ username: this.username, displayName: this.displayName || this.username }); return this.send( this.registerChallengeMethod, this.registerChallengeEndpoint, sendData, CreateOptions ); } /** * Sends the {@link WebAuthn#AuthenticatorAttestationResponse} * to the server. * * @param {WebAuthn#AuthenticatorAttestationResponse} pkCred The public key credential (containing an attesation) returned from `navigator.credentials.get()` * @return {Promise.<ServerResponse|Error>} Resolves to the {@link ServerResponse} from the server on success, or rejects with Error on failure */ sendRegisterResult(pkCred) { if (!(pkCred instanceof window.PublicKeyCredential)) { throw new Error("expected 'pkCred' to be instance of PublicKeyCredential"); } var sendData = CredentialAttestation.from({ username: this.username, rawId: pkCred.rawId, id: pkCred.rawId, response: { attestationObject: pkCred.response.attestationObject, clientDataJSON: pkCred.response.clientDataJSON } }); return this.send( this.registerResponseMethod, this.registerResponseEndpoint, sendData, ServerResponse ); } /** * Requests the login options to be used from the server, including the random * challenge to be used for this registration request. * * @return {GetOptions} The options to be used for creating the new * credential to be registered with the server. The options returned will * have been validated. */ requestLoginOptions() { var sendData = GetOptionsRequest.from({ username: this.username, displayName: this.displayname || this.username }); return this.send( this.loginChallengeMethod, this.loginChallengeEndpoint, sendData, GetOptions ); } /** * This class refers to the dictionaries and interfaces defined in the * {@link https://www.w3.org/TR/webauthn/ WebAuthn specification} that are * used by the {@link WebAuthnApp} class. They are included here for reference. * * @class WebAuthn */ /** * A {@link https://www.w3.org/TR/webauthn/#iface-pkcredential PublicKeyCredential} * that has been created by an authenticator, where the `response` field contains a * {@link https://www.w3.org/TR/webauthn/#authenticatorattestationresponse AuthenticatorAttesationResponse}. * * @typedef {Object} WebAuthn#AuthenticatorAttesationResponse */ /** * A {@link https://www.w3.org/TR/webauthn/#iface-pkcredential PublicKeyCredential} * that has been created by an authenticator, where the `response` field contains a * {@link https://www.w3.org/TR/webauthn/#authenticatorassertionresponse AuthenticatorAssertionResponse}. * * @typedef {Object} WebAuthn#AuthenticatorAssertionResponse */ /** * Sends the {@link WebAuthn#AuthenticatorAssertionResponse} * to the server. * * @param {WebAuthn#AuthenticatorAssertionResponse} assn The assertion returned from `navigator.credentials.get()` * @return {Promise.<ServerResponse|Error>} Resolves to the {@link ServerResponse} from the server on success, or rejects with Error on failure */ sendLoginResult(assn) { if (!(assn instanceof window.PublicKeyCredential)) { throw new Error("expected 'assn' to be instance of PublicKeyCredential"); } var msg = CredentialAssertion.from(assn); return this.send( this.loginResponseMethod, this.loginResponseEndpoint, msg, ServerResponse ); } /** * The lowest-level message sending. Transmits a response over the wire. * * @param {String} method "POST", currently throws if non-POST, but this may be changed in the future. * @param {String} url The REST path to send the data to * @param {Msg} data The data to be sent, in the form of a {@link Msg} object. This method will convert binary fields to their transmittable form and will validate the data being sent. * @param {Function} responseConstructor The constructor of the data to be received, which must inherit from {@link ServerResponse}. The data returned from this function will be of this type, as created by {@link Msg.from} and will be validated by {@link Msg.validate}. * @return {Promise.<Msg|Error>} Returns a Promise that resolves to a {@link Msg} of the type specified by the `responseConstructor` parameter, or rejects with an Error on failure. * @fires WebAuthnApp#debugEvent */ send(method, url, data, responseConstructor) { // check args if (method !== "POST") { return Promise.reject(new Error("why not POST your data?")); } if (typeof url !== "string") { return Promise.reject(new Error("expected 'url' to be 'string', got: " + typeof url)); } if (!(data instanceof Msg)) { return Promise.reject(new Error("expected 'data' to be instance of 'Msg'")); } if (typeof responseConstructor !== "function") { return Promise.reject(new Error("expected 'responseConstructor' to be 'function', got: " + typeof responseConstructor)); } // convert binary properties (if any) to strings data.encodeBinaryProperties(); // validate the data we're sending try { data.validate(); } catch (err) { // console.log("validation error", err); return Promise.reject(err); } // TODO: maybe some day upgrade to fetch(); have to change the mock in the tests too return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); function rejectWithFailed(errorMessage) { fireDebug("send-error", new Error(errorMessage)); return reject(new Error(errorMessage)); } xhr.open(method, url, true); xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); xhr.onload = function() { fireDebug("response-raw", { status: xhr.status, body: xhr.responseText }); if (xhr.readyState !== 4) { return rejectWithFailed("server returned ready state: " + xhr.readyState); } var response; try { response = JSON.parse(xhr.responseText); } catch (err) { if (xhr.status === 200) { return rejectWithFailed("error parsing JSON response: '" + xhr.responseText + "'"); } return rejectWithFailed("server returned status: " + xhr.status); } if (Array.isArray(response)) { response = response[0]; } var msg = responseConstructor.from(response); if (msg.status === "failed") { return rejectWithFailed(msg.errorMessage); } try { msg.validate(); } catch (err) { return rejectWithFailed(err.message); } fireDebug("response", { status: xhr.status, body: msg }); return resolve(msg); }; xhr.onerror = function() { return rejectWithFailed("POST to URL failed: " + url); }; fireDebug("send", data); data = data.toString(); fireDebug("send-raw", data); xhr.send(data); }); } } function fireEvent(type, data) { // console.log("firing event", type); var e = new CustomEvent(type, { detail: data || null }); document.dispatchEvent(e); } /** * Event fired to signal that WebAuthn is not supported in the current context. * * @event WebAuthnApp#notSupportedEvent * * @property {String} type "webauthn-not-supported" * @property {String} detail A human-readable reason for why WebAuthn is currently not supported. */ function fireNotSupported(reason) { fireEvent("webauthn-not-supported", reason); // fireDebug("not-supported", reason); } /** * Debug event, for tracking the internal status of login() and register() * * @event WebAuthnApp#debugEvent * @type {CustomEvent} * @property {String} type "webauthn-debug" * @property {Object} detail The details of the event * @property {String} detail.subtype The sub-type of the "webauth-debug" event. * Options include: "create-options", "create-result", "create-error", "get-options", * "get-result", "get-error", "send-error", "send-raw", "send", "response-raw", "response" * @property {Any} detail.data The data of the event. Varies based on the `subtype` of the event. */ function fireDebug(subtype, data) { fireEvent("webauthn-debug", { subtype: subtype, data: data }); } /** * Event that signals state changes for "User Presence" or "User Verification" testing. * User Presence involves a user simply touching a device (or perhaps a button) to signal * that the user is present and approves of a registration or log in action. On traditional * Security Key devices, such as USB Security Keys, this may be signaled to the user by a * flashing LED light on the device. User Verification is similar to User Presence, but * involves a user performing biometric authentication (fingerprint, face, etc.) or entering * a PIN. This event can be caught and a message can be displayed to the user reminding them * to perform the approperiate action to continue the registration or log in process. * * @event WebAuthnApp#userPresenceEvent * @type {CustomEvent} * @property {String} type "webauthn-user-presence-start" when the User Presence or User Verification is beginning and waiting for the user. * @property {String} type "webauthn-user-presence-done" when the User Presence or User Verification has completed (successfully or unsuccessfully) * @property {null} detail (there are no details for this event) */ function fireUserPresence(state) { switch (state) { case "start": return fireEvent("webauthn-user-presence-start"); case "done": return fireEvent("webauthn-user-presence-done"); default: throw new Error("unknown 'state' in fireUserPresence"); } } /** * Event that signals the state changes for registration. * * @event WebAuthnApp#registerEvent * @type {CustomEvent} * @property {String} type "webauthn-register-start" * @property {String} type "webauthn-register-done" * @property {String} type "webauthn-register-error" * @property {String} type "webauthn-register-success" * @property {null|Error} detail There are no details for these events, except "webauthn-register-error" * which will have the Error in detail. */ function fireRegister(state, data) { switch (state) { case "start": return fireEvent("webauthn-register-start"); case "done": return fireEvent("webauthn-register-done"); case "error": fireEvent("webauthn-register-error", data); return fireEvent("webauthn-register-done"); case "success": fireEvent("webauthn-register-success", data); return fireEvent("webauthn-register-done"); default: throw new Error("unknown 'state' in fireRegister"); } } /** * Event that signals the state changes for log in. * * @event WebAuthnApp#loginEvent * @type {CustomEvent} * @property {String} type "webauthn-login-start" * @property {String} type "webauthn-login-done" * @property {String} type "webauthn-login-error" * @property {String} type "webauthn-login-success" * @property {null|Error} detail There are no details for these events, except "webauthn-login-error" * which will have the Error in detail. */ function fireLogin(state, data) { switch (state) { case "start": return fireEvent("webauthn-login-start"); case "done": return fireEvent("webauthn-login-done"); case "error": fireEvent("webauthn-login-error", data); return fireEvent("webauthn-login-done"); case "success": fireEvent("webauthn-login-success", data); return fireEvent("webauthn-login-done"); default: throw new Error("unknown 'state' in fireLogin"); } } // exports, regardless of whether we're in browser or node.js // note that browser is using global namespace (i.e. - "window"); exp.WebAuthnHelpers = { defaultRoutes: { attestationOptions: "/attestation/options", attestationResult: "/attestation/result", assertionOptions: "/assertion/options", assertionResult: "/assertion/result" }, utils: { coerceToBase64Url, coerceToArrayBuffer, isBrowser } }; exp.Msg = Msg; exp.ServerResponse = ServerResponse; exp.CreateOptionsRequest = CreateOptionsRequest; exp.CreateOptions = CreateOptions; exp.CredentialAttestation = CredentialAttestation; exp.GetOptionsRequest = GetOptionsRequest; exp.GetOptions = GetOptions; exp.CredentialAssertion = CredentialAssertion; exp.WebAuthnOptions = WebAuthnOptions; exp.WebAuthnApp = WebAuthnApp; }()); <filename>node_modules/@nodeutils/defaults-deep/lib/index.js "use strict"; var _ = require("lodash"); module.exports = function () { var output = {}; _.toArray(arguments).reverse().forEach(function (item) { _.mergeWith(output, item, function (objectValue, sourceValue) { return _.isArray(sourceValue) ? sourceValue : undefined; }); }); return output; };<reponame>Dmarceli/ScheduleMeetingWebApp "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getRpcWorkerData = exports.createRpcWorker = void 0; const child_process = __importStar(require("child_process")); const process = __importStar(require("process")); const wrap_rpc_1 = require("./wrap-rpc"); const WORKER_DATA_ENV_KEY = 'WORKER_DATA'; function createRpcWorker(modulePath, data, memoryLimit) { const options = { env: Object.assign(Object.assign({}, process.env), { [WORKER_DATA_ENV_KEY]: JSON.stringify(data || {}) }), stdio: ['inherit', 'inherit', 'inherit', 'ipc'], serialization: 'advanced', }; if (memoryLimit) { options.execArgv = [`--max-old-space-size=${memoryLimit}`]; } let childProcess; let remoteMethod; const worker = { connect() { if (childProcess && !childProcess.connected) { childProcess.kill('SIGTERM'); childProcess = undefined; remoteMethod = undefined; } if (!(childProcess === null || childProcess === void 0 ? void 0 : childProcess.connected)) { childProcess = child_process.fork(modulePath, options); remoteMethod = (0, wrap_rpc_1.wrapRpc)(childProcess); } }, terminate() { if (childProcess) { childProcess.kill('SIGTERM'); childProcess = undefined; remoteMethod = undefined; } }, get connected() { return Boolean(childProcess === null || childProcess === void 0 ? void 0 : childProcess.connected); }, get process() { return childProcess; }, }; return Object.assign((...args) => { if (!worker.connected) { // try to auto-connect worker.connect(); } if (!remoteMethod) { return Promise.reject('Worker is not connected - cannot perform RPC.'); } return remoteMethod(...args); }, worker); } exports.createRpcWorker = createRpcWorker; function getRpcWorkerData() { return JSON.parse(process.env[WORKER_DATA_ENV_KEY] || '{}'); } exports.getRpcWorkerData = getRpcWorkerData; /* * Test string encodeURI() for a long ASCII snippet (fast path). */ if (typeof print !== 'function') { print = console.log; } function test() { var txt = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'; var i; for (i = 0; i < 10; i++) { txt = txt + txt; } print(txt.length); for (i = 0; i < 1000; i++) { void encodeURI(txt); } } try { test(); } catch (e) { print(e.stack || e); throw e; } <reponame>stdlib-js/stdlib-js.github.io /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // /** * Removes a `@stdlib/` prefix from a package name. * * @private * @param {string} pkg - package name * @returns {string} package name with the `@stdlib/` path prefix removed * * @example * var pkg = deprefix( '@stdlib/foo/bar' ); * // returns 'foo/bar' */ function deprefix( pkg ) { return pkg.replace( /^@stdlib\//, '' ); } // EXPORTS // module.exports = deprefix; <filename>web/js/dojo/src/string/__package__.js dojo.kwCompoundRequire({ common: [ "dojo.string", "dojo.string.common", "dojo.string.extras", "dojo.string.Builder" ] }); dojo.provide("dojo.string.*"); import { parser } from './parser/example' import exampleDb from './exampleDb' /* eslint-env jasmine */ describe('when parsing an info graph it', function () { beforeEach(function () { parser.yy = exampleDb }) it('should handle an info definition', function () { const str = 'info\nsay: hello' parser.parse(str) }) it('should handle an showMessage statement definition', function () { const str = 'info\nshowInfo' parser.parse(str) }) }) <reponame>Kevin-Ol/project-movie-card-library-crud import React from 'react'; import 'mutationobserver-shim'; import { Router } from 'react-router-dom'; import { screen, render, waitFor, cleanup, fireEvent } from '@testing-library/react'; import { createBrowserHistory } from 'history'; import App from '../App'; import { movieAPI, readMovies, resetStorage } from './helpers'; jest.mock('../services/movieAPI'); const renderPath = (path) => { const history = createBrowserHistory(); history.push(path); const { ...resources } = render( <Router history={ history }> <App /> </Router>, ); return { ...resources }; }; describe('4 - Faça uma requisição para buscar o filme que deverá ser renderizado dentro de `Movie Details`', () => { it('Será validado se `MovieDetails` exibe o texto "Carregando..." enquanto estiver fazendo a requisição', async () => { for (const movie of readMovies()) { cleanup(); const { getByText } = renderPath(`/movies/${movie.id}`); expect(getByText('Carregando...')); } }); it('Será validado se `MovieDetails` exibe o título, o subtítulo, a sinopse, a imagem e o gênero do filme', async () => { for (const movie of readMovies()) { const { unmount } = renderPath(`/movies/${movie.id}`); await waitFor(() => movieAPI.getMovie(movie.id)); expect(screen.getAllByText(readMovies()[movie.id - 1].title, { exact: false }).length).toBeGreaterThanOrEqual(1); expect(screen.getAllByText(readMovies()[movie.id - 1].subtitle, { exact: false }).length) .toBeGreaterThanOrEqual(1); expect(screen.getByText(readMovies()[movie.id - 1].storyline, { exact: false })).toBeTruthy; let image = screen.getByAltText('Movie Cover').src.split('/').slice(-2).join('/'); expect(image).toEqual(readMovies()[movie.id - 1].imagePath); expect(screen.getAllByText(readMovies()[movie.id - 1].genre, { exact: false })).toBeTruthy; unmount(); } }); it('Será validado se `MovieDetails` contém um botão com o texto "VOLTAR" que redireciona para a página inicial', async () => { for (const movie of readMovies()) { const { unmount, findByText } = renderPath(`/movies/${movie.id}`); await waitFor(() => movieAPI.getMovie(movie.id)); const backButton = await findByText('VOLTAR'); expect(backButton.href).toBe('http://localhost/'); unmount(); } }); it('Será validado se `MovieDetails` contém um botão com o texto "EDITAR" que redireciona para a página de edição de filme', async () => { for (const movie of readMovies()) { const { unmount, findByText } = renderPath('/movies/' + movie.id); await waitFor(() => movieAPI.getMovie(movie.id)); const backButton = await findByText('EDITAR'); expect(backButton.href).toBe(`http://localhost/movies/${movie.id}/edit`); unmount(); } }); }); describe('7 - Adicione um link para deletar um cartão em `MovieDetails`', () => { it('Será validado se `MovieDetails` contém um link com o texto "DELETAR"', async () => { for (const movie of readMovies()) { const { unmount, findByText } = renderPath(`/movies/${movie.id}`); await waitFor(() => movieAPI.getMovie(movie.id)); const deleteButton = await findByText('DELETAR'); expect(deleteButton.href).toBe('http://localhost/'); unmount(); } }); it('Será validado se o link "DELETAR" faz uma requisição para a API para excluir o filme em questão', async () => { const movieCardLength = 4; resetStorage(); const deletedMovie = readMovies()[2]; renderPath('/movies/3'); const deleteButton = await screen.findByText('DELETAR'); fireEvent.click(deleteButton); await waitFor(() => movieAPI.getMovies()); expect(window.location.pathname).toBe('/'); cleanup(); renderPath('/'); await waitFor(() => movieAPI.getMovies()); expect(screen.getAllByTestId('movie-card').length).toBe(movieCardLength); expect(screen.queryByText(deletedMovie.title)).toBeNull(); }); }); <filename>index.js import db from './src/Config/dbConnect.js'; import livros from './src/Models/Livro.js'; import express from 'express'; import bodyParser from 'body-parser'; db.on("error", console.error.bind(console, "Erro de Conexão")); db.once("open", () => { console.log('conexão com o banco feito com sucesso'); }) const app = express(); app.use(bodyParser.json()); const port = process.env.PORT || 3000; /*const livros = [ {id: 1, titulo: 'O Senhor dos Anéis', autor: '<NAME>'}, {id: 2, titulo: 'O Hobbit', autor: '<NAME>'}, {id: 3, titulo: 'O Senhor dos Anéis - A Sociedade do Anel', autor: '<NAME>'}, {id: 4, titulo: 'O Senhor dos Anéis - As Duas Torres', autor: '<NAME>'}, {id: 5, titulo: 'O Senhor dos Anéis - As Ilhas do Leão', autor: '<NAME>'}, {id: 6, titulo: 'O Senhor dos Anéis - As Trevas do Fim do Universo', autor: '<NAME>'}, ]*/ app.listen(port, () => { console.log(`Server is running on port ${port}`); }) app.get('/teste', (req, res) => { res.send('Testando servidor!'); }) app.get('/livros', async(req, res) => { res.send(livros); }) app.post('/livros', (req, res) => { const livro = req.body; livros.push(livro); res.send(livro); }) app.get('/livros/:id', (req, res) => { const livro = buscaLivro(req.params.id); res.send(livros[livro]); }) app.put('/livros/:id', (req, res) => { const index = buscaLivro(req.params.id); livros[index] = req.body; res.send(livros[index]); }) app.delete('/livros/:id', (req, res) => { const index = buscaLivro(req.params.id); livros.splice(index, 1); res.send(livros); }) function buscaLivro(id){ return livros.findIndex(livro => livro.id == id); }<gh_stars>0 /***************************************************************** * Create new typescript-express-starter project. * created by <NAME>, 12/18/2019 *****************************************************************/ const path = require('path'); const fs = require('fs'); const editJsonFile = require('edit-json-file'); const childProcess = require('child_process'); const ncp = require('ncp').ncp; const inquirer = require('inquirer'); const ora = require('ora'); const chalk = require('chalk'); async function tsExpressStarter(projectName) { try { const template = await selectedTemplates(); await copyProjectFiles(projectName, template); updatePackageJson(projectName); const dependencies = getDependencies(template); installDependencies(projectName, dependencies); ora(`${chalk.green('Complete setup project')}`).succeed(); } catch (error) { ora(chalk.red('Please leave this error as an issue.')).fail(); console.error(error); } }; async function selectedTemplates() { const directorys = getDirectorys(); const directoryChoices = [...directorys, new inquirer.Separator()]; const { selectedTemplates } = await inquirer.prompt([ { type: 'list', name: 'selectedTemplates', message: 'Select a templates', choices: directoryChoices } ]); return selectedTemplates; }; function getDirectorys() { let directorys = []; fs.readdirSync(__dirname, { withFileTypes: true }) .forEach(p => { const dir = p.name; if (p.isDirectory()) { directorys.push(dir); } }); return directorys; }; function copyProjectFiles(destination, directory) { ora(' copying project...').stopAndPersist({ symbol: '[ 1 / 3 ] 🔍 '}); const prjFolder = `./${directory}`; const source = path.join(__dirname, prjFolder); return new Promise((resolve, reject) => { ncp.limit = 16; ncp(source, destination, function(err) { if (err) reject(err); resolve(); }); }); }; function updatePackageJson(destination) { let file = editJsonFile(destination + "/package.json", { autosave: true }); file.set("name", path.basename(destination)); }; function getDependencies(directory) { ora(' fetching dependencies...').stopAndPersist({ symbol: '[ 2 / 3 ] 🚚 '}); let dependencies = 'class-transformer class-validator cors envalid express helmet hpp jest morgan ts-jest ts-node typescript'; let devDependencies = '@types/cors @types/express @types/helmet @types/hpp @types/jest @types/morgan @types/node @types/supertest supertest tslint tslint-config-airbnb'; switch (directory) { case 'mongoose': { dependencies += ' mongoose dotenv'; devDependencies += ' @types/mongoose'; } break; } return { dependencies, devDependencies }; }; function installDependencies(destination, { dependencies, devDependencies }) { ora(' linking dependencies...').stopAndPersist({ symbol: '[ 3 / 3 ] 🔗 '}); const options = { cwd: destination }; childProcess.execSync('npm i -s ' + dependencies, options); childProcess.execSync('npm i -D ' + devDependencies, options); }; module.exports = tsExpressStarter; // this function helps us to check if a string starts with a specified substring or not if (!String.prototype.startsWith) { String.prototype.startsWith = function (str) { return !this.indexOf(str); } } //function to check if a given element has a particular class or not function hasClassName(objElement, strClass) { // if there is a class if (objElement.className) { // the classes are just a space separated list, so first get the list var arrList = objElement.className.split(' '); // get uppercase class for comparison purposes var strClassUpper = strClass.toUpperCase(); // find all instances and remove them for (var i = 0; i < arrList.length; i++) { // if class found if (arrList[i].toUpperCase() == strClassUpper) { // we found it return true; } } } // if we got here then the class name is not there return false; } //deforayValidator literal var deforayValidator = { init: function (settings) { this.settings = settings; this.form = document.getElementById(this.settings["formId"]); //console.log(this.form); formInputs = jQuery("input[type='text'],input[type='password'],textarea,select"); // change color of inputs on focus for (i = 0; i < formInputs.length; i++) { formInputs[i].onfocus = function () { this.style.background = "#FFFFFF"; } }; var error = deforayValidator.validate(); if (error == "" || error == null) { return true; } else { deforayValidator.printError(error); return false; } }, validate: function () { error = ''; this.form = document.getElementById(this.settings["formId"]); formInputs = this.form.getElementsByTagName('*'); useTitleToShowMessage = true; if (this.settings["useTitle"] != 'undefined' && this.settings["useTitle"] != null && this.settings["useTitle"] == false) { useTitleToShowMessage = false; } error = deforayValidatorInternal(formInputs, useTitleToShowMessage); return error; }, printError: function (error) { alert(error,'err'); // alert(error,'err'); return false; } }; // returns true if the string is not empty function isRequired(str) { if (str == null || str.length == 0 || $.trim(str) == '') { return true; } else { return false; } //return (str == null) || (str.length == 0); } // returns true if the string is a valid email function isEmail(str, required) { if (required) { if ((str == null || str.length == 0)) return false; } else if (str != null && str.length != 0) { // var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i; return re.test(str); } return true; // else return true } // returns true if the string only contains characters 0-9 and is not null function isNumeric(str, required) { if (required) { if ((str == null || str.length == 0)) return false; } else { if (str != "") return !isNaN(parseFloat(str)) && isFinite(str); } return true; } // returns true if the number have the 10 digit, only contains 0-9 and is not null function isMobile(no, required) { var first = no.charAt(0); if (required) { if ((isNaN(no) == true) || (no == null || no.length != 10) || (first == 1) || (first == 2) || (first == 3) || (first == 4) || (first == 5)) { return false; } else { return true; } } else { if (no == "") { return true; } if ((isNaN(no) == true) || (no.length != 10) || (first == 1) || (first == 2) || (first == 3) || (first == 4) || (first == 5)) { return false; } else { return true; } } } // returns true if the password have the 6 digit and is not null function isPassword(no, required) { if (required) { // if (no.length < 6) return false; if (no == null) { return false; } else { return true; } } else { if (no == "") { return true; } // if (no.length < 6) { // return false; // } else { return true; // } } } // returns true if the username have the 3 digit and is not null function isUsername(no, required) { if (required) { if (no.length < 3) return false; if ((isNaN(no) == false) || no == null) { return false; } else { return true; } } else { if (no == "") { return true; } if (no.length < 3) return false; if (isNaN(no) == false) { return false; } else { return true; } } } // returns true if the Bootstrap Selected and is not null function isBootstrapSelect(no, required) { console.log($('.isBootstrapSelect').val()); if (selectb > 0) { return true; } else { return false; } } // returns true if the number have the 6 digit, only contains 0-9 and is not null function isPincode(no, required) { var first = no.charAt(0); if (required) { if ((isNaN(no) == true) || (no == null || no.length != 6)) { return false; } else { return true; } } else { if (no == "") { return true; } if ((isNaN(no) == true) || (no.length != 6)) { return false; } else { return true; } } } // returns true if the string only contains characters A-Z or a-z function isAlpha(str, required) { if (required) { if ((str == null || str.length == 0)) return false; } var re = /[a-zA-Z]/; if (re.test(str)) return true; return false; } // returns true if the string only contains characters 0-9 A-Z or a-z function isAlphaNum(str, required) { if (required) { if ((str == null || str.length == 0)) return false; } // var re = /[0-9a-zA-Z]/ var re = /^[0-9A-Za-z]+$/; if (re.test(str)) return true; return false; } // returns true if the string only contains characters OTHER THAN 0-9 A-Z or a-z function isSymbol(str, required) { if (required) { if ((str == null || str.length == 0)) return false; } var re = /[^0-9a-zA-Z]/; if (re.test(str)) return true; return false; } // checks if the string is of a specified minimum length or not function minLength(str, len) { if ((str == null || str.length == 0)) return false; if (str.length < len) { return false; } else { return true; } } // checks if the string is within a specified maximum length or not function maxLength(str, len) { if ((str == null || str.length == 0)) return false; if (str.length > len) { return false; } else { return true; } } // checks if the string is exactly equal to the specified length or not function exactLength(str, len) { if ((str == null || str.length == 0)) return false; if (str.length == len) { return true; } else { return false; } } //confirm password validation function confirmPassword(name) { var elements = document.getElementsByName(name); //assuming that there will be only 2 fields with this name if (elements[0].value == elements[1].value) { return true; } else { return false; } } //checkbox or radio required validation function isRequiredCheckBox(name) { var flag = false; var elements = document.getElementsByName(name); size = elements.length; count = 0; for (var i = 0; i < size; i++) { if (elements[i].checked) { flag = true; break; } else { continue; } } return flag; } function findPos(obj) { var curleft = curtop = 0; if (obj.offsetParent) { curleft = obj.offsetLeft curtop = obj.offsetTop while (obj = obj.offsetParent) { curleft += obj.offsetLeft curtop += obj.offsetTop } } return [curleft, curtop]; } function deforayValidatorInternal(formInputs, useTitleToShowMessage) { // change color of inputs on focus for (i = 0; i < formInputs.length; i++) { classes = formInputs[i].className; if (classes == "" || classes == null) { valid = true; } var parts = classes.split(" "); if (hasClassName(formInputs[i], "useTitle")) { elementTitle = formInputs[i].title; } else if (useTitleToShowMessage) { elementTitle = formInputs[i].title; } else { elementTitle = ""; } for (var cCount = 0; cCount < parts.length; cCount++) { var required = false; if (parts[cCount] == "isRequired") { required = true; if (formInputs[i].type == 'checkbox' || formInputs[i].type == 'radio') { valid = isRequiredCheckBox(formInputs[i].name); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Please select " + formInputs[i].name; } } else { var valu = (formInputs[i].value); valid = !isRequired(valu); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Please don't leave this field blank"; } } } else if (parts[cCount] == "isEmail") { var valu = (formInputs[i].value); valid = isEmail(valu, required); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Please enter a valid email id"; } } else if (parts[cCount] == "isNumeric") { valid = isNumeric(formInputs[i].value, required); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Please enter a valid number."; } } else if (parts[cCount] == "isAlpha") { valid = isAlpha(formInputs[i].value, required); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "This field can only contain alphabets and numbers."; } } else if (parts[cCount] == "isAlphaNum") { valid = isAlphaNum(formInputs[i].value, required); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "This field can only contain alphabets and numbers."; } } else if (parts[cCount] == "isSymbol") { valid = isSymbol(formInputs[i].value, required); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "This field cannot contain alphabets and numbers."; } } else if (parts[cCount].startsWith("minLength")) { innerParts = parts[cCount].split("_"); valid = minLength(formInputs[i].value, innerParts[1]); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Minimum " + innerParts[1] + " characters required"; } } else if (parts[cCount].startsWith("maxLength")) { innerParts = parts[cCount].split("_"); valid = maxLength(formInputs[i].value, innerParts[1]); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "More than " + innerParts[1] + " characters not allowed"; } } else if (parts[cCount].startsWith("exactLength")) { innerParts = parts[cCount].split("_"); valid = exactLength(formInputs[i].value, innerParts[1]); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "This field should have exactly " + innerParts[1] + " characters"; } } else if (parts[cCount] == "confirmPassword") { valid = confirmPassword(formInputs[i].name); console.log(valid); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Please make sure password and confirm password are same"; } } else if (parts[cCount] == "isMobile") { valid = isMobile(formInputs[i].value, required); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Please make sure your entered mobile number correct or not!"; } } else if (parts[cCount] == "isPassword") { valid = isPassword(formInputs[i].value, required); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Must contain at least 6 or more characters password"; } } else if (parts[cCount] == "isUsername") { valid = isUsername(formInputs[i].value, required); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Must contain at least 3 or more characters username"; } } else if (parts[cCount] == "isBootstrapSelect") { valid = isBootstrapSelect(); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Please make sure choosing atleast one zones!"; } } else if (parts[cCount] == "isPincode") { valid = isPincode(formInputs[i].value, required); if (elementTitle != null && elementTitle != "") { errorMsg = elementTitle; } else { errorMsg = "Please make sure your entered pincode number correct or not!"; } } else { valid = true; } if (!valid) { formInputs[i].style.background = "#FFFF99"; formInputs[i].style.border = "1px solid #CF3339"; $('.infocus').removeClass('infocus'); $(formInputs[i]).addClass('infocus'); //formInputs[i].focus(); //myPos = findPos(formInputs[i]); //scrollTo(myPos[0],myPos[1]); return errorMsg; } } } }<reponame>Lambda-School-Labs/LabsPT12-Express_Groomer-TeamF-FE<gh_stars>0 import { axiosWithAuth } from '../../utils/axiosWithAuth'; import { INITIALIZE_USER } from './userActionTypes'; import { POST_USERID_INITIAL, POST_USERID_SUCCESS, POST_USERID_FAILURE, } from './userActionTypes'; import { POST_PROFILE_INITIAL, POST_PROFILE_SUCCESS, EDIT_PROFILE_SUCCESS, POST_PROFILE_FAILURE, } from './userActionTypes'; export const initializeUser = (authService, history) => async dispatch => { try { var user = await authService.getUser(); } catch (err) { console.log(err); } if (!authService.getAuthState().isAuthenticated) return; const { sub, email } = user; dispatch({ type: INITIALIZE_USER, payload: { initialized: true, okta_uid: sub, email, }, }); }; export const postUserId = userId => async dispatch => { dispatch({ type: POST_USERID_INITIAL, payload: true }); try { dispatch({ type: POST_USERID_SUCCESS, payload: userId }); } catch (err) { dispatch({ type: POST_USERID_FAILURE, payload: err }); } }; export const postProfile = (userData, editing, id) => async dispatch => { dispatch({ type: POST_PROFILE_INITIAL, payload: true }); try { if (editing) { const dataPlusId = { ...userData, id }; axiosWithAuth() .put(`/profiles`, dataPlusId) .then(response => { dispatch({ type: EDIT_PROFILE_SUCCESS, payload: response.data }); }) .catch(err => { dispatch({ type: POST_PROFILE_FAILURE, payload: err }); }); } else { axiosWithAuth() .get(`/profiles/${userData.sub}`) .then(response => { dispatch({ type: POST_PROFILE_SUCCESS, payload: response.data }); }) .catch(err => { dispatch({ type: POST_PROFILE_FAILURE, payload: err }); }); } } catch (err) { dispatch({ type: POST_PROFILE_FAILURE, payload: err }); } }; <reponame>xdg-forks/evergreen<filename>public/static/js/spawned_hosts.js mciModule.controller('SpawnedHostsCtrl', ['$scope', '$window', '$timeout', '$q', '$location', 'mciSpawnRestService', 'notificationService', function ($scope, $window, $timeout, $q, $location, mciSpawnRestService, notificationService) { $scope.userTz = $window.userTz; $scope.defaultRegion = $window.defaultRegion; $scope.hosts = []; $scope.modalOpen = false; $scope.spawnTask = $window.spawnTask; $scope.spawnDistro = $window.spawnDistro; // variables for spawning a new host $scope.spawnableDistros = []; $scope.selectedDistro = {}; $scope.userKeys = []; $scope.selectedKey = {}; $scope.spawnInfo = {}; $scope.curHostData; $scope.curVolumeData; $scope.maxHostsPerUser = $window.maxHostsPerUser; $scope.maxUnexpirableHostsPerUser = $window.maxUnexpirableHostsPerUser; $scope.maxUnexpirableVolumesPerUser = $window.maxUnexpirableVolumesPerUser; $scope.maxVolumeSizePerUser = $window.maxVolumeSizePerUser; $scope.spawnReqSent = false; $scope.volumeReqSent = false; $scope.useTaskConfig = false; $scope.isVirtualWorkstation = false; $scope.noExpiration = false; $scope.volumeSizeDefault = 500; $scope.homeVolumeSize = $scope.volumeSizeDefault; $scope.homeVolumeID; $scope.volumeAttachHost; $scope.createVolumeInfo = { 'type': 'gp2', 'zone': 'us-east-1a', }; $scope.allowedInstanceTypes = []; $scope.volumes = []; // max of 7 days time to expiration $scope.maxHoursToExpiration = 24 * 7; $scope.saveKey = false; $scope.currKeyName = ''; $scope.newKey = { 'name': '', 'key': '', }; $scope.resourceTypes = ["hosts", "volumes"]; $scope.currentResourceType = function() { var params = $location.search() if ($scope.resourceTypes.includes(params["resourcetype"])) { return params["resourcetype"]; } $location.search("resourcetype", $scope.resourceTypes[0]) return $scope.resourceTypes[0]; }() var epochTime = moment('Jan 1, 1970'); $scope.hostSortOrders = [{ name: 'Status', by: 'status' }, { name: 'Uptime', by: 'uptime' }, { name: 'Create Time', by: 'creation_time', reverse: false }, { name: 'Distro', by: 'distro' } ]; $scope.hostSortBy = $scope.hostSortOrders[0]; $scope.setHostSortBy = function (order) { $scope.hostSortBy = order; }; $scope.volumeSortOrders = [{ name: 'Status', by: 'status' }, { name: 'Expires In', by: 'expiration', reverse: false } ]; $scope.volumeSortBy = $scope.volumeSortOrders[0]; $scope.setVolumeSortBy = function (order) { $scope.volumeSortBy = order; }; $scope.setResourceType = function (rtype) { $location.search("resourcetype", rtype); var id = null; if (rtype == "hosts" && $scope.curHostData) { id = $scope.curHostData.id; } if (rtype == "volumes" && $scope.curVolumeData) { id = $scope.curVolumeData.volume_id; } $location.search("id", id); $scope.currentResourceType = rtype; } $scope.isHomeVolume = function(volume) { for (var i = 0; i < $scope.hosts.length; i++) { if ($scope.hosts[i].home_volume_id === volume.volume_id) { return true; } } return false; }; // Spawn REST API calls $scope.fetchSpawnedHosts = function () { mciSpawnRestService.getSpawnedHosts( 'hosts', {}, { success: function (resp) { var hosts = resp.data; _.each(hosts, function (host) { $scope.computeUptime(host); $scope.computeHostExpirationTimes(host); host.selectedInstanceType = host.instance_type; if (host.display_name == "") { host.display_name = host.id; } host.originalDisplayName = host.display_name; if ($location.search()["id"] == host.id) { $scope.setSelectedHost(host) } }); $scope.hosts = hosts }, error: function (resp) { // Avoid errors when leaving the page because of a background refresh if ($scope.hosts == null && !$scope.errorFetchingHosts) { notificationService.pushNotification('Error fetching spawned hosts: ' + resp.data.error, 'errorHeader'); $scope.errorFetchingHosts = true; } } } ); }; $scope.updateSpawnedHosts = function () { mciSpawnRestService.getSpawnedHosts( 'hosts', {}, { success: function (resp) { var hosts = resp.data; _.each(hosts, function (host) { for (var i = 0; i < $scope.hosts.length; i++) { if ($scope.hosts[i].id !== host.id && $scope.hosts[i].id !== host.tag) { continue; } $scope.computeUptime(host); $scope.computeHostExpirationTimes(host); $scope.hosts[i].uptime = host.uptime; $scope.hosts[i].expires_in = host.expires_in; $scope.hosts[i].status = host.status; $scope.hosts[i].id = host.id; $scope.hosts[i].host = host.host; $scope.hosts[i].start_time = host.start_time; $scope.hosts[i].home_volume_id = host.home_volume_id; if ($scope.hosts[i].instance_type === undefined || $scope.hosts[i].instance_type === "") { $scope.hosts[i].instance_type = host.instance_type; } if ($scope.hosts[i].selectedInstanceType === undefined || $scope.hosts[i].selectedInstanceType === "") { $scope.hosts[i].selectedInstanceType = host.instance_type; } } }); } } ) } $scope.fetchVolumes = function () { mciSpawnRestService.getVolumes( { success: function (resp) { var volumes = resp.data; _.each(volumes, function (volume) { $scope.computeVolumeExpirationTimes(volume); if (volume.display_name == "") { volume.display_name = volume.volume_id; } volume.originalDisplayName = volume.display_name; if (volume.host_id) { volume.status = "mounted"; } else { volume.status = "free"; } if ($location.search()["id"] == volume.volume_id) { $scope.setSelectedVolume(volume) } }); $scope.volumes = volumes; $scope.homeVolumeSize = Math.min($scope.volumeSizeDefault, $scope.availableVolumeSize()); $scope.createVolumeInfo.size = $scope.homeVolumeSize; }, error: function (resp) { // Avoid errors when leaving the page because of a background refresh if ($scope.volumes == null && !$scope.errorFetchingVolumes) { notificationService.pushNotification('Error fetching volumes: ' + resp.data.error, 'errorHeader'); $scope.errorFetchingVolumes = true; } } } ); }; $scope.computeHostExpirationTimes = function (host) { if (!host.isTerminated && new Date(host.expiration_time) > new Date("0001-01-01T00:00:00Z")) { if (host.no_expiration) { host.expires_in = "never"; host.original_expiration = null; host.current_expiration = null; host.modified_expiration = new Date(); } else { var expiretime = moment().diff(host.expiration_time, 'seconds'); host.expires_in = moment.duration(expiretime, 'seconds').humanize(); host.original_expiration = new Date(host.expiration_time); host.current_expiration = new Date(host.expiration_time); host.modified_expiration = new Date(host.expiration_time); } } } $scope.computeVolumeExpirationTimes = function (volume) { if (volume.no_expiration) { volume.expires_in = "never"; } else { var expiretime = moment().diff(volume.expiration, 'seconds'); volume.expires_in = moment.duration(expiretime, 'seconds').humanize(); } volume.original_expiration = new Date(volume.expiration); volume.current_expiration = new Date(volume.expiration); volume.original_no_expiration = volume.no_expiration; } $scope.computeUptime = function (host) { host.isTerminated = host.status === 'terminated'; host.isStarted = true; const terminateTime = moment(host.termination_time); const startTime = moment(host.start_time); // check if the host is terminated to determine uptime if (host.isTerminated && terminateTime > epochTime) { const uptime = terminateTime.diff(startTime, 'seconds'); host.uptime = moment.duration(uptime, 'seconds').humanize(); } else if (host.status === 'stopped' || host.start_time == "0001-01-01T00:00:00Z") { host.uptime = ""; host.isStarted = false; } else { const uptime = moment().diff(startTime, 'seconds'); host.uptime = moment.duration(uptime, 'seconds').humanize(); } } $scope.setCurrentExpirationOnClick = function () { // host previously had an expiration if ($scope.curHostData.current_expiration != null) { $scope.curHostData.modified_expiration = new Date($scope.curHostData.current_expiration); $scope.curHostData.current_expiration = null; } else { $scope.curHostData.current_expiration = new Date($scope.curHostData.modified_expiration); } } // Load immediately, load again in 5 seconds to pick up any slow // spawns / terminates from the previous post since they are async, and // every 60 seconds after that to pick up changes. $timeout($scope.fetchSpawnedHosts, 1); $timeout($scope.updateSpawnedHosts, 5000); setInterval(function () { $scope.updateSpawnedHosts(); }, 60000); $timeout($scope.fetchVolumes, 1); // Returns true if the user can spawn another host. If hosts have not been initialized it // assumes true. $scope.availableHosts = function () { return ($scope.hosts == null) || ($scope.hosts.length < $scope.maxHostsPerUser) }; $scope.availableUnexpirableHosts = function () { return $scope.maxUnexpirableHostsPerUser - _.where($scope.hosts, { original_expiration: null }).length; } $scope.unexpirableHostEnabled = function () { return $scope.availableUnexpirableHosts() > 0 || $scope.curHostData && ($scope.curHostData.no_expiration || $scope.curHostData.original_expiration == null) }; $scope.availableVolumeSize = function () { var totalSize = $scope.maxVolumeSizePerUser; return _.reduce($scope.volumes, function(availableSize, v){ return availableSize - v.size;}, totalSize); }; $scope.invalidHostOptions = function() { if ($scope.isVirtualWorkstation && ($scope.homeVolumeID === undefined || $scope.homeVolumeID === "")) { return $scope.invalidVolumeSize($scope.homeVolumeSize); } return false; }; $scope.invalidVolumeSize = function(size) { return $scope.availableVolumeSize() - size < 0; }; $scope.availableUnexpirableVolumes = function () { return $scope.maxUnexpirableVolumesPerUser - _.where($scope.volumes, { no_expiration: true }).length; } $scope.unexpirableVolumeEnabled = function () { return $scope.availableUnexpirableVolumes() > 0 || ($scope.curVolumeData && $scope.curVolumeData.no_expiration) } $scope.generatePassword = function () { $scope.curHostData.password = _.shuffle( SHA1(document.cookie + _.now()).slice(0, 9).concat( _.take( _.shuffle('~!@#$%^&*_-+=:,.?/'), 3 ).join('') ) ).join('') } $scope.copyPassword = function () { var el = $('#password-input'); el.focus(); el.select(); document.execCommand('copy'); } $scope.fetchSpawnableDistros = function (selectDistro, cb) { mciSpawnRestService.getSpawnableDistros( 'distros', {}, { success: function (resp) { var distros = resp.data; $scope.setSpawnableDistros(distros, selectDistro); // If there is a callback to run after the distros were fetched, // execute it. if (cb) { cb(); } }, error: function (resp) { notificationService.pushNotification('Error fetching spawnable distros: ' + resp.data.error, 'errorHeader'); } } ); }; $scope.fetchAllowedInstanceTypes = function () { mciSpawnRestService.getAllowedInstanceTypes( 'types', $scope.curHostData.host_type, {}, { success: function (resp) { $scope.allowedInstanceTypes = resp.data; }, error: function (resp) { notificationService.pushNotification('Error fetching allowed instance types: ' + resp.data.error, 'errorHeader') } } ) } $scope.fetchUserKeys = function () { mciSpawnRestService.getUserKeys( 'keys', {}, { success: function (resp) { $scope.setUserKeys(resp.data); }, error: function (resp) { notificationService.pushNotification('Error fetching user keys: ' + resp.data.error, 'errorHeader'); } } ); }; $scope.setHostDisplayName = function (host) { mciSpawnRestService.updateHostDisplayName(host.id, host.display_name, { success: function (resp) { host.originalDisplayName = host.display_name; }, error: function (resp) { notificationService.pushNotification('Error setting host display name: ' + resp.data.error, 'errorHeader'); } } ); }; $scope.resetHostDisplayName = function (host) { host.display_name = host.originalDisplayName; }; $scope.setVolumeDisplayName = function (volume) { mciSpawnRestService.updateVolume("changeVolumeDisplayName", volume.volume_id, {"new_name": volume.display_name}, { success: function (resp) { volume.originalDisplayName = volume.display_name; }, error: function (resp) { notificationService.pushNotification('Error setting volume display name: ' + resp.data.error, 'errorHeader'); } } ); }; $scope.resetVolumeDisplayName = function (volume) { volume.display_name = volume.originalDisplayName; }; $scope.getHomeVolumeDisplayName = function () { if (!$scope.homeVolumeID) { return "New Volume"; } return $scope.getVolumeDisplayName($scope.homeVolumeID); } $scope.getVolumeDisplayName = function(volumeID) { volume = $scope.volumes.find(volume => {return volume.volume_id == volumeID}) if (volume) { return $scope.concatName(volume.volume_id, volume.display_name); } return volumeID; } $scope.getHostDisplayName = function(hostID) { host = $scope.hosts.find(host => {return host.id == hostID}) if (host) { return $scope.concatName(host.id, host.display_name); } return hostID; } $scope.concatName = function(id, displayName) { var name = id; if (displayName && displayName != id) { name += " (" + displayName + ")"; } return name; }; $scope.setHomeVolume = function (volume) { if (volume) { $scope.homeVolumeID = volume.volume_id; } else { $scope.homeVolumeID = ""; } } $scope.setAttachToHost = function (host) { $scope.volumeAttachHost = host; } $scope.spawnHost = function () { $scope.spawnReqSent = true; $scope.spawnInfo.spawnKey = $scope.selectedKey; $scope.spawnInfo.saveKey = $scope.saveKey; $scope.spawnInfo.userData = $scope.userdata; $scope.spawnInfo.is_virtual_workstation = $scope.isVirtualWorkstation; if ($scope.isVirtualWorkstation) { $scope.spawnInfo.no_expiration = $scope.noExpiration; $scope.spawnInfo.home_volume_size = $scope.homeVolumeSize; $scope.spawnInfo.home_volume_id = $scope.homeVolumeID; } $scope.spawnInfo.useTaskConfig = $scope.useTaskConfig; $scope.spawnInfo.region = $scope.selectedRegion; if ($scope.spawnTaskChecked && !!$scope.spawnTask) { $scope.spawnInfo.task_id = $scope.spawnTask.id; } if ($scope.spawnTask && $scope.spawnTaskSyncChecked) { $scope.spawnInfo.task_sync = true; } mciSpawnRestService.spawnHost( $scope.spawnInfo, {}, { success: function (resp) { // we don't use reload here because we need to clear query parameters // in the case of spawning a host from a task $window.location.href = "/spawn"; }, error: function (resp) { $scope.spawnReqSent = false; notificationService.pushNotification('Error spawning host: ' + resp.data.error, 'errorHeader'); } } ); }; $scope.createVolume = function () { $scope.volumeReqSent = true; mciSpawnRestService.createVolume( $scope.createVolumeInfo, {}, { success: function (resp) { $window.location.reload(); }, error: function (resp) { $scope.volumeReqSent = false; notificationService.pushNotification('Error creating volume: ' + resp.data.error, 'errorHeader'); } } ); }; $scope.updateRDPPassword = function () { mciSpawnRestService.updateRDPPassword( 'updateRDPPassword', $scope.curHostData.id, $scope.curHostData.password, {}, { success: function (resp) { $window.location.reload(); }, error: function (resp) { notificationService.pushNotification('Error setting host RDP password: ' + resp.data.error, 'errorHeader'); } } ); }; $scope.updateHost = function () { let promises = []; // update expiration if it changed if (!moment($scope.curHostData.original_expiration).startOf("second").isSame(moment($scope.curHostData.current_expiration).startOf("second"))) { let new_expiration = null; if (!$scope.curHostData.no_expiration) { new_expiration = new Date($scope.curHostData.current_expiration); } promises.push(mciSpawnRestService.extendHostExpiration( 'extendHostExpiration', $scope.curHostData.id, new_expiration, {}, { error: function (resp) { notificationService.pushNotification('Error extending host expiration: ' + resp.data.error, 'errorHeader'); } } )); } // update tags if they changed if (($scope.curHostData.tags_to_add && Object.entries($scope.curHostData.tags_to_add).length > 0) || ($scope.curHostData.tags_to_delete && $scope.curHostData.tags_to_delete.length > 0)) { let tags_to_add = []; for (key in $scope.curHostData.tags_to_add) { let new_tag = key + "=" + $scope.curHostData.tags_to_add[key]; tags_to_add.push(new_tag); } promises.push(mciSpawnRestService.updateHostTags( 'updateHostTags', $scope.curHostData.id, tags_to_add, $scope.curHostData.tags_to_delete, {}, { error: function (resp) { notificationService.pushNotification('Error updating host tags: ' + resp.data, 'errorHeader'); } } )); } // update instance type if it changed if ($scope.curHostData.selectedInstanceType && $scope.curHostData.instance_type !== $scope.curHostData.selectedInstanceType) { // Do nothing if host is not stopped if ($scope.curHostData.status != "stopped") { notificationService.pushNotification('Host must be stopped before modifying instance type', 'errorHeader'); return } promises.push(mciSpawnRestService.updateInstanceType( 'updateInstanceType', $scope.curHostData.id, $scope.curHostData.selectedInstanceType, {}, { error: function (resp) { notificationService.pushNotification('Error setting new instance type: ' + resp.data, 'errorHeader') } } )); } $q.all(promises).then(() => { $window.location.reload(); }) } $scope.updateHostStatus = function (action) { mciSpawnRestService.updateHostStatus( action, $scope.curHostData.id, {}, { success: function (resp) { $window.location.reload(); }, error: function (resp) { notificationService.pushNotification('Error changing host status: ' + resp.data.error, 'errorHeader'); } } ); }; $scope.updateVolume = function (action) { data = {}; if (action === "attachVolume" && $scope.volumeAttachHost) { data.host_id = $scope.volumeAttachHost.id; } if (action === "extendVolumeExpiration") { if ($scope.curVolumeData.no_expiration != $scope.curVolumeData.original_no_expiration) { action = $scope.curVolumeData.no_expiration? "setVolumeNoExpiration" : "setVolumeHasExpiration"; } else if (!$scope.curVolumeData.no_expiration && $scope.curVolumeData.current_expiration != $scope.curVolumeData.original_expiration) { data.expiration = $scope.curVolumeData.current_expiration; } } mciSpawnRestService.updateVolume( action, $scope.curVolumeData.volume_id, data, { success: function (resp) { $window.location.reload(); }, error: function (resp) { notificationService.pushNotification('Error editing volume: ' + resp.data.error, 'errorHeader'); } } ); }; $scope.updateVolumeExpirationEnabled = function() { if (!$scope.curVolumeData) { return false; } if ($scope.curVolumeData.no_expiration != $scope.curVolumeData.original_no_expiration) { return true; } if (!$scope.curVolumeData.no_expiration && moment($scope.curVolumeData.original_expiration).startOf("second").isBefore(moment($scope.curVolumeData.current_expiration).startOf("second"))) { return true; } return false; } // API helper methods $scope.setSpawnableDistros = function (distros, selectDistroId) { if (distros.length == 0) { distros = []; } distros.forEach(function (spawnableDistro) { $scope.spawnableDistros.push({ 'distro': spawnableDistro }); }); if (distros.length > 0) { $scope.spawnableDistros.sort(function (a, b) { if (a.distro.name < b.distro.name) return -1; if (a.distro.name > b.distro.name) return 1; return 0; }); $scope.setSpawnableDistro($scope.spawnableDistros[0].distro); $scope.spawnInfo.spawnKey = $scope.newKey; if (selectDistroId) { var selectedIndex = _.findIndex($scope.spawnableDistros, function (x) { return x.distro.name == selectDistroId } ) if (selectedIndex >= 0) { $scope.setSpawnableDistro($scope.spawnableDistros[selectedIndex].distro); } } }; }; $scope.setUserKeys = function (publicKeys) { if (publicKeys == 'null') { publicKeys = []; } $scope.userKeys = []; _.each(publicKeys, function (publicKey) { $scope.userKeys.push({ 'name': publicKey.name, 'key': publicKey.key }); }); if (publicKeys.length > 0) { $scope.userKeys.sort(function (a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }); $scope.updateSelectedKey($scope.userKeys[0]); } else { $scope.updateSelectedKey($scope.newKey); } // disable key name text field by default $('#input-key-name').attr('disabled', true); }; // User Interface helper functions // set the spawn request distro based on user selection $scope.setSpawnableDistro = function (spawnableDistro) { $scope.selectedDistro = spawnableDistro; $scope.spawnInfo.distroId = spawnableDistro.name; $scope.selectedRegion = "us-east-1"; // if multiple regions, preference the user region if ($scope.selectedDistro.regions.length > 1) { if ($scope.defaultRegion !== "") { for (let i=0; i < $scope.selectedDistro.regions.length; i++) { // valid region if ($scope.defaultRegion === $scope.selectedDistro.regions[i]) { $scope.selectedRegion = $scope.defaultRegion; break; } } } } // if preferred region not configured for this distro, default to the first region in this list if ($scope.selectedRegion === "" && $scope.selectedDistro.regions.length === 1) { $scope.selectedRegion = $scope.selectedDistro.regions[0]; } // clear home volume settings when switching between distros $scope.isVirtualWorkstation = $scope.selectedDistro.virtual_workstation_allowed && !$scope.spawnTaskChecked && !$scope.spawnTaskSyncChecked; $scope.noExpiration = $scope.selectedDistro.virtual_workstation_allowed && ($scope.availableUnexpirableHosts() > 0); $scope.homeVolumeSize = Math.min($scope.volumeSizeDefault, $scope.availableVolumeSize()); }; $scope.setRegion = function(region) { $scope.selectedRegion = region; } // set the spawn host update instance type based on user selection $scope.setInstanceType = function (instanceType) { $scope.curHostData.selectedInstanceType = instanceType } // toggle spawn key based on user selection $scope.updateSelectedKey = function (selectedKey) { $scope.selectedKey.name = selectedKey.name; $scope.selectedKey.key = selectedKey.key; $scope.currKeyName = $scope.selectedKey.name; }; // indicates if user wishes to save this key $scope.toggleSaveKey = function () { $scope.saveKey = !$scope.saveKey; } $scope.getSpawnStatusLabel = function (host) { if (host) { switch (host.status) { case 'running': return 'label success'; break; case 'initializing': case 'provisioning': case 'building': case 'starting': case 'stopping': case 'stopped': return 'label block-status-started'; break; case 'decommissioned': case 'unreachable': case 'quarantined': case 'provision failed': return 'block-status-cancelled'; break; case 'terminated': return 'block-status-failed'; break; default: return ''; } } } $scope.getVolumeStatusLabel = function (volume) { if (volume && !volume.host_id) { return 'label block-status-inactive' } if (volume && volume.host_id) { return 'label success' } return '' } // populate for selected host; highlight selected host $scope.setSelectedHost = function (host) { if ($scope.lastSelectedHost) { $scope.lastSelectedHost.selected = ''; } host.selected = 'active-host'; host.password = ''; $scope.lastSelectedHost = host; $location.search("id", host.id); $scope.curHostData = host; // check if this is a windows host $scope.curHostData.isWinHost = false; // XXX: if this is-windows check is updated, make sure to also update // model/distro/distro.go as well if (host.distro.arch.indexOf('win') != -1) { $scope.curHostData.isWinHost = true; } $scope.getTags(); $scope.fetchAllowedInstanceTypes(); }; // populate for selected volume; highlight selected volume $scope.setSelectedVolume = function (volume) { if ($scope.lastSelectedVolume) { $scope.lastSelectedVolume.selected = ''; } volume.selected = 'active-host'; $scope.lastSelectedVolume = volume; $location.search("id", volume.volume_id); $scope.curVolumeData = volume; }; $scope.invalidDelete = function (data) { if (data && data.no_expiration && data.checkDelete !== "delete") { return true; }; return false; }; $scope.getTags = function () { $scope.curHostData.tags_to_delete = []; $scope.curHostData.tags_to_add = {}; $scope.curHostData.userTags = {}; if ($scope.curHostData.instance_tags === undefined) { return; } for (var i = 0; i < $scope.curHostData.instance_tags.length; i++) { let curTag = $scope.curHostData.instance_tags[i]; if (curTag.can_be_modified) { $scope.curHostData.userTags[curTag.key] = curTag.value; } } } $scope.removeTag = function (key) { delete $scope.curHostData.userTags[key]; // only add to delete list if key isn't dirty if ($scope.curHostData.instance_tags !== undefined) { for (var i = 0; i < $scope.curHostData.instance_tags.length; i++) { if ($scope.curHostData.instance_tags[i].key === key) { $scope.curHostData.tags_to_delete.push(key); return; } } } } $scope.addTag = function () { if ($scope.new_tag.key && $scope.new_tag.value) { $scope.curHostData.tags_to_add[$scope.new_tag.key] = $scope.new_tag.value; $scope.curHostData.userTags[$scope.new_tag.key] = $scope.new_tag.value; $scope.new_tag = {}; } } $scope.validTag = function (key, value) { if (!key) { return false; } if (!value) { return false; } return true; } $scope.goToVolume = function (volume_id) { _.each($scope.volumes, function (volume) { if (volume.volume_id == volume_id) { $scope.setSelectedVolume(volume); $scope.setResourceType("volumes"); } }); } $scope.goToHost = function (host_id) { _.each($scope.hosts, function (host) { if (host.id == host_id) { $scope.setSelectedHost(host); $scope.setResourceType("hosts"); } }); } initializeModal = function (modal, title, action) { $scope.modalTitle = title; modal.on('shown.bs.modal', function () { $scope.modalOpen = true; }); modal.on('hide.bs.modal', function () { $scope.modalOpen = false; }); } attachEnterHandler = function (action) { $(document).keyup(function (ev) { if ($scope.modalOpen && ev.keyCode === 13) { if ($scope.currentResourceType == "hosts") { $scope.updateHostStatus(action); } else { $scope.updateVolume(action); } $('#spawn-modal').modal('hide'); } }); } $scope.openSpawnModal = function (opt) { $scope.modalOption = opt; $scope.modalOpen = true; var modal = $('#spawn-modal').modal('show'); switch (opt) { case 'spawnHost': $scope.fetchUserKeys(); if ($scope.spawnableDistros.length == 0) { $scope.fetchSpawnableDistros(); } initializeModal(modal, 'Spawn Host'); break; case 'terminateHost': $scope.curHostData.checkDelete = ""; initializeModal(modal, 'Terminate Host'); break; case 'stopHost': initializeModal(modal, 'Stop Host'); attachEnterHandler('stop'); break; case 'startHost': initializeModal(modal, 'Start Host'); attachEnterHandler('start'); break; case 'updateRDPPassword': initializeModal(modal, 'Set RDP Password') modal.on('shown.bs.modal', function () { $('#password-input').focus(); }) break; } }; $scope.openVolumeModal = function (opt) { $scope.modalOption = opt; $scope.modalOpen = true; var modal = $('#spawn-modal').modal('show'); switch (opt) { case 'createVolume': initializeModal(modal, 'Create Volume'); break; case 'deleteVolume': $scope.curVolumeData.checkDelete = ""; initializeModal(modal, 'Delete Volume'); attachEnterHandler('deleteVolume'); break; case 'attachVolume': if ($scope.hosts.length > 0) { $scope.setAttachToHost($scope.hosts[0]) } initializeModal(modal, 'Attach Volume'); attachEnterHandler('attachVolume'); break; case 'detachVolume': initializeModal(modal, 'Detach Volume'); attachEnterHandler('detachVolume'); break; } }; if ($scope.spawnTask && $scope.spawnDistro) { // find the spawn distro in the spawnable distros list, if it's there, // pre-select it in the modal. $scope.spawnTaskChecked = true $scope.spawnTaskSyncChecked = $scope.spawnTask.can_sync; setTimeout(function () { $scope.fetchSpawnableDistros($scope.spawnDistro._id, function () { $scope.openSpawnModal('spawnHost') }); }, 0) } } ]); 'use strict'; /** * A simple mapping library. */ class Kizazi { /** * @param {*} t Path directory. */ constructor(t) { this.tree = t; this.gen = []; this.labelName = null; this.labelList = {}; } /** * Set new tree * @param {*} t New tree. */ setTree(t) { this.tree = t; return this; } /** * Current generation. */ get getGeneration() { return this.gen; } /** * Set new generation * @param {...String} args New generation. */ generation(...args) { this.gen = args.flat(); return this; } /** * Append generation to current generation. * @param {...String} args Generation extension. */ append(...args) { this.gen = this.gen.concat(args.flat()); return this; } /** * Set label. * @param {...String} args Name, [...generation] */ setLabel(...args) { let tmp = args.flat(); this.labelList[tmp[0]] = tmp.slice(1); return this; } /** * Set multiple labels. * @param {Object} obj Labels as object. */ setLabelMany(obj) { this.labelList = Object.assign(this.labelList, obj); return this; } /** * Merge two labels. * @param {String} first First part. * @param {String} last Last part. */ merge(first, last) { this.labelList[first] = this.labelList[first].concat(this.labelList[last]); return this; } /** * Use label. * @param {String} name Label name. */ label(name) { this.gen = this.labelList[name]; return this; } /** * Get module value. */ get link() { return this.setLink(); } /** * Set module value. */ setLink() { return `${this.tree}/${this.getGeneration.join('/')}`; } } module.exports = Kizazi; /** * @desc unit test-case */ const util = require('../dist/util'); const { ObjArray, number, string } = util; global.ObjArray = ObjArray; global.number = number; global.string = string; describe('request-model', () => { describe('test number', () => { require('./number'); }); describe('test string', () => { require('./string'); }); describe('test object Array', () => { require('./object-array'); }); }); <filename>zm-ajax/WebRoot/js/ajax/dwt/widgets/DwtToolBar.js /* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Synacor, Inc. * * The contents of this file are subject to the Common Public Attribution License Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: https://www.zimbra.com/license * The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15 * have been added to cover use of software over a computer network and provide for limited attribution * for the Original Developer. In addition, Exhibit A has been modified to be consistent with Exhibit B. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the License for the specific language governing rights and limitations under the License. * The Original Code is Zimbra Open Source Web Client. * The Initial Developer of the Original Code is Zimbra, Inc. All rights to the Original Code were * transferred by Zimbra, Inc. to Synacor, Inc. on September 14, 2015. * * All portions of the code are Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Synacor, Inc. All Rights Reserved. * ***** END LICENSE BLOCK ***** */ /** * @overview * This file defines a toolbar. * */ /** * Creates a toolbar. * @constructor * @class * Creates a toolbar. Components must be added via the <code>add*()</code> functions. * A toolbar is a horizontal or vertical strip of widgets (usually buttons). * * @author <NAME> * * @param {hash} params a hash of parameters * @param {DwtComposite} params.parent the parent widget * @param {string} params.className the CSS class * @param {DwtToolBar.HORIZ_STYLE|DwtToolBar.VERT_STYLE} params.posStyle the positioning style * @param {constant} params.style the menu style * @param {number} params.index the index at which to add this control among parent's children * * @extends DwtComposite */ DwtToolBar = function(params) { if (arguments.length == 0) { return; } params = Dwt.getParams(arguments, DwtToolBar.PARAMS); params.className = params.className || "ZToolbar"; DwtComposite.call(this, params); // since we attach event handlers at the toolbar level, make sure we don't double up on // handlers when we have a toolbar within a toolbar if (params.parent instanceof DwtToolBar) { this._hasSetMouseEvents = params.parent._hasSetMouseEvents; } if (params.handleMouse !== false && !this._hasSetMouseEvents) { var events = [DwtEvent.ONMOUSEDOWN, DwtEvent.ONMOUSEUP, DwtEvent.ONCLICK]; if (!AjxEnv.isIE) { events.push(DwtEvent.ONMOUSEOVER, DwtEvent.ONMOUSEOUT); } this._setEventHdlrs(events); this._hasSetMouseEvents = true; } this._style = params.style || DwtToolBar.HORIZ_STYLE; this._createHtml(); this._numFillers = 0; this._curFocusIndex = 0; // Let toolbar be a single tab stop, then manage focus among items using arrow keys this.tabGroupMember = this; this._keyMapName = (this._style == DwtToolBar.HORIZ_STYLE) ? DwtKeyMap.MAP_TOOLBAR_HORIZ : DwtKeyMap.MAP_TOOLBAR_VERT; }; DwtToolBar.PARAMS = ["parent", "className", "posStyle", "style", "index", "id"]; DwtToolBar.prototype = new DwtComposite; DwtToolBar.prototype.constructor = DwtToolBar; DwtToolBar.prototype.role = 'toolbar'; DwtToolBar.prototype.isDwtToolBar = true; DwtToolBar.prototype.toString = function() { return "DwtToolBar"; }; // // Constants // /** * Defines the "horizontal" style. */ DwtToolBar.HORIZ_STYLE = 1; /** * Defines the "vertical" style. */ DwtToolBar.VERT_STYLE = 2; DwtToolBar.FIRST_ITEM = "ZFirstItem"; DwtToolBar.LAST_ITEM = "ZLastItem"; DwtToolBar.SELECTED_NEXT = DwtControl.SELECTED + "Next"; DwtToolBar.SELECTED_PREV = DwtControl.SELECTED + "Prev"; DwtToolBar._NEXT_PREV_RE = new RegExp( "\\b" + [ DwtToolBar.SELECTED_NEXT, DwtToolBar.SELECTED_PREV ].join("|") + "\\b", "g" ); // // Data // // main template DwtToolBar.prototype.TEMPLATE = "dwt.Widgets#ZToolbar"; // item templates DwtToolBar.prototype.ITEM_TEMPLATE = "dwt.Widgets#ZToolbarItem"; DwtToolBar.prototype.SEPARATOR_TEMPLATE = "dwt.Widgets#ZToolbarSeparator"; DwtToolBar.prototype.SPACER_TEMPLATE = "dwt.Widgets#ZToolbarSpacer"; DwtToolBar.prototype.FILLER_TEMPLATE = "dwt.Widgets#ZToolbarFiller"; // static data DwtToolBar.__itemCount = 0; // // Public methods // DwtToolBar.prototype.dispose = function() { DwtComposite.prototype.dispose.call(this); this._itemsEl = null; this._prefixEl = null; this._suffixEl = null; }; /** * Gets the item. * * @param {int} index the index * @return {Object} the item */ DwtToolBar.prototype.getItem = function(index) { return this._children.get(index); }; /** * Gets the item count. * * @return {number} the size of the children items */ DwtToolBar.prototype.getItemCount = function() { return this._children.size(); }; /** * Gets the items. * * @return {array} an array of children items */ DwtToolBar.prototype.getItems = function() { return this._children.getArray(); }; // item creation /** * Adds a spacer. * * @param {string} className the spacer CSS class name * @param {number} index the index for the spacer * @return {Object} the newly added element */ DwtToolBar.prototype.addSpacer = function(className, index) { var spacer = new DwtToolBarSpacer({ parent: this, index: index, className: className, toolbarItemTemplate: this.SPACER_TEMPLATE, id: this._htmlElId + '_spacer' + DwtToolBar.__itemCount }); return spacer; }; /** * Adds a separator. * * @param {string} className the separator CSS class name * @param {number} index the index for the separator * @return {Object} the newly added element */ DwtToolBar.prototype.addSeparator = function(className, index) { var sep = new DwtToolBarSpacer({ parent: this, index: index, className: className, toolbarItemTemplate: this.SEPARATOR_TEMPLATE, id: this._htmlElId + '_separator' + DwtToolBar.__itemCount }); return sep; }; /** * Adds a filler. * * @param {string} className the CSS class name * @param {number} index the index for the filler * @return {Object} the newly added element */ DwtToolBar.prototype.addFiller = function(className, index) { var filler = new DwtToolBarSpacer({ parent: this, index: index, className: className, toolbarItemTemplate: this.FILLER_TEMPLATE, id: this._htmlElId + '_filler' + DwtToolBar.__itemCount }); return filler; }; // DwtComposite methods /** * Adds a child item. * * @param {Object} child the child item * @param {number} index the index for the child */ DwtToolBar.prototype.addChild = function(child, index) { // get the reference element for insertion var placeControl = this.getChild(index); var placeEl = placeControl ? placeControl.getHtmlElement().parentNode : this._suffixEl; // actually add the child DwtComposite.prototype.addChild.apply(this, arguments); // create and insert the item element if (this._itemsEl) { var itemEl = this._createItemElement(child.toolbarItemTemplate); this._itemsEl.insertBefore(itemEl, placeEl); } // finally, move the child to the item child.reparentHtmlElement(itemEl); }; DwtToolBar.prototype.removeChild = function(child) { var item = child.getHtmlElement().parentNode; DwtComposite.prototype.removeChild.apply(this, arguments); if (item && item.parentNode) { item.parentNode.removeChild(item); } }; // keyboard nav /** * Gets the key map name. * * @return {string} the key map name */ DwtToolBar.prototype.getKeyMapName = function() { return this._keyMapName; }; DwtToolBar.prototype.handleKeyAction = function(actionCode, ev) { // if the user typed a left or right arrow in an INPUT, only go to the previous/next item if the cursor is at the // beginning or end of the text in the INPUT var curFocusIndex = this._curFocusIndex, numItems = this.getItemCount(), input = ev && ev.target && ev.target.nodeName.toLowerCase() === 'input' ? ev.target : null, cursorPos = input && input.selectionStart, valueLen = input && input.value && input.value.length; if (numItems < 2) { return false; } DBG.println(AjxDebug.FOCUS, 'DwtToolBar HANDLEKEYACTION: cur focus index = ' + curFocusIndex); switch (actionCode) { case DwtKeyMap.PREV: if (input && cursorPos > 0) { ev.forcePropagate = true; // don't let subsequent handlers block propagation return false; } else if (curFocusIndex > 0) { this._moveFocus(true, ev); return true; } break; case DwtKeyMap.NEXT: if (input && cursorPos < valueLen) { ev.forcePropagate = true; // don't let subsequent handlers block propagation return false; } else if (curFocusIndex < numItems - 1) { this._moveFocus(false); return true; } break; default: // pass everything else to currently focused item var item = this._getCurrentFocusItem(); if (item) { return item.handleKeyAction(actionCode, ev); } } return true; }; // // Protected methods // // utility /** * @private */ DwtToolBar.prototype._createItemId = function(id) { id = id || this._htmlElId; var itemId = [id, "item", ++DwtToolBar.__itemCount].join("_"); return itemId; }; // html creation /** * @private */ DwtToolBar.prototype._createHtml = function() { var data = { id: this._htmlElId }; this._createHtmlFromTemplate(this.TEMPLATE, data); this._itemsEl = document.getElementById(data.id + "_items"); this._prefixEl = document.getElementById(data.id + "_prefix"); this._suffixEl = document.getElementById(data.id + "_suffix"); }; /** * @private */ DwtToolBar.prototype._createItemElement = function(templateId) { templateId = templateId || this.ITEM_TEMPLATE; var data = { id: this._htmlElId, itemId: this._createItemId() }; var html = AjxTemplate.expand(templateId, data); // the following is like scratching your back with your heel: // var fragment = Dwt.toDocumentFragment(html, data.itemId); // return (AjxUtil.getFirstElement(fragment)); var cont = AjxStringUtil.calcDIV(); cont.innerHTML = html; return cont.firstChild.rows[0].cells[0]; // DIV->TABLE->TR->TD }; /** * Focuses the current item. * * @param {DwtControl} item (optional) specific toolbar item to focus */ DwtToolBar.prototype.focus = function(item) { DBG.println(AjxDebug.FOCUS, "DwtToolBar: FOCUS " + [this, this._htmlElId].join(' / ')); this._setMenuKey(); item = item || this._getCurrentFocusItem(); if (item && this._canFocusItem(item)) { this._curFocusIndex = this.__getButtonIndex(item); return item.focus(); } else { // if current item isn't focusable, find first one that is return this._moveFocus(false); } }; /** * Blurs the current item. * * @param {DwtControl} item (optional) specific toolbar item to blur * * @private */ DwtToolBar.prototype.blur = function(item) { DBG.println(AjxDebug.FOCUS, "DwtToolBar: BLUR"); item = item || this._getCurrentFocusItem(); if (item && item.blur) { item.blur(); } }; /** * Returns the item at the given index, as long as it can accept focus. * For now, we only move focus to simple components like buttons. Also, * the item must be enabled and visible. * * @param {DwtControl} item an item within toolbar * @return {boolean} true if the item can be focused * * @private */ DwtToolBar.prototype._canFocusItem = function(item) { if (!item) { return false; } if (!item.focus) { return false; } if (item.isDwtToolBarSpacer) { return false; } if (item.getEnabled && !item.getEnabled()) { return false; } if (item.getVisible && !item.getVisible()) { return false; } if (item.isDwtText && !item.getText()) { return false; } return true; }; DwtToolBar.prototype._getCurrentFocusItem = function() { return this.getItem(this._curFocusIndex); }; DwtToolBar.prototype.getEnabled = function() { // toolbars delegate focus to their children, and so are only 'enabled' -- // i.e. focusable -- when at least one child is return this._children.some(function(child) { return this._canFocusItem(child); }, this); }; /** * Moves focus to next or previous item that can take focus. * * @param {boolean} back if <code>true</code>, move focus to previous item * * @private */ DwtToolBar.prototype._moveFocus = function(back) { var index = this._curFocusIndex, maxIndex = this.getItemCount() - 1, item = null, found = false; index = back ? index - 1 : index + 1; while (!found && index >= 0 && index <= maxIndex) { item = this.getItem(index); if (this._canFocusItem(item)) { found = true; } index = back ? index - 1 : index + 1; } if (item && found) { this.blur(); this.focus(item); } return item; }; // make sure the key for expanding a button submenu matches our style DwtToolBar.prototype._setMenuKey = function() { if (!this._submenuKeySet) { var kbm = this.shell.getKeyboardMgr(); if (kbm.isEnabled()) { var kmm = kbm.__keyMapMgr; if (kmm) { if (this._style == DwtToolBar.HORIZ_STYLE) { kmm.removeMapping(DwtKeyMap.MAP_BUTTON, "ArrowRight"); kmm.setMapping(DwtKeyMap.MAP_BUTTON, "ArrowDown", DwtKeyMap.SUBMENU); } else { kmm.removeMapping(DwtKeyMap.MAP_BUTTON, "ArrowDown"); kmm.setMapping(DwtKeyMap.MAP_BUTTON, "ArrowRight", DwtKeyMap.SUBMENU); } kmm.reloadMap(DwtKeyMap.MAP_BUTTON); } } this._submenuKeySet = true; } }; // Updates internal index when a child gets focus DwtToolBar.prototype._childFocusListener = function(ev) { DBG.println(AjxDebug.FOCUS, "DwtToolBar CHILDFOCUSLISTENER: " + [ ev.dwtObj, ev.dwtObj._htmlElId ].join(' / ')); this._curFocusIndex = this.__getButtonIndex(ev.dwtObj); }; /** * @private */ DwtToolBar.prototype.__markPrevNext = function(id, opened) { var index = this.__getButtonIndex(id); var prev = this.getChild(index - 1); var next = this.getChild(index + 1); if (opened) { if (prev) { Dwt.delClass(prev.getHtmlElement(), DwtToolBar._NEXT_PREV_RE, DwtToolBar.SELECTED_PREV); } if (next) { Dwt.delClass(next.getHtmlElement(), DwtToolBar._NEXT_PREV_RE, DwtToolBar.SELECTED_NEXT); } } else { if (prev) { Dwt.delClass(prev.getHtmlElement(), DwtToolBar._NEXT_PREV_RE); } if (next) { Dwt.delClass(next.getHtmlElement(), DwtToolBar._NEXT_PREV_RE); } } // hack: mark the first and last items so we can style them specially // MOW note: this should really not be here, as it only needs to be done once, // but I'm not sure where to put it otherwise var first = this.getChild(0); if (first) { Dwt.addClass(first.getHtmlElement(), DwtToolBar.FIRST_ITEM); } var last = this.getChild(this.getItemCount()-1); if (last) { Dwt.addClass(last.getHtmlElement(), DwtToolBar.LAST_ITEM); } }; /** * Find the array index of a toolbar button. * * @param id {String|DwtControl} item ID, or item * * @return {number} Index of the id in the array, or -1 if the id does not exist. * @private */ DwtToolBar.prototype.__getButtonIndex = function(id) { var item = AjxUtil.isString(id) ? DwtControl.fromElementId(id) : id; for (var i = 0; i <= this.getItemCount() - 1; i++) { if (item === this.getItem(i)) { return i; } } return -1; }; // // Classes // /** * Creates a tool bar button. * @constructor * @class * This class represents a toolbar button. * * @param {hash} params a hash of parameters * @param {DwtComposite} parent the parent widget * @param {constant} style the menu style * @param {string} className the CSS class * @param {DwtToolBar.HORIZ_STYLE|DwtToolBar.VERT_STYLE} posStyle the positioning style * @param {Object} actionTiming the action timing * @param {string} id the id * @param {number} index the index at which to add this control among parent's children * * @extends DwtButton */ DwtToolBarButton = function(params) { if (arguments.length == 0) { return; } var params = Dwt.getParams(arguments, DwtToolBarButton.PARAMS); params.className = params.className || "ZToolbarButton"; DwtButton.call(this, params); }; DwtToolBarButton.PARAMS = ["parent", "style", "className", "posStyle", "actionTiming", "id", "index"]; DwtToolBarButton.prototype = new DwtButton; DwtToolBarButton.prototype.constructor = DwtToolBarButton; DwtToolBarButton.prototype.isDwtToolBarButton = true; DwtToolBarButton.prototype.toString = function() { return "DwtToolBarButton"; }; // Data DwtToolBarButton.prototype.TEMPLATE = "dwt.Widgets#ZToolbarButton"; // Spacing controls (spacer, separator, filler) DwtToolBarSpacer = function(params) { if (arguments.length == 0) { return; } this._noFocus = this.noTab = true; this.toolbarItemTemplate = params.toolbarItemTemplate; DwtControl.call(this, params); }; DwtToolBarSpacer.prototype = new DwtControl; DwtToolBarSpacer.prototype.constructor = DwtToolBarSpacer; DwtToolBarSpacer.prototype.isDwtToolBarSpacer = true; DwtToolBarSpacer.prototype.toString = function() { return 'DwtToolBarSpacer'; }; DwtToolBarSpacer.prototype.role = 'separator'; <reponame>TreeGecko/ArcheryScorer<gh_stars>0 angular.module('asMobile') .controller('MainCtrl', [ 'UserService', 'GuidService', function (userService, guidService) { var self = this; self.userService = userService; guidService.verifyGuidSupply(); } ]); <gh_stars>1-10 var superagent = require('superagent'); var cheerio = require('cheerio'); var moment = require('moment'); var data = require('./mongo').SpiderData; exports.dateFormat = function (date) { return moment(date).format('YYYY年MM月DD日hh:mm:ss dddd'); } exports.spiderMan = function(url){ superagent.get(url) .end(function (err, sres) { if (err) { return next(err); } var $ = cheerio.load(sres.text); var items = []; $('#topic_list .topic_title').each(function (idx, element) { var $element = $(element); items.push({ title: $element.attr('title'), href: $element.attr('href') }); var spider = { title: $element.attr('title'), href: $element.attr('href') }; data.create(spider).then(function(result){ console.log('存入的数据是'+result); }) }); //console.log('获取到的内容是:'+items); return items; }); } // Copyright (C) 2016 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-symbol.prototype.valueof es6id: 19.4.3.3 description: Called on a value that is neither a Symbol nor an Object info: | 1. Let s be the this value. 2. If Type(s) is Symbol, return s. 3. If Type(s) is not Object, throw a TypeError exception. features: [Symbol] ---*/ var valueOf = Symbol.prototype.valueOf; assert.throws(TypeError, function() { valueOf.call(null); }, 'null'); assert.throws(TypeError, function() { valueOf.call(undefined); }, 'undefined'); assert.throws(TypeError, function() { valueOf.call(0); }, 'number'); assert.throws(TypeError, function() { valueOf.call(''); }, 'string'); <reponame>edwincen/fastify-swagger 'use strict' const t = require('tap') const test = t.test const Fastify = require('fastify') const Swagger = require('swagger-parser') const yaml = require('js-yaml') const fastifySwagger = require('../index') const readFileSync = require('fs').readFileSync const resolve = require('path').resolve const swaggerInfo = { swagger: { info: { title: 'Test swagger', description: 'testing the fastify swagger api', version: '0.1.0' }, host: 'localhost', schemes: ['http'], consumes: ['application/json'], produces: ['application/json'], securityDefinitions: { apiKey: { type: 'apiKey', name: 'apiKey', in: 'header' } } }, exposeRoute: true } const opts1 = { schema: { response: { 200: { type: 'object', properties: { hello: { type: 'string' } } } }, querystring: { hello: { type: 'string' }, world: { type: 'string' } } } } const opts2 = { schema: { body: { type: 'object', properties: { hello: { type: 'string' }, obj: { type: 'object', properties: { some: { type: 'string' } } } }, required: ['hello'] } } } const opts3 = { schema: { params: { type: 'object', properties: { id: { type: 'string', description: 'user id' } } } } } const opts4 = { schema: { security: [ { 'apiKey': [] } ] } } test('/documentation/json route', t => { t.plan(2) const fastify = Fastify() fastify.register(fastifySwagger, swaggerInfo) fastify.get('/', () => {}) fastify.post('/', () => {}) fastify.get('/example', opts1, () => {}) fastify.post('/example', opts2, () => {}) fastify.get('/parameters/:id', opts3, () => {}) fastify.get('/example1', opts4, () => {}) fastify.inject({ method: 'GET', url: '/documentation/json' }, (err, res) => { t.error(err) var payload = JSON.parse(res.payload) Swagger.validate(payload) .then(function (api) { t.pass('valid swagger object') }) .catch(function (err) { t.fail(err) }) }) }) test('fastify.swagger should return a valid swagger yaml', t => { t.plan(4) const fastify = Fastify() fastify.register(fastifySwagger, swaggerInfo) fastify.get('/', () => {}) fastify.post('/', () => {}) fastify.get('/example', opts1, () => {}) fastify.post('/example', opts2, () => {}) fastify.get('/parameters/:id', opts3, () => {}) fastify.get('/example1', opts4, () => {}) fastify.inject({ method: 'GET', url: '/documentation/yaml' }, (err, res) => { t.error(err) t.is(typeof res.payload, 'string') t.is(res.headers['content-type'], 'application/x-yaml') try { yaml.safeLoad(res.payload) t.pass('valid swagger yaml') } catch (err) { t.fail(err) } }) }) test('/documenatation should send the swagger UI html', t => { t.plan(4) const fastify = Fastify() fastify.register(fastifySwagger, swaggerInfo) fastify.get('/', () => {}) fastify.post('/', () => {}) fastify.get('/example', opts1, () => {}) fastify.post('/example', opts2, () => {}) fastify.get('/parameters/:id', opts3, () => {}) fastify.get('/example1', opts4, () => {}) fastify.inject({ method: 'GET', url: '/documentation' }, (err, res) => { t.error(err) t.is(typeof res.payload, 'string') t.is(res.headers['content-type'], 'text/html') t.strictEqual( readFileSync( resolve(__dirname, '..', 'static', 'index.html'), 'utf8' ), res.payload ) }) }) test('/documenatation/:file should send back the correct file', t => { t.plan(16) const fastify = Fastify() fastify.register(fastifySwagger, swaggerInfo) fastify.get('/', () => {}) fastify.post('/', () => {}) fastify.get('/example', opts1, () => {}) fastify.post('/example', opts2, () => {}) fastify.get('/parameters/:id', opts3, () => {}) fastify.get('/example1', opts4, () => {}) fastify.inject({ method: 'GET', url: '/documentation/' }, (err, res) => { t.error(err) t.is(typeof res.payload, 'string') t.is(res.headers['content-type'], 'text/html') t.strictEqual( readFileSync( resolve(__dirname, '..', 'static', 'index.html'), 'utf8' ), res.payload ) }) fastify.inject({ method: 'GET', url: '/documentation/swagger-ui.css' }, (err, res) => { t.error(err) t.is(typeof res.payload, 'string') t.is(res.headers['content-type'], 'text/css') t.strictEqual( readFileSync( resolve(__dirname, '..', 'static', 'swagger-ui.css'), 'utf8' ), res.payload ) }) fastify.inject({ method: 'GET', url: '/documentation/swagger-ui-bundle.js' }, (err, res) => { t.error(err) t.is(typeof res.payload, 'string') t.is(res.headers['content-type'], 'application/javascript') t.strictEqual( readFileSync( resolve(__dirname, '..', 'static', 'swagger-ui-bundle.js'), 'utf8' ), res.payload ) }) fastify.inject({ method: 'GET', url: '/documentation/swagger-ui-standalone-preset.js' }, (err, res) => { t.error(err) t.is(typeof res.payload, 'string') t.is(res.headers['content-type'], 'application/javascript') t.strictEqual( readFileSync( resolve(__dirname, '..', 'static', 'swagger-ui-standalone-preset.js'), 'utf8' ), res.payload ) }) }) test('/documenatation/:file 404', t => { t.plan(3) const fastify = Fastify() fastify.register(fastifySwagger, swaggerInfo) fastify.get('/', () => {}) fastify.post('/', () => {}) fastify.get('/example', opts1, () => {}) fastify.post('/example', opts2, () => {}) fastify.get('/parameters/:id', opts3, () => {}) fastify.get('/example1', opts4, () => {}) fastify.inject({ method: 'GET', url: '/documentation/stuff.css' }, (err, res) => { t.error(err) const payload = JSON.parse(res.payload) t.strictEqual(res.statusCode, 404) t.deepEqual({ message: 'Not found', error: 'Not Found', statusCode: 404 }, payload) }) }) <reponame>JonHX/nextjs-apollo-graphql import React from 'react' import Link from '../Link' import { Button, ButtonSkeleton } from 'carbon-components-react'; import css from "./styles.scss" class Topic extends React.Component { render () { const { loading, types, type, title, data = [] } = this.props return <div className="bx--col-lg-3"> <div className="topic"> <h2 className="bx--type-beta">{ title }</h2> <ul className="topic-list"> { data.map( item => { return <li key={`${item.id}`} className="topic-list-item"> <Link to={`/${type}/:id`} id={item.id}> <a>{item.name}</a> </Link> </li> })} </ul> { loading ? <ButtonSkeleton small /> : <Link to={`/${types}`}> <Button small > See all </Button> </Link> } </div> </div> } } export default Topic// JavaScript source code const database = require('../services/database.js'); const baseQuery = `select Enroll_ID "Enroll_ID", First_Name "First_Name", Last_Name "Last_Name", Degree "Degree", Joining_Year "Joining_Year" from Student_Table`; async function find(context) { let query = baseQuery; const binds = {}; if (context.id) { binds.Enroll_ID = context.id; query += `\nwhere Enroll_ID = :Enroll_ID`; } const result = await database.simpleExecute(query, binds); return result.rows; } module.exports.find = find; const procedureStart = ` declare a varchar(10); b varchar(10); c varchar(10); d varchar(10); e varchar(10); table_name varchar(15); begin `; const procedureEnd = ` mypack.Tab_Student(a,b,c,d,e); end; `; async function create(Stude) { const Student = Object.assign({}, Stude); let query = procedureStart; const binds = {}; query += `\na:='` + Student.Enroll_ID + `';`; query += `\nb:='` + Student.First_Name + `';`; query += `\nc:='` + Student.Last_Name + `';`; query += `\nd:='` + Student.Degree + `';`; query += `\ne:='` + Student.Joining_Year + `';`; query += procedureEnd; const result = await database.simpleExecute(query, binds); return Student; } module.exports.create = create; const updateSql = `declare field_name varchar2(20); field_value varchar2(30); m number; begin `; const updatesqlEnd = ` updateStudent(field_name, field_value, TO_NUMBER(m)); end; `; async function update(teach) { const Student = Object.assign({}, teach); let query = updateSql; const binds = {}; query += `\nfield_name:='` + Student.field_name + `';`; query += `\nfield_value:='` + Student.field_value + `';`; query += `\nm:='` + Student.m + `';`; query += updatesqlEnd; const result = await database.simpleExecute(query, binds); return Student; } module.exports.update = update; const deleteSql = `declare col_name varchar2(15); compvalue varchar2(20); numvalue number; begin `; const deletesqlEnd = ` mypackage1.procedure2(col_name,compvalue,TO_NUMBER(numvalue)); end; `; async function del(teac) { const teach = Object.assign({}, teac); let query = deleteSql; const binds = {}; query += `\ncol_name:='` + teach.col_name + `';`; query += `\ncompvalue:='` + teach.compvalue + `';`; query += `\nnumvalue:='` + teach.numvalue + `';`; query += deletesqlEnd; console.log(query) const result = await database.simpleExecute(query, binds); return teach; } module.exports.delete = del; <reponame>codemargaret/animal-wiki $(document).ready(function(){ $(".clickable1").click(function(){ $("#turtles").toggle(); }) $(".clickable2").click(function(){ $("#snakes").toggle(); }) $(".clickable3").click(function(){ $("#insects").toggle(); }) }); <reponame>make-story/ui // import if(!self.isGlobalModule) { importScripts('./global.js'); } //importScripts('/a.js', '/b.js', '/c.js'); // instance let instance = {}; //instance.a = new A(); //instance.b = new B(); //instance.c = new C(); // worker event self.onmessage = (event) => { let data = event.data || {}; let { action={}, key, isSync, } = data; let { instance: i, method: m, parameter: p, } = action; // 워커 작업 실행 (async () => { console.log('[worker 정보] 요청', action); data.result = await instance[i][m](p); console.log('[worker 정보] 응답', data.result); self.postMessage(data); })(); //setTimeout(() => { //console.log('action', action); // instance, method, parameter //console.log('isSync', isSync); //console.log('key', key); //console.log(instance[action.instance]); //data.result = 'worker에서 반환되는 값!'; //self.postMessage(data); //}, action.time); };// Dependencies const express = require("express") const colors = require("colors") const layout = require("express-ejs-layouts") const fileupload = require("express-fileupload") const bodyParser = require("body-parser") const session = require("express-session") const flash = require("connect-flash") const cookieParser = require("cookie-parser") // Database require("./database/conn") // Seeds require("./seeds/seed") // Require Local Files const config = require("./config/config") // Models const User = require("./models/User") const PostUpAds = require("./models/PostUpAds") const PostLoAds = require("./models/PostLoAds") const SideUpAds = require("./models/SideUpAds") const SideLoAds = require("./models/SideLoAds") // Require Routes const defaultRoutes = require("./routes/default") const projectsRoutes = require("./routes/projects") const postsRoutes = require("./routes/posts") const categoriesRoutes = require("./routes/categories") const registerRoutes = require("./routes/register") const loginRoutes = require("./routes/login") const adsRoutes = require("./routes/ads") // Start The App const app = express() // Use Of Middlewares app.use(layout) app.set("view engine", "ejs") app.set("layout", "layouts/main") app.use(express.static("public")) app.use(session({ secret: "CodersBD", resave: true, saveUninitialized: false })) app.use(flash()) app.use(fileupload()) app.use(cookieParser()) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended: true})) // Custom Middlewares app.use((req, res, next) => { res.locals.user = req.cookies.CodersBD; res.locals.error = req.flash("error") res.locals.success = req.flash("success") next() }); app.use((req, res, next) => { if (req.cookies.CodersBD) { User.findOne({username:req.cookies.CodersBD}).exec((err, user) => { if(user.isAdmin === false) { res.locals.admin = false next() } else { res.locals.admin = true next() } }) } else { res.locals.admin = false next() } }) app.use((req, res, next) => { if (!req.cookies.CodersBD) { next() } else { User.findOne({username: req.cookies.CodersBD}, (err, localUser) => { if(err) { console.log(err) } else { if(localUser.postUpAds.length == 0) { PostUpAds.create({content: 'Ads No 1'}, (err, ad_1) => { if(err) { console.log(err) } else { localUser.postUpAds.push(ad_1) localUser.save(err => { if(err) { console.log(err) } else { next() } }) } }) } else { next() } } }) } }) app.use((req, res, next) => { if (!req.cookies.CodersBD) { next() } else { User.findOne({username: req.cookies.CodersBD}, (err, localUser) => { if(err) { console.log(err) } else { if(localUser.postLoAds.length == 0) { PostLoAds.create({content: 'Ads No 2'}, (err, ad_2) => { if(err) { console.log(err) } else { localUser.postLoAds.push(ad_2) localUser.save(err => { if(err) { console.log(err) } else { next() } }) } }) } else { next() } } }) } }) app.use((req, res, next) => { if (!req.cookies.CodersBD) { next() } else { User.findOne({username: req.cookies.CodersBD}, (err, localUser) => { if(err) { console.log(err) } else { if(localUser.sideUpAds.length == 0) { SideUpAds.create({content: 'Ads No 3'}, (err, ad_3) => { if(err) { console.log(err) } else { localUser.sideUpAds.push(ad_3) localUser.save(err => { if(err) { console.log(err) } else { next() } }) } }) } else { next() } } }) } }) app.use((req, res, next) => { if (!req.cookies.CodersBD) { next() } else { User.findOne({username: req.cookies.CodersBD}, (err, localUser) => { if(err) { console.log(err) } else { if(localUser.sideLoAds.length == 0) { SideLoAds.create({content: 'Ads No 4'}, (err, ad_4) => { if(err) { console.log(err) } else { localUser.sideLoAds.push(ad_4) localUser.save(err => { if(err) { console.log(err) } else { next() } }) } }) } else { next() } } }) } }) // Use Of Routes app.use(defaultRoutes) app.use(projectsRoutes) app.use(postsRoutes) app.use(categoriesRoutes) app.use(registerRoutes) app.use(loginRoutes) app.use(adsRoutes) app.get("*", (req, res) => { res.render("pages/notFound", { title: "Page Not Found" }) }) // Listening To Port app.listen(config.port, () => { console.log(colors.green(`The Server Has Started On >>> http://localhost:${config.port}`)) }) const OfficialWeb3 = require('web3'); const HttpProvider = require("../web3/HttpProviderCache"); const WsProvider = require("../web3/WsProviderCache"); const helpers = setup.helpers; const globals = setup.globals; const utils = helpers.utils; const web3util = helpers.web3util; const web3 = helpers.web3; const ListContractInstance = globals.ListContractInstance; describe('Web3 Multi', async() => { let TestHttpProvider; let TestWsProvider; before( async() => { TestHttpProvider = new HttpProvider["default"]( setup.globals.network_config_http ); TestHttpProvider.useCache(false); TestHttpProvider.saveToCache(true); TestWsProvider = new WsProvider["default"]( setup.globals.network_config_ws ); TestWsProvider.useCache(false); }) describe("New Web3 instance using normal HTTP Provider", async() => { let TestWeb3; let TestListContract; let totalProcessTime = 0; let totalGasUsage = 0; let totalCalls = 0; before( async() => { TestWeb3 = await new OfficialWeb3(TestHttpProvider); TestListContract = await new TestWeb3.eth.Contract(globals.abis.ListContract, ListContractInstance._address); }) after( async() => { // save result statistics let OneItemTotalGasUsage = 0; if( typeof globals.OneItemTotalGasUsage !== "undefined") { OneItemTotalGasUsage = globals.OneItemTotalGasUsage; } else { OneItemTotalGasUsage = 439155; } globals.results.multi = {}; globals.results.multi.count = totalCalls; globals.results.multi.time = totalProcessTime; globals.results.multi.gas = (OneItemTotalGasUsage * globals.TestDummyRecords); // save provider so Zoom can profile these calls globals.multiWeb3Provider = TestHttpProvider; }) describe("Load all items from list, then get all their properties ( async / at the same time in promises )", async() => { let item; const itemAddressValues = []; const testItemContracts = []; before( (done) => { const startTime = process.hrtime(); // async address values for(let i = 1; i <= globals.TestDummyRecords; i++) { itemAddressValues.push( TestListContract.methods.items(i).call() ); } Promise.all(itemAddressValues).then(function(values) { // async instantiate contracts for( let i = 0; i < values.length; i++) { // based on loaded address, instantiate child contract testItemContracts.push( new TestWeb3.eth.Contract(globals.abis.ItemEntity, values[i].itemAddress) ); totalCalls++; } Promise.all(testItemContracts).then(function(contracts) { // calculate end time const endTime = process.hrtime(startTime); const actualTime = endTime[0] + endTime[1] / 1000000000; totalProcessTime += actualTime; done(); }); }); }); it("should load and validate all items and properties", (done) => { const startTime = process.hrtime(); const callsToValidate = []; const callsToValidateWith = []; for(let i = 0; i < testItemContracts.length; i++) { const TestItemContract = testItemContracts[i]; callsToValidate.push( TestItemContract.methods.getName().call() ); callsToValidateWith.push( function(result) { assert.isTrue( typeof result === "string", "Result is not a string"); }); callsToValidate.push( TestItemContract.methods.getAsset().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 42 , "Result is not a proper address"); }); callsToValidate.push( TestItemContract.methods.getUint8().call() ); callsToValidateWith.push( function(result) { assert.isTrue( parseInt( result ) === 2**8-1 , "Result is not 2**8-1"); }); callsToValidate.push( TestItemContract.methods.getUint16().call() ); callsToValidateWith.push( function(result) { assert.isTrue( parseInt( result ) === 2**16-1 , "Result is not 2**16-1"); }); callsToValidate.push( TestItemContract.methods.getUint32().call() ); callsToValidateWith.push( function(result) { assert.isTrue( parseInt( result ) === 2**32-1 , "Result is not 2**32-1"); }); callsToValidate.push( TestItemContract.methods.getUint64().call() ); callsToValidateWith.push( function(result) { let resultingNumber = new helpers.BigNumber( result ); let valdidation = new helpers.BigNumber(2).exponentiatedBy(64).minus(1); assert.isTrue( resultingNumber.toString() === valdidation.toString() , "Result is not 2**64-1"); }); callsToValidate.push( TestItemContract.methods.getUint128().call() ); callsToValidateWith.push( function(result) { let resultingNumber = new helpers.BigNumber( result ); let valdidation = new helpers.BigNumber(2).exponentiatedBy(128).minus(1); assert.isTrue( resultingNumber.toString() === valdidation.toString() , "Result is not 2**128-1"); }); callsToValidate.push( TestItemContract.methods.getUint256().call() ); callsToValidateWith.push( function(result) { let resultingNumber = new helpers.BigNumber( result ); let valdidation = new helpers.BigNumber(2).exponentiatedBy(256).minus(1); assert.isTrue( resultingNumber.toString() === valdidation.toString() , "Result is not 2**256-1"); }); callsToValidate.push( TestItemContract.methods.getString8().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 8 , "Result length is not 8"); }); callsToValidate.push( TestItemContract.methods.getString16().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 16 , "Result length is not 16"); }); callsToValidate.push( TestItemContract.methods.getString32().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 32 , "Result length is not 32"); }); callsToValidate.push( TestItemContract.methods.getString64().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 64 , "Result length is not 64"); }); callsToValidate.push( TestItemContract.methods.getAddress().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 42 , "Result is not a proper address"); }); callsToValidate.push( TestItemContract.methods.getBoolTrue().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result , "false: Result is not a proper boolean true value"); }); callsToValidate.push( TestItemContract.methods.getBoolFalse().call() ); callsToValidateWith.push( function(result) { assert.isFalse( result , "false: Result is not a proper boolean false value"); }); callsToValidate.push( TestItemContract.methods.getBytes8().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 18 , "bytes8: Result is not a string with length 18"); }); callsToValidate.push( TestItemContract.methods.getBytes16().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 34 , "bytes16: Result is not a string with length 34"); }); callsToValidate.push( TestItemContract.methods.getBytes32().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 66 , "bytes32: Result is not a string with length 66"); }); callsToValidate.push( TestItemContract.methods.getBytes().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 130 , "bytes64: Result is not a string with length 130"); }); } Promise.all(callsToValidate).then(function(values) { // calculate end time before asserting results.. so we get lower times const endTime = process.hrtime(startTime); const actualTime = endTime[0] + endTime[1] / 1000000000; totalProcessTime += actualTime; // validate results for( let i = 0; i < values.length; i++) { totalCalls++; callsToValidateWith[i](values[i]); } done(); }); }); }); }); describe("New Web3 instance using normal WebSocket Provider", async() => { let TestWeb3; let TestListContract; let totalProcessTime = 0; let totalGasUsage = 0; let totalCalls = 0; before( async() => { TestWeb3 = await new OfficialWeb3(TestWsProvider); TestListContract = await new TestWeb3.eth.Contract(globals.abis.ListContract, ListContractInstance._address); }) after( async() => { // save result statistics let OneItemTotalGasUsage = 0; if( typeof globals.OneItemTotalGasUsage !== "undefined") { OneItemTotalGasUsage = globals.OneItemTotalGasUsage; } else { OneItemTotalGasUsage = 439155; } globals.results.multiws = {}; globals.results.multiws.count = totalCalls; globals.results.multiws.time = totalProcessTime; globals.results.multiws.gas = (OneItemTotalGasUsage * globals.TestDummyRecords); }) describe("Load all items from list, then get all their properties ( async / at the same time in promises )", async() => { let item; const itemAddressValues = []; const testItemContracts = []; before( (done) => { const startTime = process.hrtime(); // async address values for(let i = 1; i <= globals.TestDummyRecords; i++) { itemAddressValues.push( TestListContract.methods.items(i).call() ); } Promise.all(itemAddressValues).then(function(values) { // async instantiate contracts for( let i = 0; i < values.length; i++) { // based on loaded address, instantiate child contract testItemContracts.push( new TestWeb3.eth.Contract(globals.abis.ItemEntity, values[i].itemAddress) ); totalCalls++; } Promise.all(testItemContracts).then(function(contracts) { // calculate end time const endTime = process.hrtime(startTime); const actualTime = endTime[0] + endTime[1] / 1000000000; totalProcessTime += actualTime; done(); }); }); }); it("should load and validate all items and properties", (done) => { const startTime = process.hrtime(); const callsToValidate = []; const callsToValidateWith = []; for(let i = 0; i < testItemContracts.length; i++) { const TestItemContract = testItemContracts[i]; callsToValidate.push( TestItemContract.methods.getName().call() ); callsToValidateWith.push( function(result) { assert.isTrue( typeof result === "string", "Result is not a string"); }); callsToValidate.push( TestItemContract.methods.getAsset().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 42 , "Result is not a proper address"); }); callsToValidate.push( TestItemContract.methods.getUint8().call() ); callsToValidateWith.push( function(result) { assert.isTrue( parseInt( result ) === 2**8-1 , "Result is not 2**8-1"); }); callsToValidate.push( TestItemContract.methods.getUint16().call() ); callsToValidateWith.push( function(result) { assert.isTrue( parseInt( result ) === 2**16-1 , "Result is not 2**16-1"); }); callsToValidate.push( TestItemContract.methods.getUint32().call() ); callsToValidateWith.push( function(result) { assert.isTrue( parseInt( result ) === 2**32-1 , "Result is not 2**32-1"); }); callsToValidate.push( TestItemContract.methods.getUint64().call() ); callsToValidateWith.push( function(result) { let resultingNumber = new helpers.BigNumber( result ); let valdidation = new helpers.BigNumber(2).exponentiatedBy(64).minus(1); assert.isTrue( resultingNumber.toString() === valdidation.toString() , "Result is not 2**64-1"); }); callsToValidate.push( TestItemContract.methods.getUint128().call() ); callsToValidateWith.push( function(result) { let resultingNumber = new helpers.BigNumber( result ); let valdidation = new helpers.BigNumber(2).exponentiatedBy(128).minus(1); assert.isTrue( resultingNumber.toString() === valdidation.toString() , "Result is not 2**128-1"); }); callsToValidate.push( TestItemContract.methods.getUint256().call() ); callsToValidateWith.push( function(result) { let resultingNumber = new helpers.BigNumber( result ); let valdidation = new helpers.BigNumber(2).exponentiatedBy(256).minus(1); assert.isTrue( resultingNumber.toString() === valdidation.toString() , "Result is not 2**256-1"); }); callsToValidate.push( TestItemContract.methods.getString8().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 8 , "Result length is not 8"); }); callsToValidate.push( TestItemContract.methods.getString16().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 16 , "Result length is not 16"); }); callsToValidate.push( TestItemContract.methods.getString32().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 32 , "Result length is not 32"); }); callsToValidate.push( TestItemContract.methods.getString64().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 64 , "Result length is not 64"); }); callsToValidate.push( TestItemContract.methods.getAddress().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 42 , "Result is not a proper address"); }); callsToValidate.push( TestItemContract.methods.getBoolTrue().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result , "false: Result is not a proper boolean true value"); }); callsToValidate.push( TestItemContract.methods.getBoolFalse().call() ); callsToValidateWith.push( function(result) { assert.isFalse( result , "false: Result is not a proper boolean false value"); }); callsToValidate.push( TestItemContract.methods.getBytes8().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 18 , "bytes8: Result is not a string with length 18"); }); callsToValidate.push( TestItemContract.methods.getBytes16().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 34 , "bytes16: Result is not a string with length 34"); }); callsToValidate.push( TestItemContract.methods.getBytes32().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 66 , "bytes32: Result is not a string with length 66"); }); callsToValidate.push( TestItemContract.methods.getBytes().call() ); callsToValidateWith.push( function(result) { assert.isTrue( result.length === 130 , "bytes64: Result is not a string with length 130"); }); } Promise.all(callsToValidate).then(function(values) { // calculate end time before asserting results.. so we get lower times const endTime = process.hrtime(startTime); const actualTime = endTime[0] + endTime[1] / 1000000000; totalProcessTime += actualTime; // validate results for( let i = 0; i < values.length; i++) { totalCalls++; callsToValidateWith[i](values[i]); } done(); }); }); }); }); }); <reponame>abdusabri/hsds-react import styled from 'styled-components' import levels from '../../styles/mixins/depth.css' export const DepthUI = styled('div')` &.d100 { ${levels.d100} } &.d200 { ${levels.d200} &.is-active, &.with-hover-effect:hover { ${levels.d200Effect} } } &.d300 { ${levels.d300} &.is-active, &.with-hover-effect:hover { ${levels.d300Effect} } } &.d400 { ${levels.d400} &.is-active, &.with-hover-effect:hover { ${levels.d400Effect} } } &.d500 { ${levels.d500} &.is-active, &.with-hover-effect:hover { ${levels.d500Effect} } } &.d600 { ${levels.d600} } &.d700 { ${levels.d700} } ` <gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generate = void 0; var _react = _interopRequireDefault(require("react")); var _fs = require("fs"); var _mjmlReact = require("mjml-react"); var _Head = _interopRequireDefault(require("../../blocks/Head")); var _Header = _interopRequireDefault(require("../../blocks/Header")); var _Hero = _interopRequireDefault(require("../../blocks/Hero")); var _Body = _interopRequireDefault(require("../../blocks/Body")); var _Footer = _interopRequireDefault(require("../../blocks/Footer")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } // const css = readFileSync("./assets/styles.css").toString(); var generate = function generate(data, config) { return /*#__PURE__*/_react["default"].createElement(_mjmlReact.Mjml, null, /*#__PURE__*/_react["default"].createElement(_Head["default"], { data: data }), /*#__PURE__*/_react["default"].createElement(_mjmlReact.MjmlBody, { width: 500, backgroundColor: config.bgColor }, /*#__PURE__*/_react["default"].createElement(_Header["default"], null), /*#__PURE__*/_react["default"].createElement(_Hero["default"], null), /*#__PURE__*/_react["default"].createElement(_Body["default"], null), /*#__PURE__*/_react["default"].createElement(_Footer["default"], null))); }; exports.generate = generate;<gh_stars>1-10 //ToggleDIVDisplay is used to toggle a display from hidden to visible or vice versa. Used in showing user a message from the template input function ToggleDIVDisplay(id) { if (document.getElementById(id).classList.contains("displayBlock") || document.getElementById(id).classList.contains("displayHidden") != true) { document.getElementById(id).classList.add("displayHidden"); document.getElementById(id).classList.remove("displayBlock"); } else { document.getElementById(id).classList.add("displayBlock"); document.getElementById(id).classList.remove("displayHidden"); } } //ToggleCellDIVDisplay is used to toggle a display from hidden to visible or vice versa while providing a default setting for use on phones. function ToggleCellDIVDisplay(id) { if (document.getElementById(id).classList.contains("cellDefaultHidden")) { document.getElementById(id).classList.remove("cellDefaultHidden"); } else { document.getElementById(id).classList.add("cellDefaultHidden"); } } //ToggleFormDisplay is used to show hidden forms, cleans up the UI function ToggleFormDisplay(id) { if (document.getElementById(id).classList.contains("displayHidden")) { document.getElementById(id).classList.remove("displayHidden"); } else { document.getElementById(id).classList.add("displayHidden"); } return false; } //toggleCSSClass is used to toggle a css class on a given html element. function toggleCSSClass(elementID, className) { if (document.getElementById(elementID).classList.contains(className)) { document.getElementById(elementID).classList.remove(className); } else { document.getElementById(elementID).classList.add(className); } } //Expand Image or not function ExpandImage() { parent = document.getElementById("ImageGridContainer"); children = parent.getElementsByTagName("img"); for (i = 0; i < children.length; i++) { if (children[i].classList.contains("resetHeight")) { children[i].classList.remove("resetHeight"); } else { children[i].classList.add("resetHeight"); } } return false; } function UpdatePermissionBox() { var checkedBoxes = document.querySelectorAll('input[name=permCheckbox]:checked'); var permValue = 0 for (var I=0; I<checkedBoxes.length; I++) { permValue += Number(checkedBoxes[I].value); } document.querySelectorAll('input[name=permCheckbox]:checked'); document.querySelector('input[name=permissions]').value = permValue; } //API var CheckCollectionTimer = null; function CheckCollectionName(form, resultID) { //document.getElementById(resultID).innerHTML = "Add to Collection" var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200 ) { //Get JSON object, and ID Result = JSON.parse(xhttp.responseText); if (userPermissions & 4096 == 4096 || userControlsOwn && (userID == Result.UploaderID)) { document.getElementById(resultID).innerHTML = "Add to Collection" } else { document.getElementById(resultID).innerHTML = "Insufficient Permissions!" } } else if (this.readyState == 4 && this.status == 404) { if (userPermissions & 2048) { document.getElementById(resultID).innerHTML = "Create Collection" } else { document.getElementById(resultID).innerHTML = "Insufficient Permissions!" } } }; xhttp.open("GET", "/api/CollectionName?CollectionName="+form.elements["CollectionName"].value, true); xhttp.send(); return false; } function SearchUsers(formID, pageStart) { form = document.getElementById(formID) var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200 ) { //Get JSON object, and ID Result = JSON.parse(xhttp.responseText); document.getElementById("userResultCount").innerText = Result.ResultCount+" users found!"; //Clear Table table = document.getElementById("userResultTable") while (table.children.length > 1) { table.removeChild(table.children[1]) } for (I = 0; I<Result.Users.length; I++) { newElem = document.createElement("tr") newElem.innerHTML = "<td><a href=\"/mod/user?userName="+Result.Users[I].Name+"\">"+Result.Users[I].Name+"</a></td><td>"+Result.Users[I].ID+"</td><td>"+Result.Users[I].Permissions+"</td><td>"+Result.Users[I].Disabled+"</td><td>"+Result.Users[I].CreationTime+"</td>" table.appendChild(newElem); } GenerateUserSearchMenu(form.elements["userName"].value, Result.ServerStride, pageStart, Result.ResultCount, 'userResultPageMenu', formID) } else if (this.readyState == 4) { document.getElementById("userResultCount").innerText = "Error occurred: "+this.status+" - "+this.statusText+". From server: "+xhttp.responseText } }; xhttp.open("GET", "/api/Users?userNameQuery="+form.elements["userName"].value+"&PageStart="+pageStart, true); xhttp.send(); return false; } function GenerateUserSearchMenu(searchQuery, pageStride, pageOffset, maxCount, targetID, formID) { pageMenu = "<a href=\"#\" onclick=\"return SearchUsers('"+formID+"', 0);\"><<</a>" //Short circuit on param issues if (pageOffset < 0) { pageOffset = 0; } if (pageStride < 0 || maxCount <=0) { document.getElementById(targetID).innerHTML = "1"; return false; } lastPage = Math.ceil(maxCount / pageStride); maxPage = lastPage; currentPage = Math.floor(pageOffset/pageStride) + 1; minPage = currentPage -3; if (minPage < 1) { minPage = 1; } if (maxPage > currentPage+3) { maxPage = currentPage + 3; } for (processPage = minPage; processPage <= maxPage; processPage++) { if (processPage != currentPage) { pageMenu = pageMenu + ", <a href=\"#\" onclick=\"return SearchUsers('"+formID+"', "+((processPage-1)*pageStride)+");\">"+processPage+"</a>"; } else { pageMenu = pageMenu + ", "+processPage; } } pageMenu = pageMenu + ", <a href=\"#\" onclick=\"return SearchUsers('"+formID+"', "+((lastPage-1)*pageStride)+");\">>></a>"; document.getElementById(targetID).innerHTML = pageMenu; } //Helper functions for API function GetImageType(path) { text = ""; path = "."+path.toLowerCase().split('.').pop(); switch(path) { case ".wav": case ".mp3": case ".ogg": text = "audio"; break; case ".mpg": case ".mov": case ".webm": case ".avi": case ".mp4": case ".gif": text = "video"; break; default: text = "image"; } return text; } function GetEmbedForContent(imageLocation) { ToReturn = "" ext = "."+imageLocation.toLowerCase().split('.').pop(); //console.log("Path for GetEmbedContent is "+imageLocation+" with extension of "+ext); switch(ext) { case ".jpg": case ".jpeg": case ".bmp": case ".gif": case ".png": case ".svg": case ".webp": case ".tiff": case ".tif": case ".jfif": ToReturn = "<img src=\"/images/" + imageLocation + "\" alt=\"" + imageLocation + "\" id=\"IMGContent\" />"; break; case ".mpg": case ".mov": case ".webm": case ".avi": case ".mp4": case ".mp3": case ".ogg": ToReturn = "<video controls loop> <source src=\"/images/" + imageLocation + "\" type=\"" + getMIME(ext, "video/mp4") + "\">Your browser does not support the video tag.</video>"; break; case ".wav": ToReturn = "<audio controls loop> <source src=\"/images/" + imageLocation + "\" type=\"" + getMIME(ext, "audio/wav") + "\">Your browser does not support the audio tag.</audio>"; break; default: ToReturn = "<p>File format not supported. Click download.</p>"; } //console.log("Return for GetEmbedContent is "+ToReturn); wrapper = document.createElement('div'); wrapper.innerHTML= ToReturn; return wrapper.firstChild; } function getMIME(extension, fallback) { switch (extension) { case ".mp4": return "video/mp4" case ".webm": return "video/webm" case ".avi": return "video/avi" case ".mpg": return "video/mpeg" case ".mov": return "video/quicktime" case ".ogg": return "video/ogg" case ".mp3": return "audio/mpeg3" case ".wav": return "audio/wav" default: return fallback } } function CorrectImageOrient(imgID) { var imgElement = document.getElementById(imgID); window.EXIF.getData(imgElement, function () { var orientation = EXIF.getTag(this, "Orientation"); if (orientation && orientation != 1) { var canvas = window.loadImage.scale(imgElement, {orientation: orientation || 0,maxWidth: 1000,maxHeight: 1000,canvas:true}); var newIMG = document.createElement("img"); newIMG.src = canvas.toDataURL(); newIMG.id = imgID; newIMG.alt = imgElement.alt; newIMG.style = imgElement.style; imgElement.parentNode.replaceChild(newIMG,imgElement); } //Otherwise not needed }); } //Global Shortcuts var MousetrapShortcuts = "?=help\r\nr=random search\r\nq=edit search terms\r\nright arrow=next image\r\nleft arrow=prev image\r\nctrl+right arrow=next page\r\nCtrl+left arrow=prev page"; Mousetrap.bind("?", function() { console.log(MousetrapShortcuts); }); Mousetrap.bind("r", function() {$("#mainImageSearchForm :input[value='Random']").click();}) Mousetrap.bind("q", function() {$("#mainImageSearchForm :input[name='SearchTerms']").select();$("#splashForm :input[name='SearchTerms']").select();}) Mousetrap.bind("right", function() {$("#mainImageSearchForm .nextInCollection").click();}) Mousetrap.bind("left", function() {$("#mainImageSearchForm .previousInCollection").click();}) Mousetrap.bind("ctrl+right", function() {$(".CollectionList .nextInCollection").click();}) Mousetrap.bind("ctrl+left", function() {$(".CollectionList .previousInCollection").click();}) Mousetrap.bind("shift+q", function() {$("#SideMenu form[action=\"/collections\"] :input[name='SearchTerms']").select();$("#SideMenu form[action=\"/tags\"] :input[name='SearchTags']").select();})export var TemplateAddons = (function () { function TemplateAddons() { } TemplateAddons.prototype.run = function (fc) { fc.templateManipulators.postWrapper.push(function (field) { if (field && field.templateOptions && (field.templateOptions.addonLeft || field.templateOptions.addonRight)) { return 'addons'; } }); }; return TemplateAddons; }()); //# sourceMappingURL=addon.js.map<gh_stars>0 import React from "react" import styled from "styled-components" import { GatsbyImage } from "gatsby-plugin-image"; import { Link } from "gatsby" import { BsArrowLeft } from "@react-icons/all-files/bs/BsArrowLeft" function Banner2(props) { return ( <Wrapper style={!props.style ? null : props.style}> <div className="parent"> <div className="background"> {!props.img ? ( <GatsbyImage image={props.image} alt={props.title} style={{ maxWidth: "100% !important", height: "600px", opacity: "0.6", maxHeight: "600px !important", width: "100%" }} /> ) : ( <img style={{ width: "100%", height: "600px", opacity: "0.6", }} src={props.image} alt={props.title} /> )} </div> <div className="title"> <h1>{props.title}</h1> <p>{props.desc}</p> {!props.registration ? null : ( <h6 style={{marginBottom: "0px"}}> {props.registration} </h6> )} {props.event === "null" ? null : !props.event ? null : ( <h6 style={{backgroundColor: "var(--primaryColor)", color: "var(--secondaryColor)"}}> {props.event} </h6> )} <Link to={props.link} className="link"> <BsArrowLeft style={{ color: "#fff", width: "40px", height: "40px", }} /> {props.linktitle} </Link> </div> </div> </Wrapper> ); } export default Banner2 const Wrapper = styled.div` width: 100%; .parent { /* position: relative; */ display: grid; grid-template-columns: repeat(11, 1fr); grid-template-rows: 1fr; grid-column-gap: 5px; grid-row-gap: 0px; height: 600px; } p { font-size: 15px; font-weight: 400; text-align: justify; @media (max-width: 479px) { font-size: 13px; } @media (max-width: 767px) { font-size: 13px; } } .title { grid-area: 1/2/2/8; display: flex; flex-direction: column; justify-content: center; align-items: flex-start; z-index: 1; color: #fff; @media (max-width: 991px) { grid-area: 1/2/2/11; } @media (max-width: 767px) { grid-area: 1/2/2/11; } @media (max-width: 479px) { margin-top: 60px; grid-area: 1/2/2/11; } } .link { text-decoration: none; color: white; text-align: center; display: flex; align-items: center; } .link:hover { color: var(--primaryColor); } .background { position: absolute; background-color: #111111; width: 100%; height: 600px; /* opacity: 0.8; */ } .bg__header { width: 100%; height: 100%; object-fit: cover; position: absolute; grid-area: 1/1/2/12; /* opacity: 0.7; */ } h6 { font-size: 15px; width: auto; border: 1px solid transparent; background-color: var(--purpleColor); color:#ffffff; padding: 15px; border-radius:6px; } ` <reponame>bfsgr/insomnia // @flow import * as React from 'react'; import { AUTH_BASIC, AUTH_DIGEST, AUTH_BEARER, AUTH_NTLM, AUTH_OAUTH_1, AUTH_OAUTH_2, AUTH_AWS_IAM, AUTH_HAWK, AUTH_NETRC, AUTH_ASAP, AUTOBIND_CFG, } from '../../../../common/constants'; import BasicAuth from './basic-auth'; import DigestAuth from './digest-auth'; import BearerAuth from './bearer-auth'; import NTLMAuth from './ntlm-auth'; import OAuth2Auth from './o-auth-2-auth'; import OAuth1Auth from './o-auth-1-auth'; import HawkAuth from './hawk-auth'; import AWSAuth from './aws-auth'; import NetrcAuth from './netrc-auth'; import AsapAuth from './asap-auth'; import { autoBindMethodsForReact } from 'class-autobind-decorator'; import type { Request, RequestAuthentication } from '../../../../models/request'; import type { OAuth2Token } from '../../../../models/o-auth-2-token'; import type { Settings } from '../../../../models/settings'; type Props = { handleRender: Function, handleGetRenderContext: Function, handleUpdateSettingsShowPasswords: (showPasswords: boolean) => Promise<Settings>, nunjucksPowerUserMode: boolean, onChange: (Request, RequestAuthentication) => Promise<Request>, request: Request, showPasswords: boolean, isVariableUncovered: boolean, // Optional oAuth2Token: ?OAuth2Token, }; @autoBindMethodsForReact(AUTOBIND_CFG) class AuthWrapper extends React.PureComponent<Props> { renderEditor() { const { oAuth2Token, request, handleRender, handleGetRenderContext, nunjucksPowerUserMode, handleUpdateSettingsShowPasswords, onChange, showPasswords, isVariableUncovered, } = this.props; const { authentication } = request; if (authentication.type === AUTH_BASIC) { return ( <BasicAuth request={request} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} handleUpdateSettingsShowPasswords={handleUpdateSettingsShowPasswords} nunjucksPowerUserMode={nunjucksPowerUserMode} onChange={onChange} showPasswords={showPasswords} isVariableUncovered={isVariableUncovered} /> ); } else if (authentication.type === AUTH_OAUTH_2) { return ( <OAuth2Auth oAuth2Token={oAuth2Token} request={request} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} nunjucksPowerUserMode={nunjucksPowerUserMode} handleUpdateSettingsShowPasswords={handleUpdateSettingsShowPasswords} onChange={onChange} showPasswords={showPasswords} isVariableUncovered={isVariableUncovered} /> ); } else if (authentication.type === AUTH_HAWK) { return ( <HawkAuth request={request} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} nunjucksPowerUserMode={nunjucksPowerUserMode} onChange={onChange} isVariableUncovered={isVariableUncovered} /> ); } else if (authentication.type === AUTH_OAUTH_1) { return ( <OAuth1Auth request={request} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} nunjucksPowerUserMode={nunjucksPowerUserMode} showPasswords={showPasswords} onChange={onChange} isVariableUncovered={isVariableUncovered} /> ); } else if (authentication.type === AUTH_DIGEST) { return ( <DigestAuth request={request} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} handleUpdateSettingsShowPasswords={handleUpdateSettingsShowPasswords} nunjucksPowerUserMode={nunjucksPowerUserMode} onChange={onChange} showPasswords={showPasswords} isVariableUncovered={isVariableUncovered} /> ); } else if (authentication.type === AUTH_NTLM) { return ( <NTLMAuth request={request} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} nunjucksPowerUserMode={nunjucksPowerUserMode} handleUpdateSettingsShowPasswords={handleUpdateSettingsShowPasswords} onChange={onChange} showPasswords={showPasswords} isVariableUncovered={isVariableUncovered} /> ); } else if (authentication.type === AUTH_BEARER) { return ( <BearerAuth request={request} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} nunjucksPowerUserMode={nunjucksPowerUserMode} onChange={onChange} isVariableUncovered={isVariableUncovered} /> ); } else if (authentication.type === AUTH_AWS_IAM) { return ( <AWSAuth request={request} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} handleUpdateSettingsShowPasswords={handleUpdateSettingsShowPasswords} nunjucksPowerUserMode={nunjucksPowerUserMode} onChange={onChange} showPasswords={showPasswords} isVariableUncovered={isVariableUncovered} /> ); } else if (authentication.type === AUTH_NETRC) { return <NetrcAuth />; } else if (authentication.type === AUTH_ASAP) { return ( <AsapAuth request={request} handleRender={handleRender} handleGetRenderContext={handleGetRenderContext} nunjucksPowerUserMode={nunjucksPowerUserMode} onChange={onChange} isVariableUncovered={isVariableUncovered} /> ); } else { return ( <div className="vertically-center text-center"> <p className="pad super-faint text-sm text-center"> <i className="fa fa-unlock-alt" style={{ fontSize: '8rem', opacity: 0.3 }} /> <br /> <br /> Select an auth type from above </p> </div> ); } } render() { return <div className="tall">{this.renderEditor()}</div>; } } export default AuthWrapper; <filename>resources/js/components/App.js<gh_stars>0 import React from 'react'; import ReactDOM from 'react-dom'; import { ToastProvider } from 'react-toast-notifications'; import { BrowserRouter } from 'react-router-dom'; import Routes from '../routes'; import GlobalStyle from '../styles/global'; const App = () => { return ( <ToastProvider autoDismiss autoDismissTimeout={6000}> <BrowserRouter> <Routes /> </BrowserRouter> <GlobalStyle /> </ToastProvider> ); } export default App; if (document.getElementById('app')) { ReactDOM.render(<App />, document.getElementById('app')); } import React from 'react'; const Petitions = () => { return ( <div className='row justify-content-md-center mt-5 text-white text-center'> <div className='col-md-6 rounded-lg mt-5 p-3 m-4 text-dark' style={{ backgroundColor: `rgba(255,255,255,.8)` }}> <h1 className='border-bottom border-dark mb-3 pb-2'>Petitions!</h1> </div> </div> ) } export default Petitions;export copperValue from './copper-value'; export parser from './parser'; export subUnits from './sub-units'; export total from './total'; export values from './values'; <reponame>erickmerchant/framework-cli module.exports = function (commit) { commit(() => { return { location: '/heading-1.html', heading: 'Heading 1' } }) commit(() => { return { location: '/heading-2.html', heading: 'Heading 2' } }) } <gh_stars>0 var my_skins = ["skin-blue", "skin-black", "skin-red", "skin-yellow", "skin-purple", "skin-green"]; $(function () { /* For demo purposes */ var demo = $("<div />").css({ position: "fixed", top: "70px", right: "0", background: "#fff", "border-radius": "5px 0px 0px 5px", padding: "10px 15px", "font-size": "16px", "z-index": "99999", cursor: "pointer", color: "#3c8dbc", "box-shadow": "0 1px 3px rgba(0,0,0,0.1)" }).html("<i class='fa fa-link'></i>").addClass("no-print"); var demo_settings = $("<div />").css({ "padding": "10px", position: "fixed", top: "70px", right: "-250px", background: "#fff", border: "0px solid #ddd", "width": "250px", "z-index": "99999", "box-shadow": "0 1px 3px rgba(0,0,0,0.1)" }).addClass("no-print"); demo_settings.append( "<h4 class='text-light-blue' style='margin: 0 0 5px 0; border-bottom: 1px solid #ddd; padding-bottom: 15px;'>Quick links</h4>" //Fixed layout + "<div class='form-group'>" + "<div class='checkbox' id='pagelinks2'>None" + "</div>" + "</div>" ); demo.click(function () { if (!$(this).hasClass("open")) { $(this).animate({"right": "250px"}); demo_settings.animate({"right": "0"}); $(this).addClass("open"); } else { $(this).animate({"right": "0"}); demo_settings.animate({"right": "-250px"}); $(this).removeClass("open"); } }); $("body").append(demo); $("body").append(demo_settings); setup(); checkHistory("pagelinks2"); }); function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toGMTString(); document.cookie = cname + '=' + cvalue + ';path="/";' + expires; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for ( var i = 0; i < ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name) == 0) return c.substring(name.length, c.length); } return ""; } function checkHistory(targetId) { var history = getCookie("history"); var htmlContent = ''; if (history != "") { var insert = true; var sp = history.toString().split(","); for ( var i = sp.length - 1; i >= 0; i--) { htmlContent += '<a class="btn-block btn bg-purple" href="' + sp[i] + '">' //+ sp[i].substring(sp[i].lastIndexOf('/') + 1) + '</a><br>'; + sp[i].replace( path,"") + '</a><br>'; if (sp[i] == document.URL) { insert = false; } document.getElementById(targetId).innerHTML = htmlContent; } if (insert) { sp.push(document.URL); } setCookie("history", sp.toString(), 30); } else { var stack = new Array(); stack.push(document.URL); setCookie("history", stack.toString(), 30); } } function clearHistory(targetId) { setCookie("history", "", -1); document.getElementById(targetId).innerHTML = ""; alert("Visited page links were cleared"); } function change_layout(cls) { $("body").toggleClass(cls); $.AdminLTE.layout.fixSidebar(); } function change_skin(cls) { $.each(my_skins, function (i) { //$("body").removeClass(my_skins[i]); }); // $("body").addClass(cls); //store('skin', cls); return false; } function store(name, val) { if (typeof (Storage) !== "undefined") { localStorage.setItem(name, val); } else { alert('Please use a modern browser to properly view this template!'); } } function get(name) { if (typeof (Storage) !== "undefined") { return localStorage.getItem(name); } else { alert('Please use a modern browser to properly view this template!'); } } function setup() { var tmp = get('skin'); if (tmp && $.inArray(tmp, my_skins)) change_skin(tmp); } 'use strict'; module.exports = () => /(?<=^v?|\sv?)(?:(?:0|[1-9]\d*)\.){2}(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|[\da-z-]*[a-z-][\da-z-]*)(?:\.(?:0|[1-9]\d*|[\da-z-]*[a-z-][\da-z-]*))*)?(?:\+[\da-z-]+(?:\.[\da-z-]+)*)?\b/gi; /* * Conversation SDK * Text Event object model * * Copyright (c) Nexmo Inc. 2017 */ var Event = require('./event').Event; // Conversation Client Error var ConversationClientError = require('../conversationClientError'); var NexmoApiError = ConversationClientError.NexmoApiError; var NexmoClientError = ConversationClientError.NexmoClientError; /** * A text event * * @class TextEvent */ var TextEvent = function(conversation, params) { this.conversation = conversation; this.state = { seen_by: {}, delivered_to: {} }; if (params && params.body) { if (params.body.timestamp) this.timestamp = params.body.timestamp; } // Map the params for (var key in params) { this[key] = params[key]; } }; TextEvent.prototype = new Event(this.conversation, this); /** * Set the message status to 'seen' * @returns {Promise} */ TextEvent.prototype.seen = function() { this.type = "text"; return this.seenEvent(); }; /** * Set the message status to 'delivered'. * handled by the SDK * @returns {Promise} */ TextEvent.prototype.delivered = function() { this.type = "text"; return this.deliveredEvent(); }; /** * Delete the event * @returns {Promise} */ TextEvent.prototype.del = function() { return this.deleteEvent(); }; module.exports = { TextEvent: TextEvent };// Imports import React from 'react' import { Text, View, Image, ScrollView } from 'react-native' // Assets import how1Image from '../../../../../assets/images/stock/how-it-works/1.jpg' import how2Image from '../../../../../assets/images/stock/how-it-works/2.jpg' import how3Image from '../../../../../assets/images/stock/how-it-works/3.jpg' // UI Imports import { white } from '../../../../ui/common/colors' import Icon from '../../../../ui/icon/Icon' import styles from './styles' // Component const HowItWorks = () => ( <ScrollView horizontal={true}> <View style={styles.container}> <Image source={how1Image} resizeMode={"cover"} style={styles.image} /> <View style={styles.content}> <Icon name={"looks-one"} size={45} color={white} style={styles.icon} /> <Text style={styles.title}>ПОДПИСКА НА ИНФОРМАЦИОННЫЕ ПАКЕТЫ</Text> <Text style={styles.description}> Выбирайте и подписывайтесь на необходимые для Вашего бизнеса информационные пакеты от ТМ "Феникс". </Text> </View> </View> <View style={styles.container}> <Image source={how2Image} resizeMode={"cover"} style={styles.image} /> <View style={styles.content}> <Icon name={"looks-two"} size={45} color={white} style={styles.icon} /> <Text style={styles.title}>ПОЛУЧИТЕ ИНФОРМАЦИОННЫЕ ПАКЕТЫ</Text> <Text style={styles.description}> Получите информационные пакеты для оптовых покупателей или дилеров доставленные в Ваш офис. </Text> </View> </View> <View style={styles.container}> <Image source={how3Image} resizeMode={"cover"} style={styles.image} /> <View style={styles.content}> <Icon name={"looks-3"} size={45} color={white} style={styles.icon} /> <Text style={styles.title}>ВЫБОР И ОФОРМЛЕНИЕ ПРЕДЗАКАЗА</Text> <Text style={styles.description}> Выбирайте в полученных Вами информационных пакетах понравившиеся новейшие модели дверей и осуществляйте предзаказ на нашем официальном сайте http://www.f-door.com.ua </Text> </View> </View> </ScrollView> ); export default HowItWorks <filename>docs/html/search/enumvalues_0.js var searchData= [ ['input',['INPUT',['../user__config_8h.html#a35702fc16dc0c43ec25e4738735937e1ae310c909d76b003d016bef8bdf16936a',1,'user_config.h']]] ]; "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "Rect", { enumerable: true, get: function get() { return _rect.default; } }); Object.defineProperty(exports, "Size", { enumerable: true, get: function get() { return _size.default; } }); Object.defineProperty(exports, "Point", { enumerable: true, get: function get() { return _point.default; } }); var _rect = _interopRequireDefault(require("./rect")); var _size = _interopRequireDefault(require("./size")); var _point = _interopRequireDefault(require("./point"));<reponame>mira-lab/secret-store-js-client<gh_stars>0 'use strict' const PSS = require('../lib/paritySecretStore') const ACCOUNT_ADDRESS = '0x00a329c0648769A73afAc7F9381E08FB43dBEA72' const ACCOUNT_PASSWORD = '' const KEY_DIRECTORY = '/parity-keys' const FILES_DIRECTORY = '/encrypted' const NODE_T = 0 const os = require('os') const fs = require('fs') const ethUtil = require('ethereumjs-util') const paritySecretStore = new PSS(ACCOUNT_ADDRESS, ACCOUNT_PASSWORD, null) let filename = process.argv[3] if (filename === 'undefined') throw new Error('no filename specified!') let documentBody = fs.readFileSync(os.homedir() + KEY_DIRECTORY + '/' + filename).toString('hex') if (documentBody == null || documentBody === '') throw new Error('no file specified!') let mode = process.argv[2] if (mode === 'encode' || mode === 'e') { let storageId = ethUtil.sha3(documentBody + new Date().toISOString()).toString('hex') let proceedEncrypted = function (encrypted, storageId) { console.log('\nStatus code: ', encrypted.status, '\nbody: ', encrypted.body) let pathname = os.homedir() + KEY_DIRECTORY + FILES_DIRECTORY + '/' + filename fs.writeFileSync(pathname + '.key', storageId) fs.writeFileSync(pathname + '.enc', encrypted.body.result) } paritySecretStore.encode(storageId, documentBody, NODE_T, proceedEncrypted) } else if (mode === 'decode' || mode === 'd') { let pathname = os.homedir() + KEY_DIRECTORY + FILES_DIRECTORY + '/' + filename let encrypted = fs.readFileSync(pathname + '.enc').toString('ascii') let storageId = fs.readFileSync(pathname + '.key').toString('ascii') let shadowDecrypt = function (decrypted) { console.log(decrypted) } paritySecretStore.shadowDecode(storageId, encrypted, shadowDecrypt) } else if (mode === 'acc-export' || mode === 'a') { paritySecretStore.exportAccount() } else { console.log('Usage are: parity_secret_storage [mode={<e>ncode, <d>ecode, <a>cc-export}] [filename]') } import React from 'react' import { injectIntl } from 'gatsby-plugin-intl' import Markdown from 'react-remarkable' import ConcertShareButtons from '../components/ConcertPage/ConcertShareButtons' import PageTemplate from './pageTemplate' const ConcertPageTemplate = ({ pageContext, intl }) => { const concert = pageContext.concert const concertTitle = intl.formatMessage({ id: `concerts.${concert.id}.title`, }) const concertDescription = intl.formatMessage({ id: `concerts.${concert.id}.description`, }) return ( <PageTemplate title={concertTitle}> <div> <span className="fa fa-calendar mr-2" /> {new Date(concert.date).toLocaleDateString('nl-NL')} {concert.time ? ', ' + concert.time : undefined} </div> <div> <span className="fa fa-map-marker mr-2" /> <a href={concert.locationLink}>{concert.location}</a> </div> {concert.facebookEvent ? ( <div> <span className="fa fa-facebook mr-2" /> <a href={concert.facebookEvent}> {intl.formatMessage({ id: 'translations.facebook-event' })} </a> </div> ) : ( undefined )} {concert.tickets ? ( <div> <span className="fa fa-ticket mr-2" /> <a href={concert.tickets}> {intl.formatMessage({ id: 'translations.tickets-available' })}! </a> </div> ) : ( undefined )} {concert.freeEntrance ? ( <div> <span className="fa fa-ticket mr-2" /> {intl.formatMessage({ id: 'translations.free-entrance' })}! </div> ) : ( undefined )} <hr /> <Markdown>{concertDescription}</Markdown> <ConcertShareButtons concertId={concert.id} /> </PageTemplate> ) } export default injectIntl(ConcertPageTemplate) <reponame>eltociear/eth-connector require('dotenv').config(); const ethereumConfig = require('./json/ethereum-config.json'); const { ethers } = require('hardhat'); const nearAPI = require('near-api-js'); const { serialize: serializeBorsh } = require('near-api-js/lib/utils/serialize'); const NEAR_KEY_STORE_PATH = process.env.NEAR_KEY_STORE_PATH; const keyStore = new nearAPI.keyStores.UnencryptedFileSystemKeyStore(NEAR_KEY_STORE_PATH); class BorshObject { constructor (obj) { Object.assign(this, obj) } }; const logIndexBorshSchema = new Map([ [BorshObject, { kind: 'struct', fields: [ ['log_index', 'u64'], ] }] ]); const receiptIndexBorshSchema = new Map([ [BorshObject, { kind: 'struct', fields: [ ['receipt_index', 'u64'], ] }] ]); const pausedFlagsBorshSchema = new Map([ [BorshObject, { kind: 'struct', fields: [ ['paused', 'u8'], ] }] ]); async function nearFtBalanceOf(nearAccount, nearJsonRpc, nearNetwork, queryNearAccount) { const near = await nearAPI.connect({ deps: { keyStore }, nodeUrl: nearJsonRpc, networkId: nearNetwork }); const account = await near.account(nearAccount); const nearEvmContract = new nearAPI.Contract( account, ethereumConfig.nearEvmAccount, { viewMethods: ['ft_balance_of'], } ); const accountBalance = await nearEvmContract.ft_balance_of({ account_id: queryNearAccount.toString() }); return ethers.BigNumber.from(accountBalance.toString()); } async function nearFtBalanceOfEth(nearAccount, nearJsonRpc, nearNetwork, ethAddress) { const near = await nearAPI.connect({ deps: { keyStore }, nodeUrl: nearJsonRpc, networkId: nearNetwork }); const account = await near.account(nearAccount); const nearEvmContract = new nearAPI.Contract( account, ethereumConfig.nearEvmAccount, { changeMethods: ['ft_balance_of_eth'], } ); const address = ethers.utils.arrayify(ethers.utils.getAddress(ethAddress)); const accountBalance = await nearEvmContract.ft_balance_of_eth(address); return ethers.BigNumber.from(accountBalance.toString()); } async function nearSetPausedFlags(nearAccount, nearJsonRpc, nearNetwork, _pausedFlags) { const near = await nearAPI.connect({ deps: { keyStore }, nodeUrl: nearJsonRpc, networkId: nearNetwork }); const account = await near.account(nearAccount); const nearEvmContract = new nearAPI.Contract( account, ethereumConfig.nearEvmAccount, { changeMethods: ['set_paused_flags'], } ); const pausedFlags = new BorshObject({ paused: 0 }); await nearEvmContract.set_paused_flags(serializeBorsh(pausedFlagsBorshSchema, pausedFlags)); console.log(`Successfully set paused flags`); } async function nearCheckIfProofExists(nearAccount, nearJsonRpc, nearNetwork, proof) { const near = await nearAPI.connect({ deps: { keyStore }, nodeUrl: nearJsonRpc, networkId: nearNetwork }); const account = await near.account(nearAccount); const nearEvmContract = new nearAPI.Contract( account, ethereumConfig.nearEvmAccount, { changeMethods: ['is_used_proof'], } ); const res = await nearEvmContract.is_used_proof(proof); console.log(`Res: ${JSON.stringify(res)}`); } function nearGetBridgedTokenAccountId(erc20TokenAddress) { return [ erc20TokenAddress.replace('0x', ''), ethereumConfig.bridgeFactoryAccount ].join('.'); } exports.nearFtBalanceOf = nearFtBalanceOf; exports.nearFtBalanceOfEth = nearFtBalanceOfEth; exports.nearSetPausedFlags = nearSetPausedFlags; exports.nearCheckIfProofExists = nearCheckIfProofExists; exports.nearGetBridgedTokenAccountId = nearGetBridgedTokenAccountId; App.SettingsControllerController = Ember.Controller.extend({ isActionPending: false, actions: { reset: function () { this.set('isActionPending', true); var self = this; var confirmed = confirm('Are you sure you want to reset the controller? Warning: Resetting the controller may result in an unavailable UI for a duration of time, and depending on your network configuration the UI IP may change.'); if (confirmed) { this.store.createRecord('action', { name: 'reset_controller' }).save().then(function (action) { self.set('isActionPending', false); App.event(action.get('message'), action.get('health')); }, function (xhr) { self.set('isActionPending', false); App.xhrError(xhr, 'Failed to reset the controller'); }); } else { self.set('isActionPending', false); } }, shutdown: function() { this.set('isActionPending', true); var self = this; var confirmed = confirm('Are you sure you want to shutdown the controller? Warning: Shutting down the controller may result in an unavailable UI.'); if (confirmed) { this.store.createRecord('action', { name: 'shutdown_controller' }).save().then(function (action) { self.set('isActionPending', false); App.event(action.get('message'), action.get('health')); }, function (xhr) { self.set('isActionPending', false); App.xhrError(xhr, 'Failed to shutdown controller'); }); } else { self.set('isActionPending', false); } } } }); <filename>addon/utils/values.js export default function values (obj) { return Object .keys(obj) .map(key => obj[key]); } <gh_stars>0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.adaptor = void 0; var tslib_1 = require("tslib"); var common_1 = require("../../adaptor/common"); var utils_1 = require("../../utils"); var utils_2 = require("../../utils"); var geometries_1 = require("../../adaptor/geometries"); var histogram_1 = require("../../utils/transform/histogram"); /** * geometry 处理 * @param params */ function geometry(params) { var chart = params.chart, options = params.options; var data = options.data, binField = options.binField, binNumber = options.binNumber, binWidth = options.binWidth, color = options.color, stackField = options.stackField, legend = options.legend, columnStyle = options.columnStyle; // 处理数据 var plotData = histogram_1.binHistogram(data, binField, binWidth, binNumber, stackField); chart.data(plotData); var p = utils_1.deepAssign({}, params, { options: { xField: 'range', yField: 'count', seriesField: stackField, isStack: true, interval: { color: color, style: columnStyle, }, }, }); geometries_1.interval(p); // 图例 if (legend && stackField) { chart.legend(stackField, legend); } return params; } /** * meta 配置 * @param params */ function meta(params) { var options = params.options; var xAxis = options.xAxis, yAxis = options.yAxis; return utils_2.flow(common_1.scale({ range: xAxis, count: yAxis, }))(params); } /** * axis 配置 * @param params */ function axis(params) { var chart = params.chart, options = params.options; var xAxis = options.xAxis, yAxis = options.yAxis; // 为 false 则是不显示轴 if (xAxis === false) { chart.axis('range', false); } else { chart.axis('range', xAxis); } if (yAxis === false) { chart.axis('count', false); } else { chart.axis('count', yAxis); } return params; } /** * label 配置 * @param params */ function label(params) { var chart = params.chart, options = params.options; var label = options.label; var geometry = utils_1.findGeometry(chart, 'interval'); if (!label) { geometry.label(false); } else { var callback = label.callback, cfg = tslib_1.__rest(label, ["callback"]); geometry.label({ fields: ['count'], callback: callback, cfg: utils_2.transformLabel(cfg), }); } return params; } /** * 直方图适配器 * @param chart * @param options */ function adaptor(params) { // flow 的方式处理所有的配置到 G2 API return utils_2.flow(geometry, meta, axis, common_1.theme, common_1.state, label, common_1.tooltip, common_1.interaction, common_1.animation)(params); } exports.adaptor = adaptor; //# sourceMappingURL=adaptor.js.map;(function() { 'use strict'; /** * Change user password component */ angular .module('digitApp') .component('changePassword', { templateUrl: 'app/change-password/change-password.html', controllerAs: 'vm', controller: ChangePasswordCtrl }); ChangePasswordCtrl.$inject = ['$rootScope', '$log', 'ngDialog', 'QueryService']; function ChangePasswordCtrl($rootScope, $log, ngDialog, QueryService) { var vm = this; // methods vm.changePassword = changePassword; /// definitions /** * Change password */ function changePassword() { var params = { password: <PASSWORD>, confirmPassword: <PASSWORD> }; QueryService .query('PUT', 'users/change-password', null, params) .then(function(user) { var dialog = ngDialog.open({ template: '\ <p>Password changed successfully! You will be logged out of system after dialog confirmation.</p>\ <div class="ngdialog-buttons">\ <button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="closeThisDialog(\'ok\')">OK</button>\ </div>', plain: true }); dialog.closePromise.then(function(closedDialog) { $rootScope.$broadcast('user:logout'); }); }) .catch(function(err) { $log.debug(err); }); } } })(); 'use strict'; function assertHasId(model) { if (!model.$hasId()) { const modelClass = model.constructor; const ids = modelClass.getIdColumnArray().join(', '); throw new Error( `one of the identifier columns [${ids}] is null or undefined. Have you specified the correct identifier column for the model '${ modelClass.name }' using the 'idColumn' property?` ); } } module.exports = { assertHasId }; /* Name: Style Switcher Initializer Written by: Crivos - (http://www.crivos.com) Version: 1.0 */ var styleSwitcher = { initialized: false, initialize: function() { var $this = this; if (this.initialized) return; this.initialized = true; // Style Switcher CSS $("head").append($('<link rel="stylesheet">').attr("href", "master/style-switcher/style-switcher.css") ); $("head").append($('<link rel="stylesheet/less">').attr("href", "master/less/skin.less") ); $("head").append($('<link rel="stylesheet">').attr("href", "master/style-switcher/colorpicker/css/colorpicker.css") ); $.getScript("master/style-switcher/colorpicker/js/bootstrap-colorpicker.js", function(data, textStatus, jqxhr) { less = { env: "development" }; $.getScript("master/less/less.js", function(data, textStatus, jqxhr) { $this.build(); $this.events(); if($.cookie("skin") != null) { $this.setColor($.cookie("skin")); } else { $this.container.find("ul[data-type=colors] li:first a").click(); } if($.cookie("layout") != null) $this.setLayoutStyle($.cookie("layout")); if($.cookie("pattern") != null) $this.setPattern($.cookie("pattern")); if($.cookie("initialized") == null) { $this.container.find("h4 a").click(); $.cookie("initialized", true); } }); }); $.getScript("master/style-switcher/cssbeautify/cssbeautify.js", function(data, textStatus, jqxhr) {}); }, build: function() { var $this = this; // Base HTML var switcher = $("<div />") .attr("id", "styleSwitcher") .addClass("style-switcher hidden-phone") .append( $("<h4 />") .html("Style Switcher") .append( $("<a />") .attr("href", "#") .append( $("<i />") .addClass("icon-cogs") ) ), $("<div />") .addClass("style-switcher-wrap") .append( $("<h5 />") .html("Colors"), $("<ul />") .addClass("options") .attr("data-type", "colors"), $("<h5 />") .html("Layout Style"), $("<div />") .addClass("options-links layout") .append( $("<a />") .attr("href", "#") .attr("data-layout-type", "wide") .addClass("active") .html("Wide"), $("<a />") .attr("href", "#") .attr("data-layout-type", "boxed") .html("Boxed") ), $("<div />") .hide() .addClass("patterns") .append( $("<h5 />") .html("Background Patterns"), $("<ul />") .addClass("options") .attr("data-type", "patterns") ), $("<hr />"), $("<div />") .addClass("options-links") .append( $("<a />") .addClass("reset") .attr("href", "#") .html("Reset"), $("<a />") .addClass("get-css") .attr("href", "#getCSSModal") .html("Get Skin CSS") ) ) ); $("body").append(switcher); var modalHTML = '<div id="getCSSModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="cssModalLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="cssModalLabel">Skin CSS</h3></div><div class="modal-body"><div class="alert alert-info fade in" id="addBoxedClassInfo">Please add the <strong>"boxed"</strong> class to the <body> element.</div><textarea id="getCSSTextarea" class="get-css" readonly></textarea></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Close</button></div></div>'; $("body").append(modalHTML); this.container = $("#styleSwitcher"); // Colors Skins var colors = [ {"Hex": "#0088CC", "colorName": "Blue"}, {"Hex": "#4EB25C", "colorName": "Green"}, {"Hex": "#4A5B7D", "colorName": "Navy"}, {"Hex": "#E05048", "colorName": "Red"}, {"Hex": "#B8A279", "colorName": "Beige"}, {"Hex": "#c71c77", "colorName": "Pink"}, {"Hex": "#734BA9", "colorName": "Purple"}, {"Hex": "#2BAAB1", "colorName": "Cyan"} ]; var colorList = this.container.find("ul[data-type=colors]"); $.each(colors, function(i, value) { var color = $("<li />") .append( $("<a />") .css("background-color", colors[i].Hex) .attr({ "data-color-hex": colors[i].Hex, "data-color-name": colors[i].colorName, "href": "#", "title": colors[i].colorName }) ); colorList.append(color); }); if($.cookie("skin") != null) { var currentSkinColor = $.cookie("skin"); } else { var currentSkinColor = colors[0].Hex; } var colorPicker = $("<li />") .append( $("<div />") .attr("id", "colorSelector") .attr("data-color", currentSkinColor) .attr("data-color-format", "hex") .addClass("color-picker") .append( $("<a />") .css("background-color", currentSkinColor) .attr({ "href": "#", }), $("<span />") .addClass("color-picker-icon") ) ); colorList.append(colorPicker); colorList.find("a").click(function(e) { e.preventDefault(); $this.setColor($(this).attr("data-color-hex")); }); $("#colorSelector").colorpicker().on('hide', function(ev) { $this.setColor(ev.color.toHex()); $("#colorSelector").find("a").css("background-color", ev.color.toHex()) }); $("#colorSelector a").click(function(e) { e.preventDefault(); }); $(".colorpicker-saturation").mouseup(function() { $("#colorSelector").colorpicker("hide"); }); // Layout Styles this.container.find("div.options-links.layout a").click(function(e) { e.preventDefault(); $this.setLayoutStyle($(this).attr("data-layout-type"), true); }); // Background Patterns var patterns = ["gray_jean", "linedpaper", "az_subtle", "blizzard", "denim", "fancy_deboss", "honey_im_subtle", "linen", "pw_maze_white", "skin_side_up", "stitched_wool", "straws", "subtle_grunge", "textured_stripes", "wild_oliva", "worn_dots", "bright_squares", "random_grey_variations"]; var patternsList = this.container.find("ul[data-type=patterns]"); $.each(patterns, function(key, value) { var pattern = $("<li />") .append( $("<a />") .addClass("pattern") .css("background-image", "url(img/patterns/" + value + ".png)") .attr({ "data-pattern": value, "href": "#", "title": value.charAt(0).toUpperCase() + value.slice(1) }) ); patternsList.append(pattern); }); patternsList.find("a").click(function(e) { e.preventDefault(); $this.setPattern($(this).attr("data-pattern")); }); // Reset $this.container.find("a.reset").click(function(e) { e.preventDefault(); $this.reset(); }); // Get CSS $this.container.find("a.get-css").click(function(e) { e.preventDefault(); $this.getCss(); }); }, events: function() { var $this = this; $this.container.find("h4 a").click(function(e){ e.preventDefault(); if($this.container.hasClass("active")) { $this.container.animate({ left: "-195px" }, 300).removeClass("active"); } else { $this.container.animate({ left: "0" }, 300).addClass("active"); } }) if($.cookie("showSwitcher") != null) { $this.container.find("h4 a").click(); $.removeCookie("showSwitcher"); } }, setColor: function(color) { less.modifyVars({ skinColor : color }); $.cookie("skin", color); // Default Logo if(color == this.container.find("ul[data-type=colors] li:first a").attr("data-color-hex")) { $("h1.logo img").attr("src", "img/logo-default.png"); } else { $("h1.logo img").attr("src", "img/logo.png"); } }, setLayoutStyle: function(style, refresh) { $.cookie("layout", style); if(refresh) { $.cookie("showSwitcher", true); window.location.reload(); return false; } var layoutStyles = this.container.find("div.options-links.layout"); var backgroundPatterns = this.container.find("div.patterns"); layoutStyles.find("a.active").removeClass("active"); layoutStyles.find("a[data-layout-type=" + style + "]").addClass("active"); if(style == "wide") { backgroundPatterns.hide(); $("body").removeClass("boxed"); $("link[href*='bootstrap-responsive']").attr("href", "css/bootstrap-responsive.css"); $.removeCookie("pattern"); } else { backgroundPatterns.show(); $("body").addClass("boxed"); $("link[href*='bootstrap-responsive']").attr("href", "css/bootstrap-responsive-boxed.css"); if($.cookie("pattern") == null) this.container.find("ul[data-type=patterns] li:first a").click(); } }, setPattern: function(pattern) { var isBoxed = $("body").hasClass("boxed"); if(isBoxed) $("body").css("background-image", "url(img/patterns/" + pattern + ".png)") $.cookie("pattern", pattern); }, reset: function() { $.removeCookie("skin"); $.removeCookie("layout"); $.removeCookie("pattern"); $.cookie("showSwitcher", true); window.location.reload(); }, getCss: function() { raw = ""; var isBoxed = $("body").hasClass("boxed"); if(isBoxed) { raw = 'body { background-image: url("img/patterns/' + $.cookie("pattern") + '.png"); }'; $("#addBoxedClassInfo").show(); } else { $("#addBoxedClassInfo").hide(); } $("#getCSSTextarea").text(""); $("#getCSSTextarea").text($('style[id^="less:"]').text()); $("#getCSSModal").modal("show"); options = { indent: "\t", autosemicolon: true }; raw = raw + $("#getCSSTextarea").text(); $("#getCSSTextarea").text(cssbeautify(raw, options)); } }; styleSwitcher.initialize();<filename>src/utils/transformers/ltiVersionTransformer.js import {dummy} from "../constants"; export const ltiVersionTransformer = { toSelect(ltiVersions) { return ltiVersions.map(i => { let item = {}; item.value = i.versionId; item.label = i.version; return item; }); }, toFilter (ltiVersions) { return ltiVersions.reduce((map, ltiVer)=> { map[ltiVer.versionId] = ltiVer.version; return map; }, {}); }, toSelectWithDummy(ltiVersions) { if (!ltiVersions) { return [dummy]; } let result = ltiVersionTransformer .toSelect(ltiVersions); result.unshift(dummy); return result; }, }<reponame>GulajavaMinistudio/BlogWWWID import ArtikelModel from '@/components/models/ArtikelModel'; export default { name: 'ListItemComponent', props: { propsArtikelItem: { type: Object, default() { return new ArtikelModel(); }, }, }, data() { return { artikelItem: this.propsArtikelItem, categoryartikel: this.propsArtikelItem.categories, linkGambar: '', }; }, methods: { navigasiDetailHalaman() { }, }, computed: { }, filters: { snippetFilter(value) { const slicedDesc = `${value.toString().slice(0, 300)}...`; return slicedDesc; }, }, mounted() { this.linkGambar = this.propsArtikelItem.thumbnail; }, }; // Add content-security-policy in manifest. Below one giving error. // "content_security_policy": "default-src 'self'" // The group's color. ENUM "grey", "blue", "red", "yellow", "green", "pink", "purple", or "cyan" let groupInfo = { title: "", id: "", color: ""}; let allGroupsInfo = [] // [] of groupInfo chrome.runtime.onInstalled.addListener(() => { chrome.tabs.query({ currentWindow: true }, function (tabs) { tabs.sort((a, b) => { return a.index < b.index; }); console.log('Tabs List (Sorted):\n'); console.log(tabs) // Collect all different groups and query for them }); console.log(chrome) chrome.tabGroups.query( {}, function(tabGroups) { // 804016250 console.log("Groups:\n") console.log(tabGroups) // tabGroup.map( oneGrp => { // groupInfo. // }) }); }); // groups in tabs // TAB_GROUP_ID_NONE = -1. An ID that represents the absence of a group. // tabs.groupId maps to import DOMBuilder from "../DOM/DOMBuilder"; import pageLayout from "./pageLayout"; import { DirectoryDisplay } from '../DOM/DOMDirectory'; const basePageBuilder = ()=> { pageLayout.forEach((obj)=>{ DOMBuilder(obj); }); } const buildProjects = (todoList)=>{ const projectTitles = todoList.getAllProjectTitles(); const projectList = document.querySelector(".projectList"); if(projectList.children) clearPanel(projectList); if(projectTitles !== null && projectTitles.length>0) projectTitles.forEach((title)=>{ const Project = { element: "div", className: ["project"], textContent: title, }; DOMBuilder(Project, projectList); }); }; const buildTasks = (DirDisplay, todoList)=>{ const taskSummary = todoList.getAllTaskSummary(); const taskList = document.querySelector(".taskPanel"); if(taskList.children) clearPanel(taskList); if(taskSummary !== null && taskSummary.length>0) taskSummary.forEach((taskSummary)=>{ const taskDom = taskDOMFactory(taskSummary) DOMBuilder(taskDom, taskList); }); DirDisplay.totalTasks.textContent = todoList.getCurrentProjectTasksCount(); DirDisplay.activeTasks.textContent = todoList.getCurrentProjectActiveTasksCount(); }; const displayTask = (todoList)=>{ const DirDisplay = DirectoryDisplay(); let task = todoList.getCurrentTask(); let taskDueDay = todoList.getTaskDueDay(); let taskDeadline = todoList.getTaskDeadline(); if(task === null) task = ["Title", "Due Date", "Priority", "Task Discription", "Done Status"]; if(taskDueDay === null) task.push(["Due Day"]); else task.push([taskDueDay]); if(taskDeadline === null) task.push(["Days left"]); else task.push([taskDeadline]); DirDisplay.taskTitle.textContent = task[0]; DirDisplay.taskDiscription.textContent = task[4]; DirDisplay.taskDueDate.textContent = task[1]; toggleDone(DirDisplay.taskDone, task[3]); DirDisplay.taskDueDay.textContent = task[5]; DirDisplay.taskDeadline.textContent = task[6]; switch (task[2]) { case 1: case "1": DirDisplay.taskPriority.textContent = "Normal"; break; case 2: case "2": DirDisplay.taskPriority.textContent = "High"; break; case 3: case "3": DirDisplay.taskPriority.textContent = "IMPORTANT"; break; default: DirDisplay.taskPriority.textContent = "Invalid"; break; } } function clearPanel(parentNode) { while(parentNode.firstChild){ parentNode.removeChild(parentNode.lastChild); } } function toggleDone(doneBtnElement, result) { if(result) doneBtnElement.textContent = "Completed"; else doneBtnElement.textContent = "Active"; doneBtnElement.dataset.status = result; } export {basePageBuilder, buildProjects, buildTasks, displayTask, toggleDone}; function taskDOMFactory(Summary) { let priority; switch (Summary.priority) { case 1: case "1": priority = "Normal"; break; case 2: case "2": priority = "High"; break; case 3: case "3": priority = "IMPORTANT"; break; default: priority = "Invalid"; break; } const TaskDOMObject = { element: "div", className: ["task"], attributes:{ "data-done":Summary.done, }, childNodes: [ { element: "div", className: ["taskTitle"], textContent: Summary.title, }, { element: "div", className: ["taskDeadline"], textContent: Summary.deadline, }, { element: "div", className: ["taskPriority"], textContent: priority, }, ], }; return TaskDOMObject; }/** Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... Example: (1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. (2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2]. Note: You may assume all input has valid answer. Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space? */ /** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var wiggleSort = function(nums) { var len = nums.length, temp = [], midIndex = parseInt((len + 1) / 2), i, l, r, medium; medium = findKth(0, len - 1, midIndex, nums); for (i = 0, l = 0, r = len - 1; i < len; i++) { if (nums[i] < medium) { temp[l++] = nums[i]; } else if (nums[i] > medium) { temp[r--] = nums[i]; } } while (l < midIndex) { temp[l++] = medium; } while (r >= midIndex) { temp[r--] = medium; } r = len; for (i = 0; i < len; i++) { nums[i] = (i & 1) === 0? temp[--l] : temp[--r]; } }; function findKth(start, end, k, nums) { if (start >= end) { return nums[end]; } var index = partition(start, end, nums), count = index - start + 1; if (count === k) { return nums[index]; } if (count < k) { return findKth(index + 1, end, k - count, nums); } return findKth(start, index - 1, k, nums); } function partition(start, end, nums) { var val = nums[start], i, j; i = start + 1; j = end; while (true) { while (nums[i] <= val) { i++; } while (nums[j] > val) { j--; } if (i >= j) { break; } swap(nums, i, j); } swap(nums, j, start); return j; } function swap(nums, i, j) { var temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } const weatherAPI = "https://www.metaweather.com/api"; const weatherIconsAPI = "https://www.metaweather.com/static/img/weather"; const convertFarenheit = temp => ((temp * 9/5) + 32); const convertVelocity = vel => (vel*1.609); export { weatherAPI, weatherIconsAPI, convertFarenheit, convertVelocity}import React from 'react' import { withStyles } from 'material-ui/styles'; //import { classes } from 'istanbul-lib-coverage'; // const styles= ()=>({ // dashboardContainer:{ // } // }) class TripView extends React.Component{ render(){ return ( <div >This is TripView</div> ) } } export default withStyles()(TripView)<filename>packages/browserify/test/globalWrites.js const test = require('ava') const { createBundleFromRequiresArray, evalBundle, } = require('./util') // here we are providing an endowments only to a module deep in a dep graph test('globalWrites - two deps should be able to read each others globals', async (t) => { const entries = [ { id: '/one.js', file: '/one.js', source: "global.testResult.value = require('two');", deps: { two: '/node_modules/two/index.js' }, entry: true }, { id: '/node_modules/two/index.js', file: '/node_modules/two/index.js', source: ` xyz = true module.exports = require('three') `, deps: { three: '/node_modules/three/index.js' } }, { id: '/node_modules/three/index.js', file: '/node_modules/three/index.js', source: ` module.exports = xyz `, deps: {} } ] const policy = { resources: { '<root>': { packages: { two: true } }, two: { globals: { xyz: 'write' }, packages: { three: true } }, three: { globals: { xyz: true } } } } const bundle = await createBundleFromRequiresArray(entries, { policy }) const testResult = evalBundle(bundle) t.is(testResult.value, true) }) /** * @format * @flow strict-local */ import React, { Component, useState } from 'react'; import { SafeAreaView, Text, View, StyleSheet, Pressable, Animated, Easing, Image, ActivityIndicator, Alert, Platform, } from 'react-native'; import { ViroARSceneNavigator, } from '@viro-community/react-viro'; var joystickWidth = 200; import ARScene from '../ARScenes/ARScene' import LoadingIndicator from '../components/LoadingIndicator'; import styles from '../styles/styles' class ARScreen extends Component { constructor(props) { super(props) this.state = { // initial state here showInstructions: true, instructionOpacity: new Animated.Value(1), carControlsOpacity: new Animated.Value(0), isReady: false, isOverPlane: false, left: false, up: false, right: false, down: false, touchLocation: "0,0", leftRightRatio: 0, shouldResetCar: false, isRecording: false, shouldPlayMedia: true, // whether or not the AR session should play media (probably because its hidden) hours: '00', minutes: '00', seconds: '00', } // bind functions here this.getViroARView = this.getViroARView.bind(this); this.exitAR = this.exitAR.bind(this); //this.getRecordingUI = this.getRecordingUI.bind(this); this.getReadyUI = this.getReadyUI.bind(this); this.ready = this.ready.bind(this); this.getInstructions = this.getInstructions.bind(this); this.setIsOverPlane = this.setIsOverPlane.bind(this); this.resetCar = this.resetCar.bind(this); this.getCarControls = this.getCarControls.bind(this); this.getDrivingPedals = this.getDrivingPedals.bind(this); this.getJoystick = this.getJoystick.bind(this); this.getResetButton = this.getResetButton.bind(this); this.getPressDown = this.getPressDown.bind(this); this.getPressUp = this.getPressUp.bind(this); this.joystickStart = this.joystickStart.bind(this); this.joystickMove = this.joystickMove.bind(this); this.joystickEnd = this.joystickEnd.bind(this); this.setJoystickProps = this.setJoystickProps.bind(this); } componentDidMount() { } componentWillUnmount() { } render() { let text = "" + (this.state.left ? "Left," : "") + (this.state.up ? "Up," : "") + (this.state.right ? "Right," : "") + (this.state.down ? "Down," : "") return ( <SafeAreaView style={styles.outerContainer}> <View style={styles.outerContainer}> {this.getViroARView()} {this.getCarControls()} {/* Get instructions and ready */} {this.getReadyUI()} {this.getInstructions()} </View> </SafeAreaView> ) } getViroARView() { // use viroAppProps to pass in "changing/dynamic" values, passProps is "not" dynamic. let viroAppProps = { direction: (this.state.left ? 1 : 0) + (this.state.up ? 2 : 0) + (this.state.right ? 4 : 0) + (this.state.down ? 8 : 0), leftRightRatio: this.state.leftRightRatio, shouldResetCar: this.state.shouldResetCar, isReady: this.state.isReady, setIsOverPlane: this.setIsOverPlane, } return ( <ViroARSceneNavigator ref={(ref) => { this.arNavigator = ref }} viroAppProps={viroAppProps} initialScene={{ scene: ARScene, passProps: { onARInitialized: this.onARInitialized, onPosterFound: this.onPosterFound, onExperienceFinished: this.onExperienceFinished, onARSceneCreated: this.onARSceneCreated, }, }} /> ); } getCarControls() { return ( <Animated.View style={{ position: 'absolute', width: '100%', height: '100%', opacity: this.state.carControlsOpacity }}> {/* These are the controls to drive the car */} {this.getDrivingPedals()} {this.getResetButton()} {this.getJoystick()} </Animated.View> ) } getDrivingPedals() { return ( <View style={styles.drivingButtonsContainer} > <View style={styles.drivingButton} > <Image style={styles.pedalImage} opacity={this.state.down ? 0 : 1} source={require('../assets/pedal_reverse.png')} /> <Image style={styles.pedalImage} opacity={!this.state.down ? 0 : 1} source={require('../assets/pedal_reverse_press.png')} /> <View style={styles.pedalTouchArea} onTouchStart={this.getPressDown('down')} onTouchEnd={this.getPressUp('down')} /> </View> <View style={styles.drivingButton} > <Image style={styles.pedalImage} opacity={this.state.up ? 0 : 1} source={require('../assets/pedal_accel.png')} /> <Image style={styles.pedalImage} opacity={!this.state.up ? 0 : 1} source={require('../assets/pedal_accel_press.png')} /> <View style={styles.pedalTouchArea} onTouchStart={this.getPressDown('up')} onTouchEnd={this.getPressUp('up')} /> </View> </View> ) } getJoystick() { let rotation = '' + (this.state.left ? '-' : '') + Math.round(this.state.leftRightRatio * 90) + 'deg' let joystickButtonStyle = { height: 130, width: 200, resizeMode: 'contain', transform: [{ rotate: rotation }] } /* This is the joystick/steering wheel component, since the image is rotating, we need that "invisible" view to capture the touch events. */ return ( <View style={styles.joystickContainer} > <Image style={joystickButtonStyle} source={require('../assets/steering_wheel.png')} /> <View style={styles.joystickTouchArea} onTouchStart={this.joystickStart} onTouchMove={this.joystickMove} onTouchEnd={this.joystickEnd} /> </View> ) } getResetButton() { return ( <Pressable style={styles.resetButton} onPress={this.resetCar} activeOpacity={0.6} > <Image style={styles.resetImage} source={require('../assets/icon_refresh.png')} /> </Pressable> ) } resetCar() { this.setState({ shouldResetCar: true, }) // reset the flag 1 second later. setTimeout(() => { this.setState({ shouldResetCar: false, }) }, 1000) } getPressDown(key) { return () => { let dict = {} dict[key] = true this.setState(dict) } } getPressUp(key) { return () => { let dict = {} dict[key] = false this.setState(dict) } } joystickStart(evt) { this.setJoystickProps(evt); } joystickMove(evt) { this.setJoystickProps(evt); this.setState({ touchLocation: "" + evt.nativeEvent.locationX.toFixed(2) + ", " + evt.nativeEvent.locationY.toFixed(2) + ", " + evt.nativeEvent.pageX.toFixed(2) + ", " + evt.nativeEvent.pageY.toFixed(2) }) } joystickEnd(evt) { this.setState({ left: false, right: false, leftRightRatio: 0, }) } setJoystickProps(evt) { let locationX = evt.nativeEvent.locationX; // position relative to top left of view let pageX = evt.nativeEvent.pageX; // position relative to top left of screen let leftValue = false; let rightValue = false; let ratio = 0; let halfWidth = joystickWidth / 2; if (Platform.OS == 'android') { // on Android, the locationX reverts to pageX when off the button/view if (locationX != pageX) { if (locationX <= halfWidth) { leftValue = true; ratio = (halfWidth - locationX) / halfWidth } else { rightValue = true; ratio = (halfWidth - joystickWidth + locationX) / halfWidth } } else { /* if we went off the button to the left or right, then we simply set the ratio to max (1) */ // TODO: this isn't actually accurate, we need to keep track of where // relative to the top left corner of the button because a soon as we // leave the button, we get all page coordinates. keep track on "down" ratio = 1; leftValue = this.state.left; rightValue = this.state.right; } } else { // iOS if (locationX <= 0 || locationX >= joystickWidth) { ratio = 1; leftValue = this.state.left; rightValue = this.state.right; } else { if (locationX <= halfWidth) { leftValue = true; ratio = (halfWidth - locationX) / halfWidth } else { rightValue = true; ratio = (halfWidth - joystickWidth + locationX) / halfWidth } } } this.setState({ left: leftValue, right: rightValue, leftRightRatio: Math.max(Math.min(ratio, 1), 0), // bound ratio to 0 -> 1 }) } getReadyUI() { if (this.state.showInstructions) { let text = this.state.isOverPlane ? ' ' : 'Finding the floor...' let overlayStyle = { position: 'absolute', width: '100%', height: '100%', } let readyButton = { height: 60, width: 130, marginTop: 10, backgroundColor: '#292930B3', borderRadius: 10, borderWidth: 2, borderColor: '#fff', justifyContent: 'center', alignItems: 'center', opacity: this.state.isOverPlane ? 1 : .5, } return ( <Animated.View style={{ ...overlayStyle, opacity: this.state.instructionOpacity }}> <View style={styles.readyContainer}> <Text style={styles.instructionText}> {text} </Text> <Pressable style={readyButton} opacity={.5} onPress={this.ready} disabled={!this.state.isOverPlane} activeOpacity={0.6}> <Text style={styles.instructionText}> Place </Text> </Pressable> </View> </Animated.View> ) } } ready() { // only allow ready to be clicked when the user has click over a plane! if (!this.state.isOverPlane) { return; } Animated.timing(this.state.instructionOpacity, { toValue: 0, duration: 1000, useNativeDriver: true, easing: Easing.linear, }).start(() => { this.setState({ showInstructions: false, isReady: true, }) }) setTimeout(() => { Animated.timing(this.state.carControlsOpacity, { toValue: 1, duration: 500, useNativeDriver: true, easing: Easing.linear, }).start() }, 1000) } getInstructions() { if (!this.state.showInstructions) { return } var instructionContainer = { position: 'absolute', backgroundColor: '#000000B3', flexDirection: 'column', width: '100%', height: 100, justifyContent: 'center', top: 0, left: 0, } let instructions = "Scan the ground and tap Place to begin." return ( <Animated.View style={{ ...instructionContainer, opacity: this.state.instructionOpacity }}> <Text style={styles.instructionText}> {instructions} </Text> </Animated.View> ) } // this function will be called by the AR system when the user is hovering over a plane setIsOverPlane(isOverPlane) { if (this.state.isOverPlane != isOverPlane) { this.setState({ isOverPlane: isOverPlane, }) } } exitAR() { this.props.navigation.goBack(); } } export default ARScreen; import React from 'react'; import {SkipLinks} from 'frontend/navigation/SkipLinks'; import styles from 'frontend/navigation/SkipLinks.module.css'; import {render} from '@testing-library/react'; describe('SkipLinks', () => { it('renders skip links', async () => { const {getByText} = render(<SkipLinks />); expect(getByText(/content/).classList.contains(styles.link)).toBe(true); }); it('focus the button', async () => { const {container} = render(<SkipLinks />); const elem = document.getElementsByClassName(styles.link)[0]; elem.focus(); expect(document.activeElement).toBe(elem); }); }); import { PahoMQTT } from './mqtt' export const MqttMixin = { data() { return { ip: `${window.location.hostname}`, port: 61614, clientId: 'mqttjs_' + Math.random() .toString(16) .substr(2, 8), mqttData: {} } }, mounted() { const client = new PahoMQTT.Client(this.ip, this.port, this.clientId) client.onConnectionLost = responseObject => { if (responseObject.errorCode !== 0) { console.log('onConnectionLost:' + responseObject.errorMessage) } } client.onMessageArrived = message => { this.mqttData = JSON.parse(message.payloadString) } client.connect({ onSuccess: () => { // client.subscribe(`device_data_${gateway}`) // client.subscribe(`card_data_${gateway}`) const message = new PahoMQTT.Message('Hello') message.destinationName = 'World' client.send(message) } }) } } import React, {Component} from 'react'; import { Affix, Icon, Modal, Form, Input, message, Select, Mention } from 'antd'; import { inject, observer } from 'mobx-react'; const FormItem = Form.Item; const Option = Select.Option; const { toString, toContentState, getMentions } = Mention; @inject('UrlStore') @observer class NewUrl extends Component { state = { add_modal_show: false, add_modal_submitLoading: false } handleOk = () => { this.props.form.validateFieldsAndScroll((err, values) => { if (!err) { console.log('Received values of form: ', values); console.log( getMentions(values.category)); // 检查是否存在新的 category getMentions(values.category).map((item => { console.log(item); if(this.props.UrlStore.category.indexOf(item.replace("@",'')) < 0 ){ this.props.UrlStore.addCategory({name: item.replace("@",'')}); } })) console.log(this.props.UrlStore.category); // this.setState({add_modal_submitLoading: true}); // this.props.UrlStore.add(values).then(e => { // if (e.code === 200) { // this.handleCancel(); // this.setState({add_modal_show: false}); // } // }).catch(e => { // message.error(e); // }).finally(()=>{ // this.setState({add_modal_submitLoading: false}); // }); } }); } handleCancel = () => { this.props.form.resetFields(); this.setState({add_modal_show: false}); } handleShowAdd = () => { this.setState({add_modal_show: true}); } render(){ const { add_modal_show, add_modal_submitLoading } = this.state; const { getFieldDecorator } = this.props.form; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 4 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 16 }, }, }; return ( <div> <Affix className='url__new' onClick={this.handleShowAdd}> <Icon type="plus-circle" className='url__new--icon' /> </Affix> <Modal title="添加" visible={add_modal_show} onOk={this.handleOk} confirmLoading={add_modal_submitLoading} onCancel={this.handleCancel} > <FormItem {...formItemLayout} label="名称" > {getFieldDecorator('title', { rules: [{ required: true, message: 'Please input your title!' }], })( <Input prefix={<Icon type="tag-o" />} placeholder="名称" /> )} </FormItem> <FormItem {...formItemLayout} label="Url" > {getFieldDecorator('url', { rules: [{ required: true, message: 'Please input your Url!' }], })( <Input prefix={<Icon type="link" />} placeholder="链接" /> )} </FormItem> <FormItem {...formItemLayout} label="类型" > {getFieldDecorator('type', { initialValue: 'default' })( <Select style={{ width: 120 }}> <Option value="default">default</Option> <Option value="primary">primary</Option> <Option value="dashed">dashed</Option> <Option value="danger">danger</Option> </Select> )} </FormItem> <FormItem {...formItemLayout} label="分类" > {getFieldDecorator('category', { })( <Mention style={{ width: '100%' }} suggestions={this.props.UrlStore.category} /> )} </FormItem> </Modal> </div> ) } } export default Form.create()(NewUrl); <reponame>naterkane/jwt-microservices-oauth var express = require('express'); var bodyParser = require('body-parser'); var oauthserver = require('oauth2-server'); var memorystore = require('./model.js'); var app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.oauth = oauthserver({ model: memorystore, grants: ['password', 'refresh_token'], debug: true, accessTokenLifetime: memorystore.JWT_ACCESS_TOKEN_EXPIRY_SECONDS, // expiry time in seconds, consistent with JWT setting in model.js refreshTokenLifetime: memorystore.JWT_REFRESH_TOKEN_EXPIRY_SECONDS // expiry time in seconds, consistent with JWT setting in model.js }); app.all('/oauth/token', app.oauth.grant()); app.get('/', app.oauth.authorise(), function (req, res) { res.send('Secret area'); }); app.use(app.oauth.errorHandler()); app.listen(3000);<reponame>BarbourSmith/JSxCAD import { fromShapefile } from './fromShapefile.js'; import fs from 'fs'; import test from 'ava'; const { readFile } = fs.promises; test('Boolean Properties', async (t) => { const shp = await readFile('boolean-property.shp'); const dbf = await readFile('boolean-property.dbf'); const data = await fromShapefile(shp, dbf); t.deepEqual(data, { type: 'assembly', content: [ { type: 'points', points: [[1, 2, 0]], tags: ['user/shapefile/foo/null'], }, { type: 'points', points: [[3, 4, 0]], tags: ['user/shapefile/foo/true'], }, { type: 'points', points: [[5, 6, 0]], tags: ['user/shapefile/foo/true'], }, { type: 'points', points: [[7, 8, 0]], tags: ['user/shapefile/foo/false'], }, { type: 'points', points: [[9, 10, 0]], tags: ['user/shapefile/foo/false'], }, { type: 'points', points: [[11, 12, 0]], tags: ['user/shapefile/foo/true'], }, { type: 'points', points: [[13, 14, 0]], tags: ['user/shapefile/foo/true'], }, { type: 'points', points: [[15, 16, 0]], tags: ['user/shapefile/foo/false'], }, { type: 'points', points: [[17, 18, 0]], tags: ['user/shapefile/foo/false'], }, ], tags: [], }); }); import React from 'react'; import { ScrollView, View, TouchableOpacity, StyleSheet } from 'react-native'; import { RkText, RkStyleSheet, RkTheme } from 'react-native-ui-kitten'; import { RkSwitch, FindFriends } from '../../components'; import {FontAwesome} from '../../assets/icons'; export class Settings extends React.Component { static navigationOptions = { title: 'Settings'.toUpperCase() }; constructor(props) { super(props); this.state = { sendPush: true, shouldRefresh: false, twitterEnabled: true, googleEnabled: false, facebookEnabled: true } } render() { return ( <ScrollView style={styles.container}> <View style={styles.section}> <View style={[styles.row, styles.heading]}> <RkText rkType='primary header6'>PROFILE SETTINGS</RkText> </View> <View style={styles.row}> <TouchableOpacity style={styles.rowButton}> <RkText rkType='header6'>Edit Profile</RkText> </TouchableOpacity> </View> <View style={styles.row}> <TouchableOpacity style={styles.rowButton}> <RkText rkType='header6'>Change Password</RkText> </TouchableOpacity> </View> <View style={styles.row}> <RkText rkType='header6'>Send Push Notifications</RkText> <RkSwitch style={styles.switch} value={this.state.sendPush} name="Push" onValueChange={(sendPush) => this.setState({sendPush})}/> </View> <View style={styles.row}> <RkText rkType='header6'>Refresh Automatically</RkText> <RkSwitch style={styles.switch} value={this.state.shouldRefresh} name="Refresh" onValueChange={(shouldRefresh) => this.setState({shouldRefresh})}/> </View> </View> <View style={styles.section}> <View style={[styles.row, styles.heading]}> <RkText rkType='primary header6'>SUPPORT</RkText> </View> <View style={styles.row}> <TouchableOpacity style={styles.rowButton}> <RkText rkType='header6'>Help</RkText> </TouchableOpacity> </View> <View style={styles.row}> <TouchableOpacity style={styles.rowButton}> <RkText rkType='header6'>Privacy Policy</RkText> </TouchableOpacity> </View> <View style={styles.row}> <TouchableOpacity style={styles.rowButton}> <RkText rkType='header6'>Terms & Conditions</RkText> </TouchableOpacity> </View> <View style={styles.row}> <TouchableOpacity style={styles.rowButton} onPress={() => this.props.navigation.navigate('Login2',{id: 0})}> <RkText rkType='header6'>Logout</RkText> </TouchableOpacity> </View> </View> </ScrollView> ) } } let styles = RkStyleSheet.create(theme => ({ container: { backgroundColor: theme.colors.screen.base, }, header: { paddingVertical: 25 }, section: { marginVertical: 25 }, heading: { paddingBottom: 12.5 }, row: { flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 17.5, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: theme.colors.border.base, alignItems: 'center' }, rowButton: { flex: 1, paddingVertical: 24 }, switch: { marginVertical: 14 }, })); /* eslint-disable no-undefined */ const Page = require('./ExpandableListPage'), {validateTitle, expectClosed, expectOpen} = require('./ExpandableList-utils.js'); describe('ExpandableList', function () { beforeEach(function () { Page.open(); }); it('should have focus on first expandable at start', function () { expect(Page.components.radioSelect.title.isFocused()).to.be.true(); }); describe('radio select', function () { const expandable = Page.components.radioSelect; validateTitle(expandable, 'ExpandableList Radio Select'); it('should have correct none text', function () { expect(expandable.valueText).to.equal('Nothing Selected'); }); it('should be initially closed', function () { expectClosed(expandable); }); describe('5-way', function () { it('should open and spot first item on select', function () { Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); expectOpen(expandable); expect(expandable.item(0).isFocused()).to.be.true(); }); it('should close when moving up to header', function () { Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); expect(expandable.isOpen).to.be.true(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightUp(); }); expect(expandable.isOpen).to.be.false(); expect(expandable.title.isFocused()).to.be.true(); }); it('should not allow 5-way exit from bottom', function () { Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); expect(expandable.isOpen).to.be.true(); Page.spotlightDown(); Page.spotlightDown(); expect(expandable.item(2).isFocused()).to.be.true(); Page.spotlightDown(); expect(expandable.item(2).isFocused()).to.be.true(); }); it('should select item when pressing select', function () { Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); }); it('should update value text on select', function () { Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightUp(); expect(expandable.valueText).to.equal('option1'); }); it('should not unselect item', function () { Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightSelect(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); }); it('should only allow one selected item', function () { Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightDown(); Page.spotlightSelect(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.false(); expect(expandable.item(1).$(expandable.selectedClass).isExisting()).to.be.true(); }); }); describe('pointer', function () { it('should open on title click when closed', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expectOpen(expandable); }); it('should close on title click when open', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.isOpen).to.be.true(); Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.isOpen).to.be.false(); }); it('should select item', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); }); it('should update value text', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.valueText).to.equal('option1'); }); it('should not unselect item', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); expandable.item(0).click(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); }); it('should only allow one selected item', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); expandable.item(1).click(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.false(); expect(expandable.item(1).$(expandable.selectedClass).isExisting()).to.be.true(); }); }); }); describe('multi select', function () { const expandable = Page.components.multiSelect; validateTitle(expandable, 'ExpandableList Multi Select'); it('should have correct none text', function () { expect(expandable.valueText).to.equal('Nothing Selected'); }); it('should be initially closed', function () { expectClosed(expandable); }); describe('5-way', function () { it('should open and spot first item on select', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); expectOpen(expandable); expect(expandable.item(0).isFocused()).to.be.true(); }); it('should select item when pressing select', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); }); it('should update value text on select', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightUp(); expect(expandable.valueText).to.equal('option1'); }); it('should allow unselecting item', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightSelect(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.false(); }); it('should allow multiple selected items', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightDown(); Page.spotlightSelect(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); expect(expandable.item(1).$(expandable.selectedClass).isExisting()).to.be.true(); }); it('should combine value text with multi-select', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightDown(); Page.spotlightSelect(); Page.spotlightUp(); Page.spotlightUp(); expect(expandable.valueText).to.equal('option1, option2'); }); }); describe('pointer', function () { it('should open on title click when closed', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expectOpen(expandable); }); it('should close on title click when open', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.isOpen).to.be.true(); Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.isOpen).to.be.false(); }); it('should select item', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); }); it('should update value text', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.valueText).to.equal('option1'); }); it('should allow unselecting item', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); expandable.item(0).click(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.false(); }); it('should allow multiple selected items', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); expandable.item(1).click(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); expect(expandable.item(1).$(expandable.selectedClass).isExisting()).to.be.true(); }); }); }); describe('single select', function () { const expandable = Page.components.singleSelect; validateTitle(expandable, 'ExpandableList Single Select'); it('should have correct none text', function () { expect(expandable.valueText).to.equal('Nothing Selected'); }); it('should be initially closed', function () { expectClosed(expandable); }); describe('5-way', function () { it('should open and spot first item on select', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); expectOpen(expandable); expect(expandable.item(0).isFocused()).to.be.true(); }); it('should select item when pressing select', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); }); it('should update value text on select', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightUp(); expect(expandable.valueText).to.equal('option1'); }); it('should allow unselecting item', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightSelect(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.false(); }); it('should reset none text if nothing selected', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightSelect(); Page.spotlightUp(); expect(expandable.valueText).to.equal('Nothing Selected'); }); it('should not allow multiple selected items', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightSelect(); Page.spotlightDown(); Page.spotlightSelect(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.false(); expect(expandable.item(1).$(expandable.selectedClass).isExisting()).to.be.true(); }); }); describe('pointer', function () { it('should open on title click when closed', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expectOpen(expandable); }); it('should close on title click when open', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.isOpen).to.be.true(); Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.isOpen).to.be.false(); }); it('should select item', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.true(); }); it('should update value text', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.valueText).to.equal('option1'); }); it('should unselect item', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); expandable.item(0).click(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.false(); }); it('should only allow one selected item', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expandable.item(0).click(); expandable.item(1).click(); expect(expandable.item(0).$(expandable.selectedClass).isExisting()).to.be.false(); expect(expandable.item(1).$(expandable.selectedClass).isExisting()).to.be.true(); }); }); }); describe('no lock bottom', function () { const expandable = Page.components.noLockBottom; validateTitle(expandable, 'ExpandableList No Lock Bottom'); describe('5-way', function () { it('should allow 5-way out when open', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); expect(expandable.isOpen).to.be.true(); Page.spotlightDown(); Page.spotlightDown(); expect(expandable.item(2).isFocused()).to.be.true(); Page.spotlightDown(); expect(Page.components.noAutoClose.title.isFocused()).to.be.true(); }); }); }); describe('no auto close', function () { const expandable = Page.components.noAutoClose; validateTitle(expandable, 'ExpandableList No Auto Close'); it('should be initially closed', function () { expectClosed(expandable); }); describe('5-way', function () { it('should open and spot first item on select', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); expectOpen(expandable); expect(expandable.item(0).isFocused()).to.be.true(); }); it('should not close when navigating up to title', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); Page.spotlightUp(); expectOpen(expandable); expect(expandable.title.isFocused()).to.be.true(); }); }); }); describe('default open', function () { const expandable = Page.components.defaultOpen; validateTitle(expandable, 'ExpandableList Default Open'); it('should be initially open', function () { expectOpen(expandable); }); describe('5-way', function () { it('should close on select', function () { expandable.focus(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightSelect(); }); expectClosed(expandable); expect(expandable.title.isFocused()).to.be.true(); }); it('should close when navigating up to title', function () { expandable.focus(); Page.spotlightDown(); Page.waitTransitionEnd(3000, undefined, () => { Page.spotlightUp(); }); expect(expandable.isOpen).to.be.false(); expect(expandable.chevron).to.equal('󯿭'); expect(expandable.title.isFocused()).to.be.true(); }); }); describe('pointer', function () { it('should close on title click', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.isOpen).to.be.false(); expect(expandable.chevron).to.equal('󯿭'); }); it('should open on title click when closed', function () { Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.isOpen).to.be.false(); Page.waitTransitionEnd(3000, undefined, () => { expandable.title.click(); }); expect(expandable.isOpen).to.be.true(); }); }); }); describe('disabled', function () { const expandable = Page.components.disabled; validateTitle(expandable, 'ExpandableList Disabled'); it('should be initially closed', function () { expect(expandable.isOpen).to.be.false(); expect(expandable.chevron).to.equal('󯿭'); }); describe('5-way', function () { it('should be spottable', function () { expandable.focus(); expect(expandable.title.isFocused()).to.be.true(); }); it('should stay closed on title selected', function () { expandable.focus(); Page.spotlightSelect(); // In this case, it should never fire, but we need to wait just in case. browser.pause(500); expect(expandable.isOpen).to.be.false(); expect(expandable.chevron).to.equal('󯿭'); }); }); describe('pointer', function () { it('should stay closed on title click', function () { expandable.title.click(); // In this case, it should never fire, but we need to wait just in case. browser.pause(500); expect(expandable.isOpen).to.be.false(); expect(expandable.chevron).to.equal('󯿭'); }); }); }); describe('general 5-way navigation', function () { it('should not stop 5-way down when closed', function () { Page.spotlightDown(); expect(Page.components.multiSelect.title.isFocused()).to.be.true(); }); }); describe('general pointer operation', function () { it('should not close other expandable when opening', function () { Page.waitTransitionEnd(3000, undefined, () => { Page.components.radioSelect.title.click(); }); Page.waitTransitionEnd(3000, undefined, () => { Page.components.multiSelect.title.click(); }); expect(Page.components.radioSelect.isOpen).to.be.true(); expect(Page.components.multiSelect.isOpen).to.be.true(); }); }); }); <reponame>Cross-Lab-Project/webviz // @flow // // Copyright (c) 2019-present, Cruise LLC // // This source code is licensed under the Apache License, Version 2.0, // found in the LICENSE file in the root directory of this source tree. // You may not use this file except in compliance with the License. import { renderHook, act } from "@testing-library/react-hooks"; import { mount } from "enzyme"; import * as React from "react"; import { type CameraState } from "regl-worldview"; import type { Interactive } from "webviz-core/src/panels/ThreeDimensionalViz/Interactions/types"; import { type GLTextMarker, getHighlightedIndices, SearchCameraHandler, } from "webviz-core/src/panels/ThreeDimensionalViz/SearchText"; import Transforms from "webviz-core/src/panels/ThreeDimensionalViz/Transforms"; import { TextHighlighter, ORANGE } from "webviz-core/src/panels/ThreeDimensionalViz/utils/searchTextUtils"; import type { TextMarker } from "webviz-core/src/types/Messages"; import { MARKER_MSG_TYPES } from "webviz-core/src/util/globalConstants"; jest.mock("lodash", () => { // Require the original module to not be mocked... const originalModule = jest.requireActual("lodash"); return { __esModule: true, // Use it when dealing with esModules ...originalModule, debounce: (fn) => fn, }; }); export const ROOT_FRAME_ID = "root_frame"; export const CHILD_FRAME_ID = "child_frame"; export const header = { frame_id: ROOT_FRAME_ID, stamp: { sec: 0, nsec: 0 }, }; function makeInteractive<T>(message: T): Interactive<T> { return { ...message, interactionData: { topic: "/topic", originalMessage: message } }; } const createMarker = (text: string): Interactive<TextMarker> | Interactive<GLTextMarker> => { return makeInteractive({ header, ns: "base", action: 0, scale: { x: 1, y: 1, z: 1 }, color: { r: 1, g: 1, b: 1, a: 1 }, id: "id", pose: { orientation: { x: 0, y: 0, z: 0, w: 1 }, position: { x: 1, y: 1, z: 1 }, }, type: MARKER_MSG_TYPES.TEXT_VIEW_FACING, text, }); }; const highlightText = ( text: Interactive<TextMarker>[], searchText: string, searchTextMatches: Interactive<GLTextMarker>[], setSearchTextMatches: (marker: Interactive<GLTextMarker>[]) => void = jest.fn(), selectedMatchIndex: number = 0 ) => new TextHighlighter(setSearchTextMatches).highlightText({ text, searchText, searchTextOpen: true, selectedMatchIndex, searchTextMatches, }); describe("<SearchText />", () => { describe("getHighlightedIndices", () => { expect(getHighlightedIndices("hello webviz", "e")).toEqual([1, 7]); expect(getHighlightedIndices("hello webviz", "hello ")).toEqual([0, 1, 2, 3, 4, 5]); it("is case insensitive", () => { expect(getHighlightedIndices("Car", "car")).toEqual([0, 1, 2]); expect(getHighlightedIndices("car", "Car")).toEqual([0, 1, 2]); }); }); describe("TextHighlighter", () => { it("updates the text markers to include highlighted indices", async () => { const setSearchTextMatches = jest.fn(); const glTextMarkers = highlightText([createMarker("hello")], "hello", [], setSearchTextMatches); expect(glTextMarkers.length).toEqual(1); expect(glTextMarkers[0].highlightedIndices).toEqual([0, 1, 2, 3, 4]); expect(setSearchTextMatches).toHaveBeenCalledWith(glTextMarkers); }); it("works with empy text markers", async () => { const setSearchTextMatches = jest.fn(); const glTextMarkers = highlightText([createMarker("")], "hello", [], setSearchTextMatches); expect(glTextMarkers.length).toEqual(1); expect(glTextMarkers[0].highlightedIndices).toEqual(undefined); expect(setSearchTextMatches).not.toHaveBeenCalled(); }); it("updates matches to empty", async () => { const setSearchTextMatches = jest.fn(); const marker = createMarker("hello"); const glTextMarkers = highlightText([marker], "bye", [(marker: any)], setSearchTextMatches); expect(glTextMarkers.length).toEqual(1); expect(glTextMarkers[0].highlightedIndices).toEqual(undefined); expect(setSearchTextMatches).toHaveBeenCalledWith([]); }); it("sets a custom highlight color to the correct index", async () => { const setSearchTextMatches = jest.fn(); const markers = [createMarker("hello webviz"), createMarker("hello cruies"), createMarker("hello future")]; const glTextMarkers = highlightText(markers, "hello", [], setSearchTextMatches, 2); expect(glTextMarkers.length).toEqual(3); expect(glTextMarkers[2].highlightColor).toEqual(ORANGE); }); it("does update the markers if search text has changed", async () => { const marker = createMarker("hello"); const originalMarkers: Interactive<TextMarker>[] = [marker]; let glTextMarkers = []; const Wrapper = ({ searchText }: { searchText: string }) => { const highlighter = React.useMemo(() => new TextHighlighter(jest.fn()), []); glTextMarkers = highlighter.highlightText({ text: originalMarkers, searchText, searchTextOpen: true, selectedMatchIndex: 0, searchTextMatches: [], }); return <span>{searchText}</span>; }; const root = await mount(<Wrapper searchText={"hello"} />); root.update(); const originalGlText = glTextMarkers; root.setProps({ searchText: "bye" }); expect(glTextMarkers).not.toEqual(originalGlText); root.unmount(); }); it("does not update the markers if nothing has changed", async () => { const marker = createMarker("hello"); const originalMarkers: Interactive<TextMarker>[] = [marker]; let glTextMarkers = []; const Wrapper = ({ randomNum }: { randomNum: number }) => { const highlighter = React.useMemo(() => new TextHighlighter(jest.fn()), []); glTextMarkers = highlighter.highlightText({ text: originalMarkers, searchText: "hello", searchTextOpen: true, selectedMatchIndex: 0, searchTextMatches: [], }); return <span>{randomNum}</span>; }; const root = await mount(<Wrapper randomNum={1} />); root.update(); const originalGlText = glTextMarkers; root.setProps({ randomNum: 2 }); expect(glTextMarkers).toEqual(originalGlText); root.unmount(); }); }); describe("useCurrentMatchPosition", () => { const p = (x: number = 0, y = x, z = x) => ({ x, y, z }); const q = (x = 0, y = 0, z = 0, w = 0) => ({ x, y, z, w }); const baseCameraState = { target: [0, 0, 0], targetOffset: [0, 0, 0], targetOrientation: [0, 0, 0, 1], }; const useWrapper = ( initialCameraState?: CameraState = baseCameraState, initialMatch?: GLTextMarker = createMarker("text") ) => { const pose = { position: p(30, 60, 90), orientation: q(0, 0, 0, 1) }; const transforms = new Transforms([{ childFrame: CHILD_FRAME_ID, parentFrame: ROOT_FRAME_ID, pose }]); const [cameraState, updateCameraState] = React.useState(initialCameraState); const [currentMatch, updateCurrentMatch] = React.useState<GLTextMarker>(initialMatch); const onCameraStateChange = React.useCallback(jest.fn(updateCameraState), []); const cameraHandler = React.useMemo(() => new SearchCameraHandler(), []); cameraHandler.focusOnSearch(cameraState, onCameraStateChange, ROOT_FRAME_ID, transforms, true, currentMatch); return { cameraState, updateCurrentMatch, onCameraStateChange }; }; it("updates camera state with a new target offset based on the root transform", () => { const { result } = renderHook(() => useWrapper(baseCameraState)); expect(result.current.cameraState).toEqual({ ...baseCameraState, targetOffset: [1, 1, 1], }); }); it("should take into account target heading in target offset", () => { const initialCameraState = { ...baseCameraState, targetOrientation: [0.0, 0.0, -0.8, 0.6], }; const { result } = renderHook(() => useWrapper(initialCameraState)); const [x, y, z] = result.current.cameraState.targetOffset; expect(x).toBeCloseTo(-1.24); expect(y).toBeCloseTo(0.68); expect(z).toEqual(1); }); it("should update camera state if there are new matches", () => { const { result } = renderHook(() => useWrapper(baseCameraState)); act(() => { result.current.updateCurrentMatch({ ...createMarker("text"), pose: { position: p(2, 2, 2), orientation: q(0, 0, 0, 1), }, }); }); expect(result.current.cameraState).toEqual({ ...baseCameraState, targetOffset: [2, 2, 2], }); act(() => { result.current.updateCurrentMatch({ ...createMarker("text"), pose: { position: p(3, 3, 3), orientation: q(0, 0, 0, 1), }, }); }); expect(result.current.cameraState).toEqual({ ...baseCameraState, targetOffset: [3, 3, 3], }); }); it("should not fire onCameraStateChange if cameraState is updated independently", () => { const { result } = renderHook(() => useWrapper(baseCameraState)); expect(result.current.onCameraStateChange).toHaveBeenCalledTimes(1); act(() => { result.current.onCameraStateChange({ targetOffset: [5, 5, 5], }); }); expect(result.current.onCameraStateChange).toHaveBeenCalledTimes(2); }); }); }); define([], function () { // # OperatorFactory.js // Takes and expression and wraps it with an operator. function MOperator(regexp) { this.regexp = regexp; } // Overloaded by the factory MOperator.prototype.expression = function (_input, _pos, exp, operators) { }; function operatorFactory(regexp, expression) { var out = new MOperator(regexp); out.expression = expression; return out; } return operatorFactory; });function hide_menu() { $('.menu-background').hide(); $('.sub-menu').hide(); $('.menu-list > li > a').removeClass('active') } $(document).ready(function() { $('.menu-background').on('click', function() { hide_menu() }); $('ul.menu-list > li > a').on('click', function() { var selector = this.attributes['data-toggle'].nodeValue; if ($(selector).is(":visible")) { hide_menu(); } else { $('.menu-background').show(); $('.sub-menu').hide(); $('.menu-list > li > a').removeClass('active') $(selector).show(); $(this).addClass('active'); } }); $('.scroll-up').click(function(){ $('html, body').animate({scrollTop:0}, 800); }); $('.scroll-down').click(function(){ var $elem = $('body'); $('html, body').animate({scrollTop: $elem.height()}, 800); }); // TODO: enabling it with failing sockets crushes JS on page // var ws4redis = WS4Redis({ // uri: websocket_uri + 'pm?subscribe-user', // receive_message: receiveMessage, // heartbeat_msg: 'heartbeat' //}); // receive a message though the websocket from the server function receiveMessage(msg) { if (msg > last_read_pm_id) { $('.new_messages').addClass('active') //alert(msg); } } });export const theme = { colors: { primary: 'rgb(61, 72, 90)', secondary: 'rgba(61, 72, 90, 0.8)', accent: '#ffc95e', // accent: '#2db34a', white: 'white', background: 'white', primaryDark: 'rgba(255, 255, 255, 0.5)' }, fontFamilies: { regular: '"Poppins", sans-serif', headings: '"Merienda", cursive', }, fontSizes: { small: '.8rem', base: '1rem', medium: '1.1rem', large: '1.2rem', xLarge: '1.3rem', xxLarge: '1.4px', }, media: { xsmall: `(min-width: 22em)`, small: `(min-width: 48em)`, medium: `(min-width: 64em)`, large: `(min-width: 85.375em)`, xlarge: `(min-width: 120em)`, xxlarge: `(min-width: 160em)`, }, transitions: { default: '0.2s ease-in-out', }, }const Emitter = require('./emitter'); const Constants = require('./constants'); const encoderWorkerSrc = require('./../vendor/opus-recorder/src/encoderWorker.inline'); /** * Encoder interface. Encoder is used by <code>OutgoingMessage</code> to encode data recorder with <code>Recorder</code>. * Custom Encoder implementation should call method <code>ondata</code> once encoded data portion is ready * @interface Encoder **/ class Encoder extends Emitter { constructor() { super(); let blob; try { blob = new Blob([encoderWorkerSrc], {type: 'application/javascript'}); } catch (e) { let blobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder; blob = new blobBuilder(); blob.append(encoderWorkerSrc); blob = blob.getBlob(); } this.encoderWorker = new window.Worker(URL.createObjectURL(blob)); this.encoderWorker.addEventListener('message', (e) => { if (!e.data || e.data.type !== 'opus' || !e.data.data) { return; } this.emit(Constants.EVENT_DATA_ENCODED, e.data.data); this.ondata(e.data.data); }); } /** * Emit encoded data portion to let <code>OutgoingMessage</code> instance get encoded data ready to be sent into channel * * @method Encoder#ondata * @param {Uint8Array | array} data encoded opus data portion * **/ ondata(data) {} postMessage(message) { this.encoderWorker.postMessage(JSON.parse(JSON.stringify(message))); } /** * @param {array} data array of 1 or 2 buffers for each PCM channel * **/ encode(data) { this.encoderWorker.postMessage({ command: "encode", buffers: data }); } } module.exports = Encoder;const mutation = { }; export default mutation; import React, { Component } from 'react'; // import _ from 'lodash'; import { observer, inject } from 'mobx-react'; import DevTools from 'mobx-react-devtools'; import { useStrict } from 'mobx'; import { Link } from 'react-router-dom'; useStrict(true); @inject('store') @observer class App extends Component { render() { console.log(this.props); return ( <div> <h1>React Router Tutorial</h1> <ul> <li> <Link to='/about'>About</Link> </li> <li> <Link to='/inbox'>inbox</Link> </li> </ul> {this.props.children} <DevTools /> </div> ); } } export default App; <reponame>189569400/II-RPA<gh_stars>10-100 var html = "" var addLiuchengItem = {}; var liuchengItem = ""; var tipsBox; function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { var tipsBoxDemo = '<div class="liucheng-item-tips">'; var thisTipsBox = $(ev.target).parent().find(".liucheng-item-tips").length > 0 ? tipsBoxDemo + $(ev.target).parent().find(".liucheng-item-tips").eq(0).html() + '</div>' : ''; tipsBox = thisTipsBox; html = $(ev.target).parent().find(".child-menu-operate").html() var thisParentLiIndex = $(ev.target).parents(".child-menu").parent("li").index(); var thisVal = $(ev.target).parent().children(".child-menu-title").text(); addLiuchengItem.uuid = new Date().getTime(); //获取时间戳作为uuid addLiuchengItem.thisParentLiIndex = thisParentLiIndex; addLiuchengItem.newNodeMainClass = "menu-item-" + (thisParentLiIndex + 1); addLiuchengItem.newNodeLeftIconClass = $(ev.target).find(".child-menu-title").find("i").className(); liuchengItem = '<li id="' + addLiuchengItem.uuid + '" class="' + addLiuchengItem.newNodeMainClass + ' dads-children clear"><i class="' + addLiuchengItem.newNodeLeftIconClass + ' menu-icon"></i><span class="title" style="line-height: 32px;">'; liuchengItem += thisVal; liuchengItem += '</span><div class="liucheng-utils clear">'; liuchengItem += '<i class="liucheng-icon-xiugai"></i>'; liuchengItem += '<i class="liucheng-icon-delete"></i>'; liuchengItem += '</div><span class="liucheng-operate-data"></span>'; // liuchengItem += '<div class="liucheng-item-tips">'; liuchengItem += tipsBox; liuchengItem += '</li>'; addLiuchengItem.newNodeItem = liuchengItem; // console.log(ev.target.innerText); // // ev.dataTransfer.setData("Text", ev.target.id); // // $(".liucheng-list").append('<li id="1512011404372" class="menu-item-1 dads-children clear"><i class="menu-icon-1 dad-draggable-area"></i><span class="title">打开网页</span></li>'); // $('.liucheng-list').dad({ // draggable: '.menu-icon-1' // }); // $(".first-tips-box").hide(); // if ($(".liucheng-box").eq(0).css("display") == "none") { // $(".liucheng-box").show(); // $('.liucheng-list').css('height', '180px'); // } } function drop(ev) { let txt = "#"; txt += ev.target.id; $(txt).parent().find('ul').eq(0).append(addLiuchengItem.newNodeItem); $("#" + addLiuchengItem.uuid + "> .liucheng-operate-data").html(html) console.log(addLiuchengItem.uuid) html = "" addLiuchengItem = {}; // ev.preventDefault(); // var data = ev.dataTransfer.getData("Text"); // ev.target.appendChild(document.getElementById(data)); $('.liucheng-list').dad({ draggable: '.menu-icon' }); }"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var temp = function FileTwoTone(primaryColor, secondaryColor) { return { name: 'file', theme: 'twotone', nameWithTheme: 'file-twotone', tag: 'svg', attrs: { xmlns: 'http://www.w3.org/2000/svg', class: 'icon', viewBox: '0 0 1024 1024' }, children: [ { tag: 'path', attrs: { fill: secondaryColor, d: 'M534 352V136H232v752h560V394H576c-23.2 0-42-18.8-42-42z' }, children: [] }, { tag: 'path', attrs: { d: 'M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM602 137.8L790.2 326H602V137.8zM792 888H232V136h302v216c0 23.2 18.8 42 42 42h216v494z', fill: primaryColor }, children: [] } ] }; }; temp.nameWithTheme = 'file-twotone'; var FileTwoTone = temp; exports.default = FileTwoTone; const router = require('express').Router() const images = require('./images') // Main router router.route('/') .get((req, res) => { res.json({ message: ['/', 'Main router!'] }) }) router.route('/hello') .get((req, res) => { res.json({ message: ['/hello', 'Hello Express!'] }) }) // Load sub-router router.use('/images', images) module.exports = router <gh_stars>1-10 import { html, defineElement } from '@webtides/element-js'; import FormField, { FormFieldEvents } from '@webtides/form-field'; import { unsafeHTML } from 'lit-html/directives/unsafe-html'; import { classMap } from 'lit-html/directives/class-map'; import style from './checkbox-field.css'; export default class CheckboxField extends FormField { uuid = Math.random().toString(36).substr(2, 5); constructor(options) { super({ shadowRender: false, styles: [style], ...options }); } properties() { return { ...super.properties(), checked: false, }; } hooks() { return { connected: () => { this.setAttribute('checked', this.checked === true ? 'true' : 'false'); }, }; } watch() { return { ...super.watch(), checked: (checked) => { this.setAttribute('checked', checked ? 'true' : 'false'); this.dispatch(FormFieldEvents.INPUT_CHANGE, this.$refs.input.value, true); }, }; } events() { return { ...super.events(), input: { change: () => { this.checked = this.$refs.input.checked; }, }, }; } fieldTemplate() { const classes = { 'is-checked': !!this.checked }; return html` <label for="checkbox-${this.uuid}"> <input ref="input" type="checkbox" id="checkbox-${this.uuid}" aria-describedby="checkbox-${this.uuid}" value="${this.value}" name="${this.name}" ?disabled="${this.disabled}" ?checked="${this.checked}" ?required="${this.required}" /> <div class="checked-indicator ${classMap(classes)}">${this.selectedIndicatorTemplate()}</div> <div class="label">${unsafeHTML(this.label)}</div> </label> `; } selectedIndicatorTemplate() { return html` <div class="checked">✓</div> `; } } export function define() { defineElement('checkbox-field', CheckboxField); } /** * This particular test makes it impossible to impose a limit of one * expectation to each case. So we need to deal with multiple expectations. * * Maybe we could make this more generic, but really, a case should only ever * have one expectation, so this is, at the moment, a huge hack. * * @param DOM element * The element currently being tested. * @param string caseID * The test's ID for a Case. Sometimes a test will produce sub-types of cases * that will be identified by a unique string. * * @return string|null * The expected result: 'pass', 'fail', 'notApplicable' * * @hereDeDragons. */ quail.components.resolveExpectation = function(element, caseID) { var $scope = $(element).closest('.quail-test'); var expected = $scope.data('expected'); var result; // If no caseID is supplied, assume that the expected data attribute could // contain a simple, singular expectation. if (!caseID) { result = $scope.data('expected'); } var expectations = typeof expected === 'string' && expected.split('|'); // This might be a single case ID expectation. if (caseID && expectations.length === 0 && expected.indexOf(':') > -1) { expectations = [expected]; } if (expectations.length > 0 && element.nodeType === 1) { var condition, $el; // Split apart the compound expectations. for (var i = 0, il = expectations.length; i < il; ++i) { condition = expectations[i].split(':'); // If a caseID is supplied, assume the expect targets them. if (caseID) { if (condition[0] === caseID) { if (!condition[1] || condition[1] === 'ignore') { return; } else { // Retrieve the expectation for this element. result = condition[1]; } } } // Try to use the condition zero element as a selector. else { $el = $(condition[0], $scope); if ($el.length === 1 && element === $el.get(0)) { if (!condition[1] || condition[1] === 'ignore') { return; } else { // Retrieve the expectation for this element. result = condition[1]; } } } } } // Otherwise the expectation is given as a simple value. return result; }; const b = 1; const foo1 = b; export { foo1 as foo }; <gh_stars>0 require(['$', 'bootstrap', 'bootstrap-material', 'bootstrap-material-ripples'], ($)=> $.material.init()); require(['$'], ($)=> { $(()=> { $('.lang-hbs').each((i, el)=> { require(['handlebars'], (handlebars)=> { const data = window.data || $(el).attr('data') || {}; const src = $(el).text(); const template = handlebars.compile(src); $(el).text(template(data)); }); }); $('.lang-js-run').each((i, el)=> { require(['babel'], (babel)=> { babel.run(`require(["$", "_"], ($, _)=> { ${$(el).text()} });`); }); }); $('.lang-js-run-d3').each((i, el)=> { require(['babel'], (babel)=> { babel.run(`require(["$", "_", "d3"], ($, _, d3)=> { ${$(el).text()} });`); }); }); }); }); //ga // if( '{{{package.homepage}\}\}' === 'http://' + window.location.hostname ) { // var _gaq = _gaq || []; // _gaq.push(['_setaccount', 'ua-27493298-1']); // _gaq.push(['_trackpageview']); // (function() { // var ga = document.createelement('script'); ga.type = 'text/javascript'; ga.async = true; // ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; // var s = document.getelementsbytagname('script')[0]; s.parentnode.insertbefore(ga, s); // })(); // } ������������"���3���D���U���f���w�������������������������������������!��2��C��T��e��v���������������������������� ��1��B��S��d��u������������������������������0��A��R��c��t�������������������������� ����/��@��Q��b��s�������������������������� ����.��?��P��a��r�������������������������� ����-��>��O��`��q�������������������������� ����,��=��N��_��p�������������������������� ����+��<��M��^��o�������������������� ��! ��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,���,���,���,���,���,���,��-��(-��?-��V-��m-���-���-���-���-���-���-��.��%.��<.��S.��j.���.���.���.���.���.���.�� /��"/��9/��P/��g/��~/���/���/���/���/���/��0��0��60��M0��d0��{0���0���0���0���0���0��1��1��31��J1��a1��x1���1���1���1���1���1��2��2��02��G2��^2��u2���2���2���2���2���2���2��3��-3��D3��[3��r3���3���3���3���3���3���3��4��*4��A4��X4��o4���4���4���4���4���4���4��5��'5��>5��U5��l5���5���5���5���5���5���5�� 6��$6��;6��R6��i6���6���6���6���6���6���6�� 7��!7��87��O7��f7��}7���7���7���7���7���7��8��8��58��L8��c8��z8���8���8���8���8���8��9��9��29��I9��`9��w9���9���9���9���9���9��:��:��/:��F:��]:��t:���:���:���:���:���:���:��;��,;��C;��Z;��q;���;���;���;���;���;���;��<��)<��@<��W<��n<���<���<���<���<���<���<��=��&=��==��T=��k=���=���=���=���=���=���=�� >��#>��:>��Q>��h>��>���>���>���>���>���>�� ?�� ?��7?��N?��e?��|?���?���?���?���?���?��@��@��4@��K@��b@��y@���@���@���@���@���@��A��A��1A��HA��_A��vA���A���A���A���A���A���B��B��.B��EB��\B��sB���B���B���B���B���B���B��C��+C��BC��YC��pC���C���C���C���C���C���C��D��(D��?D��VD��mD���D���D���D���D���D���D��E��%E��<E��SE��jE���E���E���E���E���E���E�� F��"F��9F��PF��gF��~F���F���F���F���F���F��G��G��6G��MG��dG��{G���G���G���G���G���G��H��H��3H��JH��aH��xH���H���H���H���H���H��I��I��0I��GI��^I��uI���I���I���I���I���I���I��J��-J��DJ��[J��rJ���J���J���J���J���J���J��K��*K��AK��XK��oK���K���K���K���K���K���K��L��'L��>L��UL��lL���L���L���L���L���L���L�� M��$M��;M��RM��iM���M���M���M���M���M���M�� N��!N��8N��ON��fN��}N���N���N���N���N���N��O��O��5O��LO��cO��zO���O���O���O���O���O��P��P��2P��IP��`P��wP���P���P���P���P���P��Q��Q��/Q��FQ��]Q��tQ���Q���Q���Q���Q���Q���Q��R��,R��CR��ZR��qR���R���R���R���R���R���R��S��)S��@S��WS��nS���S���S���S���S���S���S��T��&T��=T��TT��kT���T���T���T���T���T���T�� U��#U��:U��QU��hU��U���U���U���U���U���U�� V�� V��7V��NV��eV��|V���V���V���V���V������StarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascriptStarcoderdataJavascript������������� ����� � ��������p1������� �� ��� ����������@���������� ��������������������������� ������ ����������������������������������� �������"����������������������������������� ��������������3�������������@��������������@��������������@������������������������������%���,���1���8���?���G���O���V���]���e���l���t���|����������������������������������������������������������������������������������$��,��3��:��@��G��N��V��^��e��l��t��{������������������������������������������������������� ��������'��/��6��>��E��M��T��Z��b��i��q��x��������������������������������������������������������� ������%��,��4��;��C��K��R��Z��b��j��q��y������������������������������������������������������� ������ ��(��-��4��<��C��J��R��Y��a��i��p��w�����������������������������������������������������������������'��.��5��<��D��L��T��\��d��l��s��{���������������������������������������������������������� ��������&��-��5��=��D��L��T��\��c��j��r��z����������������������������������������������������������������$��,��3��;��B��I��Q��X��`��h��p��w��~����������������������������������������������������������������$��+��2��:��B��J��Q��W��^��f��n��u��}����������������������������������������������������� �� �� �� �� ��% ��, ��3 ��: ��B ��J ��Q ��Y ��` ��g ��m ��u ��} ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� �� �� �� �� �� ��( ��/ ��6 ��> ��E ��L ��S ��Z ��b ��i ��p ��v ��~ ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� �� �� �� �� ��$ ��+ ��3 ��; ��C ��J ��R ��Y ��` ��g ��n ��u ��| ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� �� �� �� �� �� ��& ��. ��5 ��< ��C ��K ��S ��Z ��b ��j ��p ��x ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� �� �� �� �� ��# ��* ��0 ��7 ��> ��E ��K ��R ��Y ��_ ��g ��n ��v ��~ ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ��� ���� ������#��+��2��:��A��H��P��V��^��f��m��t��|�������������������������������������������������������������$��,��4��<��C��K��S��[��b��i��p��w��~������������������������������������������������������� ������"��*��2��:��A��H��O��V��^��f��m��u��|���������������������116836645505095133499913698087144763995673494555546366954219898149649921933886650865749030747190446265884595125109511201361329440621139214010905155119961491006632219297088130594165971467159670543209596191582386223875313676827722484578177864245411286903012319262541949711243289875565809772358916019618555356473815452838386175410729149012305755151546251902055426125810582171146013413942395136279401931886951661781722776017939328162479813595194722128913034992132035775246749778595213246962172578558001353823667601999810372815735711371794587505929104835351727742497281151745434759510171540339718874856614811310235487206371926189198020625921013171823787648364100421201663035114335154202745446959641804802123194691459520163409671746923041361041141833451282592239080161251454963071714390616876022102723931104413422161571134270715354791585376616262349663705714233639147330901031730392890721358001710081394173194041776551217335934134330731097403120887551505776715578350192137571655639218369273435641698662196662751940233752499714571951190110752727676128319172406594164681042409179937191747894025738342782861124918345938998184128541945446471234242436623167363041267651289259561320448786244474217495582094274260211806028248331628122652797976105527613586954270696214749138879655724870658253241794778312177366802779211823336133969995591004771398558476411179313017223051161787921952280317601474177206871053204105904145297863107233991535214333096275943816466534159925716050834420904133294017618699319606216986067888604688960074218557998237578499217183519737054593918543032955493326076133706453623146370191726023064995141027614213749472142055727618199980416517817722182190363163899194186925679232112955421877664188818681231785322709481911701511579954384146811682702172164779536023225824346737214791687508978280116448132656114295108559769211224316826770191364619245298543001967405441653348690050571002893113317901183775036502179455858760775056060697106303145121924677756575556162539711863698843181503743947700560996559810506612152499881253258014184472265317666311361912737711140316569428309706656399478438369842328216876849139831361847509162461661319961433143150243971678405248233481141848756254987805275410128180917014188248869832660499299649861634369420461771939317416260797142964531352141711768145838693033645041264991954308894427149394647145312201001301744578231486092953278719272271111398412011602144795369471849877084274934715596726117591447401416674489848232139178591019379612875170559312186161875874328146250395472043146661641123152810279302101074151668113935022562059046130649541940951774827582918425157915084331759804608510650737678881912224002468634215567519449038979509836601716371281170695664939611683932535664456320779455982254505137932312762255672613719382949378359535006511605229157794210083872526490317188461189539341462759376217332033785492478143891661997540140081781137561511310275883044519101816932722088401321513022589797724765019363674141018721139180419152859683664417494086517061914585971332241858306311194663810972851807728854066255808757190563791644649918975212723564199295658446901389670197845481158731051702347297465591151489464314188909158346204367702185824491862938082193315949970157499609926061887458515547113162575527045322527232810554014930295087669991294351618116119931537667916956333409183416411694967624511513519300380427219227419154085047348194221152233048976329116699925784245765619655850382374098811530158648192023327114941541861658617342983181500548814942139470911297776711556015116902159344693792342711980017101625254497149130612809003110160567895704120058046116805166191271160231611831101698874217327656354244612276026427816629121931608225831690719034875149163194855653184871313434113156472371544579010268494108595621748202611371233180566211462404514252620184420748712427671683983995051237573427833291902408214778993133148398953782933557722887608929205136116911290016311772927246164218167603188935921551425349365178088109379121884325063995129262200468349491028955131008572320693839509774393034454684455205518015642166496293630027971422217936943112663115718168129344551452899518811563912094214519697157864801694287015253127133011511720799212456017732326842051161113551923280295203611468541490398361142917296854883150382154483313864123����������������������2��<���?���A���A���C���F���F���Q��_U��og��Fi���k���m��9�������:���I���<��(�����������;�������=��h������������ �+"�h"�?$��%��&�>-�j1��2�wU�s[��^�;d�������2��֫�������������������7��&��4�����X�����z���M��W��a��a�7b�c��c��j��u����������n����i� P�~R��U��^��`�qd�h���a�����N��˘����f��x��E�����h�bn�<o��p�M����������K��M��������L��8����|��������2��Y��Z�������O�2��P�R�7U�@]��]��h�j��j�l�Jn��q��w��x���������������������������%��N�����5A�C�E�|`��`��e��s�v{�چ� ��b��d �r+�~,�p1�4��4�<5��5�[�/v��y�/��ێ� ��[������4 �&7 �; ��A �O �t ��x ��� ��� �3� �ڱ �o� �)� ��� �F� �e� �!� ��� �� �V� �}� �� ��� ��� �� �� �� �$ ��' �s� �s� �� �� �Т �� �� ��� �� �%� ��� ��� ��� ��� � �� �O �4 �� �� ��! �F5 �d6 ��: ��; �bM �] �r ��u �� �� �b� �~� ��� �)� �f� �*� �� �.� �h� �ʼ �� �F� ��� �7� �H� ��� �(� �M� ��� �� �E� �:� �+� �~- ��/ �: �#= ��> �"@ �TG �KI �r �u �ty ��� �S� ��� �,� ��� ��� ��� �,� ��� ��� ��� ��� �k� ���q �D�I!�'"��&��'�,�^@�TN�QP�Y������� ��>�������$�����9�W;�hQ��T�3Y��`��s�y��|�~��>����(��Ӭ�ƭ�ص�W��G��u��$�����_��������������]�C�Z��"��#�C�9I��L��N�@P��_�Yc��e�sf��o��r�hw�}��}�������x��i����������p��}�� �����˴� ��k��������`��������g��r�����$���z���Y7�D�yH��I�O��P�>W�Qc��e��i��j�u}����b��e��a��"��8��G�����*����?��d�����������������������������������;��������?�������������!�<��:��ڷ� �����H����� �"�W$��&��0�n3��B��D�F��P��R�V��]�?v�(y�\���������{��հ���Q�������j��������1#��+�K@�(Q���������L��ۓ�Z�����C��x��;��%��ɾ�������.��g�� �7���� ��$�'&��'��)�R+�-/��6��;����d�����f��}�����r�����D��?���������I��!����'��+��1��7�M;�h?�'I�n\�Fe�[v��y�-|� �������������ؕ���� ��}�������z�������I�����R��������A��P��������y ��^�7`��f��m�9q�}�z��x���������������n�����C�m�`V��~�)�����J��s��������7��������������������<reponame>trendzsoft/MUTS<filename>client/app/components/machine/machine.controller.js class MachineController { constructor() { this.name = 'machine'; } } export default MachineController; <gh_stars>0 import React from "react"; import store from "../store"; import { setTypingValue, sendMessage } from "../actions"; import "./MessageInput.css"; const MessageInput = ({ value }) => { const handleChange = (e) => { store.dispatch(setTypingValue(e.target.value)); }; const state = store.getState(); const handleSubmit = (e) => { e.preventDefault(); const { typing, activeUserId } = state; store.dispatch(sendMessage(typing, activeUserId)); }; return ( <form className="Message" onSubmit={handleSubmit}> <input className="Message__input" onChange={handleChange} value={value} placeholder="write a message" /> </form> ); }; export default MessageInput; export default { zh: { msg: { message: "消息", contact: "联系人", me: "我", moments: "朋友圈", cancel: "取消", search: "搜索", settings: "设置", noData: "暂无数据", noMessage: "暂时没有新消息", back: "返回", send: "发送", newFriends: "新的朋友", lang: '语言', zh: '中文', en: '英文', nearBy: '附近朋友', login: '登录', logout: '退出', register: '注册', username: '用户名', password: '密码', noAccount: '没有账号?', hasAccount: '已有账号?', loginNow: '立即登录', registerNow: '立即注册', unameMsg: '请输入用户名', passwdMsg: '请输入密码', firstCharMsg: '字母开头', usernameLengthMsg: '用户名长度在5-16', usernameMsg: '只能包含字母数字下划线', passwordLengthMsg: '密码长度在6-18', confirmPassword: '<PASSWORD>', confirmPasswordMsg: '请再次输入密码', twicePasswdNotSame: '两次密码不一致', enterWith20: '输入20字以内', enterWith150: '输入150字以内', confirmLogout: '确定退出登录?', userNotExist: '用户不存在', cannotAddYourself: '自己不能添加自己', tips: '提示', add: '添加', confirm: '确定', reqSuccess: '请求已发送', addSuccess: '添加成功', friendReq: '好友请求', refuse: '拒绝', accept: '同意', friendDetails: '好友详情', setRemark: '设置备注', region: '地区', remark: '备注', nickname: '昵称', sendMsg: '发送消息', deleteFriend: '删除', hasRefused: '已拒绝', hasAdded: '已添加', hasDeleted: '已删除', confirmDeleteFriend: '确定删除好友', lostConnect: '正在尝试重新连接...', accountLoginOthPlace: '账号在其它地方登录', gender: '性别', empty: '空', male: '男', female: '女', whatUp: '签名', realName: '姓名', regSuccess: '注册成功', pullRefresh: '下拉刷新', releaseRefresh: '释放刷新', loading: '加载中...', loadSuccess: '加载成功', loadFail: '加载失败', networkErr: '网络异常', profiles: '个人信息', profilePhoto: '头像', choosePhoto: '选择照片', upload: '上传', readFail: '读取图片失败', comingSoon: '敬请期待', photoTooLarge: '图片太大', clearLocation: '清除位置信息' } }, en: { msg: { message: "Messages", contact: "Contacts", me: "Me", moments: "Moments", cancel: "cancel", search: "search", settings: "Settings", noData: "No data", noMessage: "No message", back: "back", send: "send", newFriends: "New Friends", lang: 'Language', zh: 'Chinese', en: 'English', nearBy: 'People NearBy', login: 'Login', register: 'Register', logout: 'Log out', username: 'Username', password: 'Password', noAccount: 'No account?', hasAccount: 'Existing Account?', loginNow: 'Login now', registerNow: 'Register now', unameMsg: 'Please enter username', passwdMsg: 'Please enter password', firstCharMsg: 'The first character should be a letter', usernameLengthMsg: 'The username length of 5 to 16', usernameMsg: 'Only alphanumeric underline', passwordLengthMsg: 'The password length of 6 to 18', twicePasswdNotSame: 'Twice passwords were not same', enterWith20: 'Enter within 20 words', enterWith150: 'Enter within 150 words', confirmPassword: '<PASSWORD>', confirmPasswordMsg: 'Please re-enter password', confirmLogout: 'Do you want to log out?', userNotExist: 'User not exist', cannotAddYourself: 'Yourself can not add yourself', tips: 'tips', add: 'Add', confirm: 'confirm', reqSuccess: 'Request has sent', addSuccess: 'Add success', friendReq: 'Friends requests', refuse: 'Refuse', accept: 'Accept', friendDetails: 'Friend details', setRemark: 'Set remark', region: 'Region', remark: 'remark', nickname: 'nickname', sendMsg: 'Send message', deleteFriend: 'Delete', hasRefused: 'Has refused', hasAdded: 'Has added', hasDeleted: 'Has deleted', confirmDeleteFriend: 'Do you want to delete friend', lostConnect: 'Trying to reconnect...', accountLoginOthPlace: 'The account was logged in elsewhere', gender: 'Gender', empty: 'Empty', male: 'Male', female: 'Female', whatUp: 'What’s up', realName: '<NAME>', regSuccess: 'Register success', pullRefresh: 'Pull-down refresh', releaseRefresh: 'Release refresh', loading: 'loading...', loadSuccess: 'Load success', loadFail: 'Load fail', networkErr: 'Network anomaly', profiles: 'Profiles', profilePhoto: 'Profile photo', choosePhoto: 'Choose photo', upload: 'Upload', readFail: 'Read file fail', comingSoon: 'Coming soon', photoTooLarge: 'Photo was too large', clearLocation: 'Clear location' } } } // mine.js const App = getApp() Page({ /** * 页面的初始数据 */ data: { hidePopup:true, phoneNumber:'请输入', userInfo: {}, items: [ { icon: '../../images/mine/Fingerprint.png', text: '每日打卡', path: '/pages/signin/sign-in' }, { icon: '../../images/mine/ok.png', text: '待确认课程', path: '/pages/shop-cart/index' }, { icon: '../../images/mine/order.png', text: '已预订课程', path: '/pages/order-list/index' }, { icon: '../../images/mine/phone.png', text: '我的电话', path: '' }, { icon: '../../images/mine/support.png', text: '联系客服', path: '18629027590', }, ], settings: [ { icon: '../../images/mine/About-Us.png', text: '关于我们', path: '/pages/articles-detail/index?id=742' }, ] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; wx.getStorage({ key: 'phoneNumber', success: function(res) { that.setData({ phoneNumber: res.data }) }, }); this.getUserInfo(); console.log(this.data.userinfo); wx.getWeRunData({ success(res) { console.log(res); } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { return { title: "李大力的健身房", path:"/pages/home/home" } }, //获取用户信息 getUserInfo:function() { var userInfo = App.globalData.userInfo var that = this; if (userInfo) { that.setData({ userInfo: userInfo }) return } userInfo = App.getUserInfo(); console.log(userInfo); that.setData({ userInfo: userInfo }) }, bindtap(e) { }, navigateTo:function(e) { const index = e.currentTarget.dataset.index; const path = e.currentTarget.dataset.path; switch (index) { case 3: this.showPopupTap(); break; case 4: wx.makePhoneCall({ phoneNumber: path }) break; default: console.log(path); // console.log(typeof path); wx.navigateTo({ url: path }); }; }, closePopupTap: function () { this.setData({ hidePopup: true }) }, showPopupTap: function () { this.setData({ hidePopup: false }) }, formSubmit:function(e){ console.log(e); const phoneNumber = e.detail.value.phoneNumber; if (phoneNumber.length != 11 && phoneNumber.length != 8){ wx.showModal({ title: '提示', content: '电话号码不正确,请确认后重新输入。', }); return; } this.setData({ phoneNumber: e.detail.value.phoneNumber }); wx.setStorageSync({ key: "phoneNumber", data: phoneNumber }); this.closePopupTap(); }, }) /* import __config from '../../etc/config' const App = getApp() Page({ data: { userInfo: {}, items: [ { icon: '../../assets/images/iconfont-order.png', text: '我的订单', path: '/pages/order/list/index' }, { icon: '../../assets/images/iconfont-addr.png', text: '收货地址', path: '/pages/address/list/index' }, { icon: '../../assets/images/iconfont-kefu.png', text: '联系客服', path: '400-0728-156', }, { icon: '../../assets/images/iconfont-help.png', text: '常见问题', path: '/pages/help/list/index', }, ], settings: [ { icon: '../../assets/images/iconfont-clear.png', text: '清除缓存', path: '0.0KB' }, { icon: '../../assets/images/iconfont-about.png', text: '关于我们', path: '/pages/about/index' }, ] }, onLoad() { this.getUserInfo() this.getStorageInfo() }, navigateTo(e) { const index = e.currentTarget.dataset.index const path = e.currentTarget.dataset.path switch(index) { case 2: App.WxService.makePhoneCall({ phoneNumber: path }) break default: App.WxService.navigateTo(path) } }, getUserInfo() { const userInfo = App.globalData.userInfo if (userInfo) { this.setData({ userInfo: userInfo }) return } App.getUserInfo() .then(data => { console.log(data) this.setData({ userInfo: data }) }) }, getStorageInfo() { App.WxService.getStorageInfo() .then(data => { console.log(data) this.setData({ 'settings[0].path': `${data.currentSize}KB` }) }) }, bindtap(e) { const index = e.currentTarget.dataset.index const path = e.currentTarget.dataset.path switch(index) { case 0: App.WxService.showModal({ title: '友情提示', content: '确定要清除缓存吗?', }) .then(data => { if(data.confirm == 1) { App.WxService.clearStorage() this.signIn() } }) break default: App.WxService.navigateTo(path) } }, // logout() { // App.WxService.showModal({ // title: '友情提示', // content: '确定要登出吗?', // }) // .then(data => data.confirm == 1 && this.signOut()) // }, // signOut() { // App.HttpService.signOut() // .then(data => { // console.log(data) // if (data.meta.code == 0) { // App.WxService.removeStorageSync('token') // App.WxService.redirectTo('/pages/login/index') // } // }) // }, signIn() { if (App.WxService.getStorageSync('token')) return App.HttpService.signIn({ username: __config.loginItem.name, password: <PASSWORD>, }) .then(data => { console.log(data) if (data.meta.code == 0) { App.WxService.setStorageSync('token', data.data.token) } }) }, }) */import React, { Component } from 'react' import { View, Text, TouchableOpacity, KeyboardAvoidingView, TextInput, StyleSheet } from 'react-native' import { connect } from 'react-redux' import { purple, white } from '../utils/colors' import { addCard } from '../actions'; import { addCardToDeck } from '../utils/api'; class AddCard extends Component { state = { question: '', answer: '' } static navigationOptions = ({ navigation }) => { return { title: 'Add Card' } } submit = () => { const { deckId } = this.props.navigation.state.params const { question, answer } = this.state if (question.trim().length === 0 || answer.trim().length === 0) { return alert('Please fill both question and answer.') } else { this.props.dispatch(addCard(deckId, { question, answer })) addCardToDeck(deckId, { question, answer }) this.props.navigation.goBack() } } render() { const { question, answer } = this.state return ( <View style={styles.container}> <KeyboardAvoidingView> <TextInput style={styles.input} value={question} placeholder="Card question" onChangeText={(text) => this.setState({ question: text })} /> <TextInput style={styles.input} value={answer} placeholder="Card answer" onChangeText={(text) => this.setState({ answer: text })} /> </KeyboardAvoidingView> <TouchableOpacity style={styles.btn} onPress={this.submit} > <Text style={styles.btnText}>Submit</Text> </TouchableOpacity> </View> ) } } export default connect()(AddCard) const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: white, paddingTop: 30, paddingBottom: 30 }, input: { borderColor: purple, borderWidth: 2, borderRadius: 8, marginLeft: 30, marginRight: 30, padding: 10, fontSize: 24, marginBottom: 30, }, btn: { borderRadius: 8, backgroundColor: purple, marginBottom: 15, padding: 15, paddingLeft: 30, paddingRight: 30, alignItems: 'center', alignSelf: 'center' }, btnText: { color: white, fontSize: 24 } })<filename>src/js/actions/changeAmbiance.js import getAverageRGB from "../lib/getAverageRGB"; import LightenDarkenColor from "../lib/LightenDarkenColor"; import luma from "../lib/luma"; window.$muzik.changeAmbiance = (imageUrl) => { getAverageRGB(imageUrl).then((color) => { if (luma(color)) { color = LightenDarkenColor(color, 70); } const darkColor = LightenDarkenColor(color, -30); const lightColor = LightenDarkenColor(color, 30); window.$muzik.$colors.innerHTML = ` :root { --muzik-track-color: ${darkColor}; --muzik-thumb-color: ${color}; --muzik-thumb-color-hover: ${lightColor}; } body { background: linear-gradient(${Math.floor( Math.random() * 360 )}deg, ${lightColor} 0%, ${color} 50%, ${darkColor} 100%); } `; document.querySelector('meta[name="theme-color"]').content = color; }); }; import React from 'react'; import PropTypes from 'prop-types'; class ChipGroup extends React.PureComponent { static defaultProps = {}; static propTypes = {}; state = {}; constructor(props) { super(props); } componentDidMount() {} render() { const {className=null, children, ...rest} = this.props; let cls = ['c-chip-group']; cls.push(className); return (<div className={cls.join(' ')} {...rest}>{children}</div>); } } export default ChipGroup;<filename>html/namespaces_dup.js var namespaces_dup = [ [ "oist", "namespaceoist.html", null ] ];<reponame>jiumx60rus/grishyGhost<gh_stars>0 var util = require('util'), extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'), Xml = require('./Xml'); function Xslt(config) { Xml.call(this, config); } util.inherits(Xslt, Xml); extendWithGettersAndSetters(Xslt.prototype, { contentType: 'text/xslt+xml', supportedExtensions: ['.xsl', '.xslt'], isPretty: false }); module.exports = Xslt; const { createLogger, format, transports } = require('winston'); const logger = createLogger({ format: format.combine( format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), format.json() ), transports: [new transports.Console()], }); class DeviceObjectId { constructor(type, instance) { this.type = type; this.instance = instance; } } class DeviceObject { constructor(objectId, name, description, type, units, presentValue) { this.objectId = objectId; this.name = name; this.description = description; this.type = type; this.units = units; this.presentValue = presentValue; } } module.exports = { DeviceObjectId, DeviceObject, logger };<reponame>AndersCan/dvlp export const bar = 'hello from browser'; import React from "react"; import axios from "axios"; import { Doughnut } from "react-chartjs-2"; import classes from "./Graph.module.css"; class Graph extends React.Component { state = { ailments: [], labels: [], datasets: [ { label: "Past Ailments", backgroundColor: [], hoverBackgroundColor: [], data: [], }, ], }; getRandomColor = () => { var letters = '<KEY>'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } generateDataPoints = (arr) => { let tempLabels = []; let tempData = []; let tempBGColor = []; let tempFGColor = []; // Loop through data elements for (var i = 0; i < arr.length; i++){ // Generate Legend Headings for(var j = 0; j < arr[i].ailments.length; j++){ // Generate Data Points let t = arr[i]["ailments"][j].toString().trim(); // console.log("Value: ", t); if (!tempLabels.includes(t)){ // Create New Item and Set Count to 1 tempLabels.push(t); let n = tempLabels.indexOf(t); tempData[n] = 1; // console.log("Index of T: ", n); //Generate Random Color; tempBGColor[n] = this.getRandomColor(); tempFGColor[n] = this.getRandomColor(); }else if (tempLabels.includes(t)){ // Increate Data Item if exists let n = tempLabels.indexOf(t); tempData[n] = tempData[n] + 1; // console.log("Index of T: ", n); }else{ continue; } } } return [tempLabels, {data: tempData, backgroundColor: tempBGColor, hoverBackgroundColor: tempBGColor}]; }; componentDidMount() { // fetch and organise ailments let tempAilments = []; axios .get("/api/prescriptions") .then((response) => { //filter each pres to match the user tempAilments = response.data.filter( (item) => item.user_id === localStorage.getItem("user_id") ); let result = this.generateDataPoints(tempAilments); this.setState({labels: result[0], datasets: [result[1]]}); }) .catch((error) => { // console.log(error); }); } render() { return ( <div className={classes.Container}> <Doughnut data={this.state} width={500} height={500} options={{ title: { display: true, text: "Past Ailments", fontSize: 20, }, legend: { display: true, position: "top", }, }} /> </div> ); } } export default Graph; const prefixKey = key => 'ipfsUploader/' + key // persisteFile = { name: string, hash: string } export const storeFile = (box, ipfsHash) => box.private.get(prefixKey('files')).then(files => { const newFiles = Array.isArray(files) ? files : [] newFiles.push({ name: '', hash: ipfsHash, date: Date.now() }) box.private .set(prefixKey('files'), newFiles) .then(result => console.log(result)) }) export const fetchFiles = (box, callback) => box.private .get(prefixKey('files')) .then(files => { if (!Array.isArray(files)) return typeof callback === 'function' && callback([]) typeof callback === 'function' && callback(files) }) .catch(err => { console.error(err) }) export const saveFiles = (box, files, callback) => box.private.set(prefixKey('files'), files).then(result => { console.log(result) fetchFiles(box, callback) }) <reponame>tatchanon-j/Thaiwater_frontend /** * * Main JS application file for management display page. * This file is control the options and display data. * * @author CIM Systems (Thailand) <<EMAIL>> * @license HAII * */ var srvData = {}; //initial data srvData.init = function(translator) { var self = srvData; //initial data self.translator = translator; //Text for label and message on java script //Declare url servicce self.service_setting_list = 'thaiwater30/backoffice/tool/setting_list'; //service setting list self.service_display_setting_json = 'thaiwater30/backoffice/tool/display_setting_json'; //service code json for setting //Get data from service to generate option on filter setting list. apiService.SendRequest('GET', self.service_setting_list, {}, self.genFilterService); //Event filter setting change. $('#filter_setting').on('change', self.changeDataSetting); //Event click button save. $('#btn-save').on('click', self.saveDisplaySetting); // add custom validation json window.Parsley.addValidator('json', { validateString: function(value) { try { return JSON.parse(value); } catch (e) { return false; } }, messages: { en: srvData.translator["msg_err_json_format"], fr: srvData.translator["msg_err_json_format"] } }); //Event click on button edit. $('.btn-edit').on('click',function(){ $('.grp-btn').show(); $('.btn-edit').hide(); $('#display_setting').removeAttr('disabled','false'); }) //Event click on button cancel. $('#btn-cancel').on('click',self.closeEdit) } /** * Generate option on filter setting list * * @param {st} st list data to setting */ srvData.genFilterService = function(st){ var filter_setting = document.getElementById('filter_setting'); //element filter setting var data_service = apiService.getFieldValue(st,'data'); //data list setting var i = 0; //condition loop if(data_service == null){return } for(i; i<data_service.length; i++){ var gen_option = document.createElement('option'); //create element option var txt_option = data_service[i]['name']; //option name var val_option = data_service[i]['code']; //option value gen_option.text = txt_option gen_option.value = val_option filter_setting.add(gen_option) } srvData.displaySetting() } /** * Event change filter setting list * */ srvData.changeDataSetting = function(){ srvData.closeEdit(); srvData.displaySetting(); } /** * Display data setting * */ srvData.displaySetting = function(){ var data_setting = $('#filter_setting').val(); //list setting var param = { code : data_setting } apiService.SendRequest('GET', srvData.service_display_setting_json, param, function(js){ var data_display = JH.GetJsonValue(js,'data') $('#display_setting').val(data_display) }); } /** * Save data setting * */ srvData.saveDisplaySetting = function(){ var self = srvData; //initial data var st = $('#display_setting').val(); //code json for setting var data_code = $('#filter_setting').val(); //list setting var frm = $('#display-form'); //element form setting $('#display-form').parsley().validate(); if (! $('#display-form').parsley().isValid() ){ return false; } //var j_st = JSON.parse(st); var param = { code : data_code, value : st } apiService.SendRequest('PUT', self.service_display_setting_json, param, function(data, status, jqxhr){ if(status == 'success'){ bootbox.alert({ message: self.translator['msg_save_suc'], buttons: { ok: { label: self.translator['btn_close'] } } }) $('p.err-json').remove() srvData.closeEdit() }else{ bootbox.alert({ message: self.translator['msg_save_unsuc'], buttons: { ok: { label: self.translator['btn_close'] } } }) } }) } /** * Check fotmat json data * * @param {josn} st json data for settig */ srvData.isJson = function(st) { var data_code = $('#filter_setting').val(); //list setting $('p.err-json').remove(); try { return JSON.parse(st); } catch (e) { //text data type then do not validate json if(data_code!='thaiwater30.service.CreateYearlyPartitionCron' && data_code!='server.model.dataimport.GenerateDataImportDailyReportEventCron'){ $('#display_setting').parsley().addError("msg_err_json_format", {message: srvData.translator["msg_err_json_format"], updateClass: true}); } } return false; } /** * Close edit settig * */ srvData.closeEdit = function(){ srvData.displaySetting(); $('p.err-json').remove(); $('.grp-btn').hide(); $('.btn-edit').show(); $('#display_setting').attr('disabled','true'); $('#display-form').parsley().reset(); } exports.daysObjects = [ {id: 1, name: 'poniedziałek', short: 'pn'}, {id: 2, name: 'wtorek', short: 'wt'}, {id: 3, name: 'środa', short: 'śr'}, {id: 4, name: 'czwartek', short: 'czw'}, {id: 5, name: 'piątek', short: 'pt'}, {id: 6, name: 'sobota', short: 'sob'}, {id: 7, name: 'niedziela', short: 'nd'} ]; exports.daysArray = [ 'poniedziałek', 'wtorek', 'środa', 'czwartek', 'piątek', 'sobota', 'niedziela' ];<reponame>Gizeta/buaa-android-course<gh_stars>1-10 if (window.Clarinetto == undefined) { window.Clarinetto = Clarinetto = { controls: {} }; if (window.Backend == null) { window.Backend = { UpdateMusicList: function(){ }, Play: function() { }, Pause: function() { }, PlayPrevious: function() { }, PlayNext: function() { }, PlayMusic: function(e) { }, LoadInitialMusic: function() { }, Seek: function(e) { } } } (function() { window.addEventListener('contextmenu', function(e) { e.preventDefault(); }); })(); } /* * @Author: liuzhongbao * @Date: 2019-10-20 12:59:29 * @Last Modified by: liuzhongbao * @Last Modified time: 2019-10-26 10:34:39 */ // import {liuzhongbao,photosynthesis} from '@/servers/photosynthesis'; // 集成环境 Dva的核心模块 export default { namespace: 'exam', state: { userdata: {}, }, reducers: { changeState(state, action) { return { ...state, ...action }; }, }, effects: { // 此处写generalter函数 }, }; <gh_stars>1000+ const sqlite3 = require('sqlite3'); const appLog = require('../../lib/app-log'); const { formatSchemaQueryResults } = require('../utils'); const id = 'sqlite'; const name = 'SQLite'; const fields = [ { key: 'filename', formType: 'TEXT', label: 'Filename / path', // empty string is anonymous disk backed. :memory: is in memory }, { key: 'readonly', formType: 'CHECKBOX', label: 'Read only', }, ]; class Client { constructor(connection) { this.connection = connection; this.db = null; } async connect() { if (this.db) { throw new Error('Client already connected'); } const { filename, readonly } = this.connection; // If read only is selected we'll use that otherwise fall back to default // By default sqlite3 driver will open with OPEN_READWRITE | OPEN_CREATE // The mode can't be sent in as NULL/undefined to trigger this fallback behavior, // so instead we'll make separate calls here if (readonly) { return new Promise((resolve, reject) => { this.db = new sqlite3.Database( filename, sqlite3.OPEN_READONLY, (err) => { if (err) { this.db = null; return reject(err); } return resolve(); } ); }); } return new Promise((resolve, reject) => { this.db = new sqlite3.Database(filename, (err) => { if (err) { this.db = null; return reject(err); } return resolve(); }); }); } async disconnect() { if (this.db) { const db = this.db; this.db = null; return new Promise((resolve, reject) => { db.close((err) => { if (err) { appLog.error(err, 'Error ending sqlite db'); return reject(err); } return resolve(); }); }); } } /** * Run query and return the results * * Instead of taking the ODBC approach where a result set is suppressed and the last SELECT set is shown, * The SQLite implementation shows a jumbled mix of results * The reason for this is because we can't tell what was a successful SELECT query vs INSERT/DELETE * as they all return an array of row objects * @param {string} query - string of SQL to execute */ async runQuery(query) { let incomplete = false; let rows = []; const { maxRows } = this.connection; rows = await dbAllAsync(this.db, query); if (rows.length > maxRows) { rows = rows.slice(0, maxRows); incomplete = true; } return { rows, incomplete }; } } function dbAllAsync(db, query) { return new Promise((resolve, reject) => { db.all(query, (err, rows) => { if (err) { return reject(err); } return resolve(rows); }); }); } /** * Run query for connection * Should return { rows, incomplete } * @param {string} query * @param {object} connection */ async function runQuery(query, connection) { const db = new Client(connection); await db.connect(); try { const result = await db.runQuery(query); await db.disconnect(); return result; } catch (error) { await db.disconnect(); throw error; } } /** * Test connectivity of connection * @param {*} connection */ function testConnection(connection) { const query = "SELECT 'success' AS TestQuery;"; return runQuery(query, connection); } /** * Get schema for connection * @param {*} connection */ async function getSchema(connection) { const db = new Client(connection); await db.connect(); try { // For SQLite get tables, then iterate over and get columns for each const queryResult = await db.runQuery(` SELECT 'main' as table_schema, name as table_name, null as column_name, null as data_type FROM sqlite_master `); // For each table row, call PRAGMA to get info, // and use the combined results for the schema results const columnRows = []; for (const tableRow of queryResult.rows) { const { table_name } = tableRow; // eslint-disable-next-line no-await-in-loop const columnQueryResult = await db.runQuery( `PRAGMA table_info(${table_name})` ); columnQueryResult.rows.forEach((row) => { columnRows.push({ table_schema: 'main', table_name, column_name: row.name, data_type: row.type, }); }); } // Replace the table queryResult rows with those from column rows // The table names will be lifted up (we'll otherwise have null "columns" listed in tree) queryResult.rows = columnRows; await db.disconnect(); return formatSchemaQueryResults(queryResult); } catch (error) { await db.disconnect(); throw error; } } module.exports = { Client, id, name, fields, getSchema, runQuery, testConnection, }; <filename>index.js require('./src/tyt-checkin')().catch(console.error) function TurtleState(angle, other) { this.onLine = false; if(other == undefined) { this.setQuaternions(angle); this.at = new THREE.Vector3(0, 0, 0); this.quaternion = new THREE.Quaternion(); } else { this.at = other.at.clone(); this.quaternion = other.quaternion.clone(); this.yawAddQuat = other.yawAddQuat; this.yawSubtractQuat = other.yawSubtractQuat; this.rollAddQuat = other.rollAddQuat; this.rollSubtractQuat = other.rollSubtractQuat; this.pitchAddQuat = other.pitchAddQuat; this.pitchSubtractQuat = other.pitchSubtractQuat; } } TurtleState.prototype = { AXIS_X: new THREE.Vector3(1, 0, 0), AXIS_Y: new THREE.Vector3(0, 1, 0), AXIS_Z: new THREE.Vector3(0, 0, 1), DEG_TO_RAD: Math.PI / 180, setQuaternions(angle) { angle *= this.DEG_TO_RAD; this.yawAddQuat = new THREE.Quaternion(); this.yawAddQuat.setFromAxisAngle(this.AXIS_Z, angle); this.yawSubtractQuat = new THREE.Quaternion(); this.yawSubtractQuat.setFromAxisAngle(this.AXIS_Z, -angle); this.rollAddQuat = new THREE.Quaternion(); this.rollAddQuat.setFromAxisAngle(this.AXIS_Y, angle); this.rollSubtractQuat = new THREE.Quaternion(); this.rollSubtractQuat.setFromAxisAngle(this.AXIS_Y, -angle); this.pitchAddQuat = new THREE.Quaternion(); this.pitchAddQuat.setFromAxisAngle(this.AXIS_X, angle); this.pitchSubtractQuat = new THREE.Quaternion(); this.pitchSubtractQuat.setFromAxisAngle(this.AXIS_X, -angle); }, getDirectionVector() { var v = new THREE.Vector3(0, 1, 0); v.applyQuaternion(this.quaternion); return v; }, extrude() { this.at = this.at.add(this.getDirectionVector()); return this.at.clone(); }, yawAdd() { this.quaternion.multiply(this.yawAddQuat); this.setOnLine(false); }, yawSubtract() { this.quaternion.multiply(this.yawSubtractQuat); this.setOnLine(false); }, rollAdd() { this.quaternion.multiply(this.rollAddQuat); }, rollSubtract() { this.quaternion.multiply(this.rollSubtractQuat); }, pitchAdd() { this.quaternion.multiply(this.pitchAddQuat); this.setOnLine(false); }, pitchSubtract() { this.quaternion.multiply(this.pitchSubtractQuat); this.setOnLine(false); }, isOnLine() { return this.onLine; }, setOnLine(onLine) { this.onLine = onLine; }, get() { return this.at.clone(); } } function Scene(scene, content, light) { this.scene = scene; this.content = content; this.light = light; for(var i = 0; i < this.content.length; ++i) this.scene.add(this.content[i]); this.scene.add(light); } Scene.prototype = { dispose() { for(var i = 0; i < this.content.length; ++i) { this.scene.remove(this.content[i]); this.content[i].geometry.dispose(); } this.scene.remove(this.light); } } function Geometry(symbols, constants, angle) { this.symbols = symbols; this.constants = constants; this.angle = angle; } Geometry.prototype = { TUBE_PRECISION: 5, TUBE_RADIUS: 0.2, END_SPHERE: new THREE.SphereGeometry(0.3, 5, 5), MATERIAL_TUBE: new THREE.MeshPhongMaterial({ emissive: new THREE.Color("rgb(153, 204, 0)").multiplyScalar(0.3), color: new THREE.Color("rgb(153, 204, 0)"), specular: new THREE.Color("rgb(255, 255, 255)").multiplyScalar(0.3), shininess: 25 }), MATERIAL_CUBES: new THREE.MeshPhongMaterial({ emissive: new THREE.Color("rgb(151, 200, 219)").multiplyScalar(0.3), color: new THREE.Color("rgb(151, 200, 219)"), specular: new THREE.Color("rgb(255, 255, 255)").multiplyScalar(0.3), shininess: 30 }), MATERIAL_BRANCH: new THREE.MeshPhongMaterial({ emissive: new THREE.Color("rgb(196, 159, 113)").multiplyScalar(0.3), color: new THREE.Color("rgb(196, 159, 113)"), specular: new THREE.Color("rgb(255, 255, 255)").multiplyScalar(0.3), shininess: 4 }), MATERIAL_LEAF: new THREE.MeshPhongMaterial({ emissive: new THREE.Color("rgb(153, 204, 0)").multiplyScalar(0.3), color: new THREE.Color("rgb(153, 204, 0)"), specular: new THREE.Color("rgb(255, 255, 255)").multiplyScalar(0.3), shininess: 12 }), MATERIAL_LINE: new THREE.LineBasicMaterial({ color: new THREE.Color("rgb(255, 255, 255)") }), MATERIAL_WIREFRAME: new THREE.LineBasicMaterial({ color: new THREE.Color("rgb(255, 255, 255)") }), get() { return this.geometry; }, getCenter() { return this.center; }, getRadius() { return this.radius; }, getBranches(trim) { var branches = []; var states = []; var workingBranches = [[]]; var state = new TurtleState(this.angle); var xMin = 0; var xMax = 0; var yMin = 0; var yMax = 0; var zMin = 0; var zMax = 0; workingBranches[workingBranches.length - 1].push(state.get()); for(var index = 0; index < this.symbols.length; ++index) { switch(this.symbols[index].symbol) { case "[": states.push(new TurtleState(this.angle, state)); state.setOnLine(false); workingBranches.push([state.get()]); break; case "]": state = states.pop(); var branch = workingBranches.pop(); if(branch.length > 1) branches.push(branch); break; case "+": state.yawAdd(); break; case "-": state.yawSubtract(); break; case "/": state.rollAdd(); break; case "\\": state.rollSubtract(); break; case "^": state.pitchAdd(); break; case "_": state.pitchSubtract(); break; default: if(this.constants.indexOf(this.symbols[index].symbol) == -1) { var pos = state.extrude(); if(pos.x < xMin) xMin = pos.x; if(pos.x > xMax) xMax = pos.x; if(pos.y < yMin) yMin = pos.y; if(pos.y > yMax) yMax = pos.y; if(pos.z < zMin) zMin = pos.z; if(pos.z > zMax) zMax = pos.z; if(state.isOnLine() && trim) workingBranches[workingBranches.length - 1].pop(); else state.setOnLine(true); workingBranches[workingBranches.length - 1].push(pos); } break; } } branches.push(workingBranches.pop()); var xRange = xMax - xMin; var yRange = yMax - yMin; var zRange = zMax - zMin; this.center = new THREE.Vector3( xMin + xRange / 2, yMin + yRange / 2, zMin + zRange / 2); this.radius = new THREE.Vector3(xRange, yRange, zRange).length() / 2; return branches; }, buildGeometryTubes(branches) { var geometry = new THREE.Geometry(); for(var i = 0; i < branches.length; ++i) { var branch = branches[i]; if(branch.length <= 1) continue; var tube = new THREE.TubeGeometry( new THREE.CatmullRomCurve3(branch), (branch.length - 1) * 4, this.TUBE_RADIUS, this.TUBE_PRECISION, false); if(i == 0) geometry.merge(this.END_SPHERE); geometry.merge(tube); tube.dispose(); var canopy = branches[i][branches[i].length - 1]; var canopyMatrix = new THREE.Matrix4().makeTranslation(canopy.x, canopy.y, canopy.z); geometry.merge(this.END_SPHERE, canopyMatrix); } return [new THREE.Mesh(geometry, this.MATERIAL_TUBE)]; }, buildGeometryLines(branches) { var geometry = new THREE.Geometry(); for(var i = 0; i < branches.length; ++i) { var branch = branches[i]; if(branch.length <= 1) continue; for(var j = 0; j < branch.length - 1; ++j) { geometry.vertices.push(branch[j]); geometry.vertices.push(branch[j + 1]); } } return [new THREE.LineSegments(geometry, this.MATERIAL_LINE)]; }, buildGeometryWireframe(branches) { var geometry = new THREE.Geometry(); for(var i = 0; i < branches.length; ++i) { var branch = branches[i]; if(branch.length <= 1) continue; var tube = new THREE.TubeGeometry( new THREE.CatmullRomCurve3(branch), (branch.length - 1) * 4, this.TUBE_RADIUS, this.TUBE_PRECISION, false); geometry.merge(tube); tube.dispose(); } var wireframeGeometry = new THREE.WireframeGeometry(geometry); geometry.dispose(); return [new THREE.LineSegments(wireframeGeometry, this.MATERIAL_WIREFRAME)]; }, buildGeometryPlant(branches) { var geometryBranches = new THREE.Geometry(); var geometryLeaves = new THREE.Geometry(); for(var i = 0; i < branches.length; ++i) { var branch = branches[i]; if(branch.length <= 1) continue; var tube = new THREE.TubeGeometry( new THREE.CatmullRomCurve3(branch), (branch.length - 1) * 4, this.TUBE_RADIUS, this.TUBE_PRECISION, false); geometryBranches.merge(tube); tube.dispose(); if(branch.length >= 2) { var leaf = new THREE.ConeGeometry( 1, 1.5, 5, 1, false); var direction = new THREE.Vector3(); direction.subVectors(branch[branch.length - 1], branch[branch.length - 2]); var leafTranslation = new THREE.Matrix4().makeTranslation( branch[branch.length - 1].x, branch[branch.length - 1].y, branch[branch.length - 1].z); var leafRotation = new THREE.Matrix4().lookAt( branch[branch.length - 1], branch[branch.length - 2], new THREE.Vector3(0, 1, 0)).multiply(new THREE.Matrix4().makeRotationX(Math.PI * -0.5)); var leafOffset = new THREE.Matrix4().makeTranslation(0, -0.4, 0); geometryLeaves.merge(leaf, leafTranslation.multiply(leafRotation).multiply(leafOffset)); leaf.dispose(); } } return [ new THREE.Mesh(geometryBranches, this.MATERIAL_BRANCH), new THREE.Mesh(geometryLeaves, this.MATERIAL_LEAF)]; }, buildGeometryCubes(branches) { var geometry = new THREE.Geometry(); for(var i = 0; i < branches.length; ++i) { var branch = branches[i]; if(branch.length <= 1) continue; for(var j = 0; j < branch.length; ++j) { var box = new THREE.BoxGeometry(1, 1, 1); var boxTransform = new THREE.Matrix4().makeTranslation( branch[j].x, branch[j].y, branch[j].z); geometry.merge(box, boxTransform); box.dispose(); } } return [new THREE.Mesh(geometry, this.MATERIAL_CUBES)]; }, build(scene, light, renderStyle) { var content; switch(renderStyle) { default: case "lines": content = this.buildGeometryLines(this.getBranches(true)); break; case "tubes": content = this.buildGeometryTubes(this.getBranches(true)); break; case "wireframe": content = this.buildGeometryWireframe(this.getBranches(true)); break; case "plant": content = this.buildGeometryPlant(this.getBranches(true)); break; case "cubes": content = this.buildGeometryCubes(this.getBranches(false)); break; } return new Scene(scene, content, light); } }<filename>client/src/js/base/__tests__/NoneFound.test.js import { NoneFound, NoneFoundBox, NoneFoundSection } from "../NoneFound"; describe("<NoneFound />", () => { it("should render with [noun='files'", () => { const wrapper = shallow(<NoneFound noun="files" />); expect(wrapper).toMatchSnapshot(); }); }); describe("<NoneFoundBox />", () => { it("should render with [noun='boxes'", () => { const wrapper = shallow(<NoneFoundBox noun="boxes" />); expect(wrapper).toMatchSnapshot(); }); }); describe("<NoneFoundSection />", () => { it("should render with [noun='sections'", () => { const wrapper = shallow(<NoneFoundSection noun="sections" />); expect(wrapper).toMatchSnapshot(); }); it("should render with [noun='sections'] and children", () => { const wrapper = shallow( <NoneFoundSection noun="sections"> <span>foo</span> </NoneFoundSection> ); expect(wrapper).toMatchSnapshot(); }); }); /** * @fileoverview Enforce a defaultProps definition for every prop that is not a required prop. * @author <NAME> */ 'use strict'; // ------------------------------------------------------------------------------ // Requirements // ------------------------------------------------------------------------------ const rule = require('../../../lib/rules/require-default-props'); const RuleTester = require('eslint').RuleTester; const parserOptions = { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { jsx: true } }; const ruleTester = new RuleTester({parserOptions}); // ------------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------------ ruleTester.run('require-default-props', rule, { valid: [ // // stateless components { code: [ 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string.isRequired,', ' bar: PropTypes.string.isRequired', '};' ].join('\n') }, { code: [ 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'MyStatelessComponent.defaultProps = {', ' foo: "foo"', '};' ].join('\n') }, { code: [ 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}' ].join('\n') }, { code: [ 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = {', ' bar: PropTypes.string.isRequired', '};', 'MyStatelessComponent.propTypes.foo = PropTypes.string;', 'MyStatelessComponent.defaultProps = {', ' foo: "foo"', '};' ].join('\n') }, { code: [ 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = {', ' bar: PropTypes.string.isRequired', '};', 'MyStatelessComponent.propTypes.foo = PropTypes.string;', 'MyStatelessComponent.defaultProps = {};', 'MyStatelessComponent.defaultProps.foo = "foo";' ].join('\n') }, { code: [ 'function MyStatelessComponent({ foo }) {', ' return <div>{foo}</div>;', '}', 'MyStatelessComponent.propTypes = {};', 'MyStatelessComponent.propTypes.foo = PropTypes.string;', 'MyStatelessComponent.defaultProps = {};', 'MyStatelessComponent.defaultProps.foo = "foo";' ].join('\n') }, { code: [ 'const types = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = types;', 'MyStatelessComponent.defaultProps = {', ' foo: "foo"', '};' ].join('\n') }, { code: [ 'const defaults = {', ' foo: "foo"', '};', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'MyStatelessComponent.defaultProps = defaults;' ].join('\n') }, { code: [ 'const defaults = {', ' foo: "foo"', '};', 'const types = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = types;', 'MyStatelessComponent.defaultProps = defaults;' ].join('\n') }, // // createReactClass components { code: [ 'var Greeting = createReactClass({', ' render: function() {', ' return <div>Hello {this.props.foo} {this.props.bar}</div>;', ' },', ' propTypes: {', ' foo: PropTypes.string.isRequired,', ' bar: PropTypes.string.isRequired', ' }', '});' ].join('\n') }, { code: [ 'var Greeting = createReactClass({', ' render: function() {', ' return <div>Hello {this.props.foo} {this.props.bar}</div>;', ' },', ' propTypes: {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', ' },', ' getDefaultProps: function() {', ' return {', ' foo: "foo"', ' };', ' }', '});' ].join('\n') }, { code: [ 'var Greeting = createReactClass({', ' render: function() {', ' return <div>Hello {this.props.foo} {this.props.bar}</div>;', ' },', ' propTypes: {', ' foo: PropTypes.string,', ' bar: PropTypes.string', ' },', ' getDefaultProps: function() {', ' return {', ' foo: "foo",', ' bar: "bar"', ' };', ' }', '});' ].join('\n') }, { code: [ 'var Greeting = createReactClass({', ' render: function() {', ' return <div>Hello {this.props.foo} {this.props.bar}</div>;', ' }', '});' ].join('\n') }, // // ES6 class component { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' foo: PropTypes.string.isRequired,', ' bar: PropTypes.string.isRequired', '};', 'Greeting.defaultProps = {', ' foo: "foo"', '};' ].join('\n') }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'Greeting.defaultProps = {', ' foo: "foo"', '};' ].join('\n') }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}' ].join('\n') }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' bar: PropTypes.string.isRequired', '};', 'Greeting.propTypes.foo = PropTypes.string;', 'Greeting.defaultProps = {', ' foo: "foo"', '};' ].join('\n') }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' bar: PropTypes.string.isRequired', '};', 'Greeting.propTypes.foo = PropTypes.string;', 'Greeting.defaultProps = {};', 'Greeting.defaultProps.foo = "foo";' ].join('\n') }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {};', 'Greeting.propTypes.foo = PropTypes.string;', 'Greeting.defaultProps = {};', 'Greeting.defaultProps.foo = "foo";' ].join('\n') }, // // edge cases // not a react component { code: [ 'function NotAComponent({ foo, bar }) {}', 'NotAComponent.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};' ].join('\n') }, { code: [ 'class Greeting {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' bar: PropTypes.string.isRequired', '};' ].join('\n') }, // external references { code: [ 'const defaults = require("./defaults");', 'const types = {', ' foo: PropTypes.string,', ' bar: PropTypes.string', '};', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = types;', 'MyStatelessComponent.defaultProps = defaults;' ].join('\n') }, { code: [ 'const defaults = {', ' foo: "foo"', '};', 'const types = require("./propTypes");', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = types;', 'MyStatelessComponent.defaultProps = defaults;' ].join('\n') }, { code: [ 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string', '};', 'MyStatelessComponent.defaultProps = require("./defaults").foo;', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}' ].join('\n') }, { code: [ 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string', '};', 'MyStatelessComponent.defaultProps = require("./defaults").foo;', 'MyStatelessComponent.defaultProps.bar = "bar";', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}' ].join('\n') }, { code: [ 'import defaults from "./defaults";', 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string', '};', 'MyStatelessComponent.defaultProps = defaults;', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}' ].join('\n'), parserOptions: Object.assign({sourceType: 'module'}, parserOptions) }, { code: [ 'import { foo } from "./defaults";', 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string', '};', 'MyStatelessComponent.defaultProps = foo;', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}' ].join('\n'), parserOptions: Object.assign({sourceType: 'module'}, parserOptions) }, // using spread operator { code: [ 'const component = rowsOfType(GuestlistEntry, (rowData, ownProps) => ({', ' ...rowData,', ' onPress: () => ownProps.onPress(rowData.id),', '}));' ].join('\n') }, { code: [ 'MyStatelessComponent.propTypes = {', ' ...stuff,', ' foo: PropTypes.string', '};', 'MyStatelessComponent.defaultProps = {', ' foo: "foo"', '};', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}' ].join('\n') }, { code: [ 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string', '};', 'MyStatelessComponent.defaultProps = {', ' ...defaults,', '};', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}' ].join('\n') }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' ...someProps,', ' bar: PropTypes.string.isRequired', '};' ].join('\n') }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'Greeting.defaultProps = {', ' ...defaults,', ' bar: "bar"', '};' ].join('\n') }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'Greeting.defaultProps = {', ' ...defaults,', ' bar: "bar"', '};' ].join('\n') }, // // with Flow annotations { code: [ 'type Props = {', ' foo: string', '};', 'class Hello extends React.Component {', ' props: Props;', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'type Props = {', ' foo: string,', ' bar?: string', '};', 'class Hello extends React.Component {', ' props: Props;', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}', 'Hello.defaultProps = {', ' bar: "bar"', '};' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'class Hello extends React.Component {', ' props: {', ' foo: string,', ' bar?: string', ' };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}', 'Hello.defaultProps = {', ' bar: "bar"', '};' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'class Hello extends React.Component {', ' props: {', ' foo: string', ' };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'function Hello(props: { foo?: string }) {', ' return <div>Hello {props.foo}</div>;', '}', 'Hello.defaultProps = { foo: "foo" };' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'function Hello(props: { foo: string }) {', ' return <div>Hello {foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'const Hello = (props: { foo?: string }) => {', ' return <div>Hello {props.foo}</div>;', '};', 'Hello.defaultProps = { foo: "foo" };' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'const Hello = (props: { foo: string }) => {', ' return <div>Hello {foo}</div>;', '};' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'const Hello = function(props: { foo?: string }) {', ' return <div>Hello {props.foo}</div>;', '};', 'Hello.defaultProps = { foo: "foo" };' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'const Hello = function(props: { foo: string }) {', ' return <div>Hello {foo}</div>;', '};' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'type Props = {', ' foo: string,', ' bar?: string', '};', 'type Props2 = {', ' foo: string,', ' baz?: string', '}', 'function Hello(props: Props | Props2) {', ' return <div>Hello {props.foo}</div>;', '}', 'Hello.defaultProps = {', ' bar: "bar",', ' baz: "baz"', '};' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'import type Props from "fake";', 'class Hello extends React.Component {', ' props: Props;', ' render () {', ' return <div>Hello {this.props.name.firstname}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'type Props = any;', 'const Hello = function({ foo }: Props) {', ' return <div>Hello {foo}</div>;', '};' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'import type ImportedProps from "fake";', 'type Props = ImportedProps;', 'function Hello(props: Props) {', ' return <div>Hello {props.name.firstname}</div>;', '}' ].join('\n'), parser: 'babel-eslint' }, // don't error when variable is not in scope { code: [ 'import type { ImportedType } from "fake";', 'type Props = ImportedType;', 'function Hello(props: Props) {', ' return <div>Hello {props.name.firstname}</div>;', '}' ].join('\n'), parser: 'babel-eslint' }, // make sure error is not thrown with multiple assignments { code: [ 'import type ImportedProps from "fake";', 'type NestedProps = ImportedProps;', 'type Props = NestedProps;', 'function Hello(props: Props) {', ' return <div>Hello {props.name.firstname}</div>;', '}' ].join('\n'), parser: 'babel-eslint' }, // make sure defaultProps are correctly detected with quoted properties { code: [ 'function Hello(props) {', ' return <div>Hello {props.bar}</div>;', '}', 'Hello.propTypes = {', ' bar: PropTypes.string', '};', 'Hello.defaultProps = {', ' "bar": "bar"', '};' ].join('\n'), parser: 'babel-eslint' }, { code: [ 'class Hello extends React.Component {', ' static propTypes = {', ' foo: PropTypes.string.isRequired', ' }', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', options: [{forbidDefaultForRequired: true}] }, // test support for React PropTypes as Component's class generic { code: [ 'type HelloProps = {', ' foo: string,', ' bar?: string', '};', 'class Hello extends React.Component<HelloProps> {', ' static defaultProps = {', ' bar: "bar"', ' }', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', options: [{forbidDefaultForRequired: true}] }, { code: [ 'type HelloProps = {', ' foo: string,', ' bar?: string', '};', 'class Hello extends Component<HelloProps> {', ' static defaultProps = {', ' bar: "bar"', ' }', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', options: [{forbidDefaultForRequired: true}] }, { code: [ 'type HelloProps = {', ' foo: string,', ' bar?: string', '};', 'type HelloState = {', ' dummyState: string', '};', 'class Hello extends Component<HelloProps, HelloState> {', ' static defaultProps = {', ' bar: "bar"', ' }', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', options: [{forbidDefaultForRequired: true}] }, { code: [ 'type HelloProps = {', ' foo?: string,', ' bar?: string', '};', 'class Hello extends Component<HelloProps> {', ' static defaultProps = {', ' foo: "foo",', ' bar: "bar"', ' }', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', options: [{forbidDefaultForRequired: true}] }, { code: ` type Props = { +name?: string, }; function Hello(props: Props) { return <div>Hello {props.name}</div>; } Hello.defaultProps = { name: 'foo' }; `, parser: 'babel-eslint' } ], invalid: [ // // stateless components { code: [ 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 5, column: 3 }] }, { code: [ 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = forbidExtraProps({', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '});' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 5, column: 3 }], settings: { propWrapperFunctions: ['forbidExtraProps'] } }, { code: [ 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'const propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'MyStatelessComponent.propTypes = forbidExtraProps(propTypes);' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 5, column: 3 }], settings: { propWrapperFunctions: ['forbidExtraProps'] } }, { code: [ 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'MyStatelessComponent.propTypes.baz = React.propTypes.string;' ].join('\n'), errors: [ { message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 5, column: 3 }, { message: 'propType "baz" is not required, but has no corresponding defaultProps declaration.', line: 8, column: 1 } ] }, { code: [ 'const types = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = types;' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 2, column: 3 }] }, { code: [ 'const defaults = {', ' foo: "foo"', '};', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string', '};', 'MyStatelessComponent.defaultProps = defaults;' ].join('\n'), errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 9, column: 3 }] }, { code: [ 'const defaults = {', ' foo: "foo"', '};', 'const types = {', ' foo: PropTypes.string,', ' bar: PropTypes.string', '};', 'function MyStatelessComponent({ foo, bar }) {', ' return <div>{foo}{bar}</div>;', '}', 'MyStatelessComponent.propTypes = types;', 'MyStatelessComponent.defaultProps = defaults;' ].join('\n'), errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 6, column: 3 }] }, // // createReactClass components { code: [ 'var Greeting = createReactClass({', ' render: function() {', ' return <div>Hello {this.props.foo} {this.props.bar}</div>;', ' },', ' propTypes: {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', ' }', '});' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 6, column: 5 }] }, { code: [ 'var Greeting = createReactClass({', ' render: function() {', ' return <div>Hello {this.props.foo} {this.props.bar}</div>;', ' },', ' propTypes: {', ' foo: PropTypes.string,', ' bar: PropTypes.string', ' },', ' getDefaultProps: function() {', ' return {', ' foo: "foo"', ' };', ' }', '});' ].join('\n'), errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 7, column: 5 }] }, // // ES6 class component { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 9, column: 3 }] }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string', '};', 'Greeting.defaultProps = {', ' foo: "foo"', '};' ].join('\n'), errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 10, column: 3 }] }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' bar: PropTypes.string.isRequired', '};', 'Greeting.propTypes.foo = PropTypes.string;' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 11, column: 1 }] }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {', ' bar: PropTypes.string', '};', 'Greeting.propTypes.foo = PropTypes.string;', 'Greeting.defaultProps = {};', 'Greeting.defaultProps.foo = "foo";' ].join('\n'), errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 9, column: 3 }] }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'Greeting.propTypes = {};', 'Greeting.propTypes.foo = PropTypes.string;', 'Greeting.defaultProps = {};', 'Greeting.defaultProps.bar = "bar";' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 9, column: 1 }] }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'const props = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'Greeting.propTypes = props;' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 9, column: 3 }] }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', '}', 'const props = {', ' foo: PropTypes.string,', ' bar: PropTypes.string', '};', 'const defaults = {', ' foo: "foo"', '};', 'Greeting.propTypes = props;', 'Greeting.defaultProps = defaults;' ].join('\n'), errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 10, column: 3 }] }, // // ES6 classes with static getter methods { code: [ 'class Hello extends React.Component {', ' static get propTypes() {', ' return {', ' name: PropTypes.string', ' };', ' }', ' render() {', ' return <div>Hello {this.props.name}</div>;', ' }', '}' ].join('\n'), errors: [{ message: 'propType "name" is not required, but has no corresponding defaultProps declaration.', line: 4, column: 7 }] }, { code: [ 'class Hello extends React.Component {', ' static get propTypes() {', ' return {', ' foo: PropTypes.string,', ' bar: PropTypes.string', ' };', ' }', ' static get defaultProps() {', ' return {', ' bar: "world"', ' };', ' }', ' render() {', ' return <div>Hello {this.props.name}</div>;', ' }', '}' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 4, column: 7 }] }, { code: [ 'const props = {', ' foo: PropTypes.string', '};', 'class Hello extends React.Component {', ' static get propTypes() {', ' return props;', ' }', ' render() {', ' return <div>Hello {this.props.name}</div>;', ' }', '}' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 2, column: 3 }] }, { code: [ 'const defaults = {', ' bar: "world"', '};', 'class Hello extends React.Component {', ' static get propTypes() {', ' return {', ' foo: PropTypes.string,', ' bar: PropTypes.string', ' };', ' }', ' static get defaultProps() {', ' return defaults;', ' }', ' render() {', ' return <div>Hello {this.props.name}</div>;', ' }', '}' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 7, column: 7 }] }, // // ES6 classes with property initializers { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', ' static propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', ' };', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 8, column: 5 }] }, { code: [ 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', ' static propTypes = {', ' foo: PropTypes.string,', ' bar: PropTypes.string', ' };', ' static defaultProps = {', ' foo: "foo"', ' };', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 9, column: 5 }] }, { code: [ 'const props = {', ' foo: PropTypes.string,', ' bar: PropTypes.string.isRequired', '};', 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', ' static propTypes = props;', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 2, column: 3 }] }, { code: [ 'const props = {', ' foo: PropTypes.string,', ' bar: PropTypes.string', '};', 'const defaults = {', ' foo: "foo"', '};', 'class Greeting extends React.Component {', ' render() {', ' return (', ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>', ' );', ' }', ' static propTypes = props;', ' static defaultProps = defaults;', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 3, column: 3 }] }, // // edge cases { code: [ 'let Greetings = {};', 'Greetings.Hello = class extends React.Component {', ' render () {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}', 'Greetings.Hello.propTypes = {', ' foo: PropTypes.string', '};' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 8, column: 3 }] }, { code: [ 'var Greetings = ({ foo = "foo" }) => {', ' return <div>Hello {this.props.foo}</div>;', '}', 'Greetings.propTypes = {', ' foo: PropTypes.string', '};' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 5, column: 3 }] }, // component with no declared props followed by a failing component { code: [ 'var ComponentWithNoProps = ({ bar = "bar" }) => {', ' return <div>Hello {this.props.foo}</div>;', '}', 'var Greetings = ({ foo = "foo" }) => {', ' return <div>Hello {this.props.foo}</div>;', '}', 'Greetings.propTypes = {', ' foo: PropTypes.string', '};' ].join('\n'), errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 8, column: 3 }] }, // // with Flow annotations { code: [ 'class Hello extends React.Component {', ' props: {', ' foo?: string,', ' bar?: string', ' };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}', 'Hello.defaultProps = {', ' foo: "foo"', '};' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 4, column: 5 }] }, { code: [ 'type Props = {', ' foo: string,', ' bar?: string', '};', 'class Hello extends React.Component {', ' props: Props;', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 3, column: 3 }] }, { code: [ 'type Props = {', ' foo?: string', '};', 'class Hello extends React.Component {', ' props: Props;', ' static defaultProps: { foo: string };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 2, column: 3 }] }, { code: [ 'class Hello extends React.Component {', ' props: {', ' foo: string,', ' bar?: string', ' };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 4, column: 5 }] }, { code: [ 'class Hello extends React.Component {', ' props: {', ' foo?: string,', ' bar?: string', ' };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [ { message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 3, column: 5 }, { message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 4, column: 5 } ] }, { code: [ 'class Hello extends React.Component {', ' props: {', ' foo?: string', ' };', ' static defaultProps: { foo: string };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 3, column: 5 }] }, { code: [ 'type Props = {', ' foo?: string,', ' bar?: string', '};', 'class Hello extends React.Component {', ' props: Props;', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}', 'Hello.defaultProps = {', ' foo: "foo"', '};' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 3, column: 3 }] }, { code: [ 'type Props = {', ' foo?: string,', ' bar?: string', '};', 'class Hello extends React.Component {', ' props: Props;', ' static defaultProps: { foo: string, bar: string };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}', 'Hello.defaultProps = {', ' foo: "foo"', '};' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 3, column: 3 }] }, { code: [ 'class Hello extends React.Component {', ' props: {', ' foo?: string,', ' bar?: string', ' };', ' static defaultProps: { foo: string, bar: string };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}', 'Hello.defaultProps = {', ' foo: "foo"', '};' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 4, column: 5 }] }, { code: [ 'function Hello(props: { foo?: string }) {', ' return <div>Hello {props.foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 25 }] }, { code: [ 'function Hello({ foo = "foo" }: { foo?: string }) {', ' return <div>Hello {foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 35 }] }, { code: [ 'function Hello(props: { foo?: string, bar?: string }) {', ' return <div>Hello {props.foo}</div>;', '}', 'Hello.defaultProps = { foo: "foo" };' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 39 }] }, { code: [ 'function Hello(props: { foo?: string, bar?: string }) {', ' return <div>Hello {props.foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint', errors: [ { message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 25 }, { message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 39 } ] }, { code: [ 'type Props = {', ' foo?: string', '};', 'function Hello(props: Props) {', ' return <div>Hello {props.foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 2, column: 3 }] }, { code: [ 'const Hello = (props: { foo?: string }) => {', ' return <div>Hello {props.foo}</div>;', '};' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 25 }] }, { code: [ 'const Hello = (props: { foo?: string, bar?: string }) => {', ' return <div>Hello {props.foo}</div>;', '};', 'Hello.defaultProps = { foo: "foo" };' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 39 }] }, { code: [ 'const Hello = function(props: { foo?: string }) {', ' return <div>Hello {props.foo}</div>;', '};' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 33 }] }, { code: [ 'const Hello = function(props: { foo?: string, bar?: string }) {', ' return <div>Hello {props.foo}</div>;', '};', 'Hello.defaultProps = { foo: "foo" };' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 47 }] }, { code: [ 'type Props = {', ' foo?: string', '};', 'function Hello(props: Props) {', ' return <div>Hello {props.foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 2, column: 3 }] }, { code: [ 'type Props = {', ' foo?: string,', ' bar?: string', '};', 'function Hello(props: Props) {', ' return <div>Hello {props.foo}</div>;', '}', 'Hello.defaultProps = { foo: "foo" };' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 3, column: 3 }] }, // UnionType { code: [ 'function Hello(props: { one?: string } | { two?: string }) {', ' return <div>Hello {props.foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint', errors: [ { message: 'propType "one" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 25 }, { message: 'propType "two" is not required, but has no corresponding defaultProps declaration.', line: 1, column: 44 } ] }, { code: [ 'type Props = {', ' foo: string,', ' bar?: string', '};', 'type Props2 = {', ' foo: string,', ' baz?: string', '}', 'function Hello(props: Props | Props2) {', ' return <div>Hello {props.foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint', errors: [ { message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.', line: 3, column: 3 }, { message: 'propType "baz" is not required, but has no corresponding defaultProps declaration.', line: 7, column: 3 } ] }, { code: [ 'type Props = {', ' foo: string,', ' bar?: string', '};', 'type Props2 = {', ' foo: string,', ' baz?: string', '}', 'function Hello(props: Props | Props2) {', ' return <div>Hello {props.foo}</div>;', '}', 'Hello.defaultProps = {', ' bar: "bar"', '};' ].join('\n'), parser: 'babel-eslint', errors: [ { message: 'propType "baz" is not required, but has no corresponding defaultProps declaration.', line: 7, column: 3 } ] }, { code: [ 'type HelloProps = {', ' two?: string,', ' three: string', '};', 'function Hello(props: { one?: string } | HelloProps) {', ' return <div>Hello {props.foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint', errors: [ { message: 'propType "two" is not required, but has no corresponding defaultProps declaration.', line: 2, column: 3 }, { message: 'propType "one" is not required, but has no corresponding defaultProps declaration.', line: 5, column: 25 } ] }, { code: [ 'type HelloProps = {', ' two?: string,', ' three: string', '};', 'function Hello(props: ExternalProps | HelloProps) {', ' return <div>Hello {props.foo}</div>;', '}' ].join('\n'), parser: 'babel-eslint', errors: [ { message: 'propType "two" is not required, but has no corresponding defaultProps declaration.', line: 2, column: 3 } ] }, { code: [ 'class Hello extends React.Component {', ' static propTypes = {', ' foo: PropTypes.string', ' };', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [ { message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.', line: 3, column: 5 } ] }, { code: [ 'class Hello extends React.Component {', ' static get propTypes() {', ' return {', ' name: PropTypes.string', ' };', ' }', ' static defaultProps() {', ' return {', ' name: \'John\'', ' };', ' }', ' render() {', ' return <div>Hello {this.props.name}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "name" is not required, but has no corresponding defaultProps declaration.' }] }, { code: [ 'class Hello extends React.Component {', ' static get propTypes() {', ' return {', ' \'first-name\': PropTypes.string', ' };', ' }', ' render() {', ' return <div>Hello {this.props[\'first-name\']}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "first-name" is not required, but has no corresponding defaultProps declaration.' }] }, { code: [ 'class Hello extends React.Component {', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}', 'Hello.propTypes = {', ' foo: PropTypes.string.isRequired', '};', 'Hello.defaultProps = {', ' foo: \'bar\'', '};' ].join('\n'), options: [{forbidDefaultForRequired: true}], errors: [{ message: 'propType "foo" is required and should not have a defaultProps declaration.' }] }, { code: [ 'function Hello(props) {', ' return <div>Hello {props.foo}</div>;', '}', 'Hello.propTypes = {', ' foo: PropTypes.string.isRequired', '};', 'Hello.defaultProps = {', ' foo: \'bar\'', '};' ].join('\n'), options: [{forbidDefaultForRequired: true}], errors: [{ message: 'propType "foo" is required and should not have a defaultProps declaration.' }] }, { code: [ 'const Hello = (props) => {', ' return <div>Hello {props.foo}</div>;', '};', 'Hello.propTypes = {', ' foo: PropTypes.string.isRequired', '};', 'Hello.defaultProps = {', ' foo: \'bar\'', '};' ].join('\n'), options: [{forbidDefaultForRequired: true}], errors: [{ message: 'propType "foo" is required and should not have a defaultProps declaration.' }] }, { code: [ 'class Hello extends React.Component {', ' static propTypes = {', ' foo: PropTypes.string.isRequired', ' }', ' static defaultProps = {', ' foo: \'bar\'', ' }', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', options: [{forbidDefaultForRequired: true}], errors: [{ message: 'propType "foo" is required and should not have a defaultProps declaration.' }] }, { code: [ 'class Hello extends React.Component {', ' static get propTypes () {', ' return {', ' foo: PropTypes.string.isRequired', ' };', ' }', ' static get defaultProps() {', ' return {', ' foo: \'bar\'', ' };', ' }', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), options: [{forbidDefaultForRequired: true}], errors: [{ message: 'propType "foo" is required and should not have a defaultProps declaration.' }] }, // test support for React PropTypes as Component's class generic { code: [ 'type HelloProps = {', ' foo: string,', ' bar?: string', '};', 'class Hello extends React.Component<HelloProps> {', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.' }] }, { code: [ 'type HelloProps = {', ' foo: string,', ' bar?: string', '};', 'class Hello extends Component<HelloProps> {', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.' }] }, { code: [ 'type HelloProps = {', ' foo: string,', ' bar?: string', '};', 'type HelloState = {', ' dummyState: string', '};', 'class Hello extends Component<HelloProps, HelloState> {', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.' }] }, { code: [ 'type HelloProps = {', ' foo?: string,', ' bar?: string', '};', 'class Hello extends Component<HelloProps> {', ' render() {', ' return <div>Hello {this.props.foo}</div>;', ' }', '}' ].join('\n'), parser: 'babel-eslint', errors: [{ message: 'propType "foo" is not required, but has no corresponding defaultProps declaration.' }, { message: 'propType "bar" is not required, but has no corresponding defaultProps declaration.' }] }, { code: ` type Props = { +name?: string, }; function Hello(props: Props) { return <div>Hello {props.name}</div>; } `, parser: 'babel-eslint', errors: [{ message: 'propType "name" is not required, but has no corresponding defaultProps declaration.' }] } ] }); import { addClass, getClass } from '@/util/element' import Collapse from './collapse' export default class Card { constructor (data, { templateFunction, event }) { this.data = data this.templateFunction = templateFunction this.event = event this.createFragment() } createFragment () { const oFragment = document.createDocumentFragment() const oWrapper = document.createElement('div') addClass(oWrapper, getClass('card-wrapper')) // card-header const oHeader = document.createElement('div') addClass(oHeader, getClass('card-header')) oWrapper.appendChild(oHeader) // card-body const oBody = document.createElement('div') addClass(oBody, getClass('card-body')) oWrapper.appendChild(oBody) this._renderBaseInfo(oBody) this._renderCollapse(oBody) oFragment.append(oWrapper) this.wrapper = oWrapper this.fragment = oFragment } _renderBaseInfo (oBody) { const hostEL = document.createElement('h2') hostEL.innerText = this.data.operationName hostEL.classList.add('host') oBody.appendChild(hostEL) const oDiv = document.createElement('div') oDiv.innerHTML = this.templateFunction(this.data) addClass(oDiv, getClass('info-list')) oBody.appendChild(oDiv) } _renderCollapse (oBody) { const collapseContainer = document.createElement('div') collapseContainer.classList.add(getClass('collapse')) oBody.appendChild(collapseContainer) const { tags, process, logs } = this.data const instances = [] if (tags && tags.length > 0) { const tagsCol = document.createElement('div') tagsCol.classList.add('collapse-tags') this.tagsColInstance = new Collapse(tagsCol, { title: 'Tags', template: this._getTagsTemplate(), event: this.event, }) instances.push(tagsCol) } if (process) { const processCol = document.createElement('div') processCol.classList.add('collapse-process') this.processColInsance = new Collapse(processCol, { title: 'Process', template: this._getProcessTemplate(), event: this.event, }) instances.push(processCol) } if (logs && logs.length > 0) { const logsCol = document.createElement('div') logsCol.classList.add('collapse-logs') this.logColInstance = new Collapse(logsCol, { title: 'Logs', event: this.event, customBodyFunc: (bodyEle) => { this._getLogsTemplate(bodyEle) }, }) instances.push(logsCol) } instances.forEach((el) => { el.classList.add('collapse-item') collapseContainer.appendChild(el) }) } _getLogsTemplate (wrapper) { this.collapseList = [] const { logs } = this.data if (!logs || logs.length === 0) return false return (logs || []).forEach((item) => { const { timestamp, fields } = item const el = document.createElement('div') el.classList.add('log-item') wrapper.appendChild(el) this.collapseList.push(new Collapse(el, { title: `${timestamp}`, template: this._getLogsFieldsTemplate(fields), event: this.event, })) }) } _getLogsFieldsTemplate (fields) { return ` <table> <tbody> ${fields.map(({ key, value }) => `<tr><td class="label-td">${key}</td><td class="value-td">${value}</td></tr>`).join('')} </tbody> </table> ` } _getTagsTemplate () { const { tags } = this.data if (!tags || tags.length === 0) return false return ` <table> <tbody> ${tags.map(({ key, value }) => `<tr><td class="label-td">${key}</td><td class="value-td">${value}</td></tr>`).join('')} </tbody> </table> ` } _getProcessTemplate () { const { process } = this.data if (!process) return false const { tags } = process if (!tags || tags.length === 0) return false return ` <table> <tbody> ${tags.map(({ key, value }) => `<tr><td class="label-td">${key}</td><td class="value-td">${value}</td></tr>`).join('')} </tbody> </table> ` } destory () { this.event = null this.data = null this.wrapper.parentNode.removeChild(this.wrapper) this.tagsColInstance && this.tagsColInstance.destory() this.processColInsance && this.processColInsance.destory() this.logColInstance && this.logColInstance.destory() Array.isArray(this.collapseList) && this.collapseList.forEach((el) => { el.destory() }) this.collapseList = [] } } <reponame>fossabot/hull-shortener import updatePixels from "./update-pixels"; import { smartNotifierHandler } from "hull/lib/utils"; const handler = smartNotifierHandler({ handlers: { "ship:update": ({ ship, client }) => { updatePixels({ ship, client }); return Promise.resolve({}); } } }); export default handler; exports.up = function (knex, Promise) { console.log(process.env); return knex.schema .createTable('orders', function (table) { table.increments('id'); table.integer('pick_up_time'); table.timestamp('time_stamp').defaultTo(knex.fn.now()); table.boolean('pending'); }).createTable('products', function (table) { table.increments('id'); table.varchar('name'); table.varchar('description'); table.float('price'); table.string('img'); }).createTable('product_orders', function (table) { table.increments('id'); table.integer('order_id').references('orders.id').onDelete('CASCADE'); table.integer('product_id').references('products.id').onDelete('CASCADE'); table.integer('quantity'); }).createTable('guests', function (table) { table.increments('id'); table.varchar('name'); table.varchar('phone'); table.integer('order_id').references('orders.id').onDelete('CASCADE'); }).createTable('restaurants', function (table) { table.increments('id'); table.varchar('password'); }); }; exports.down = function (knex, Promise) { return Promise.all([ knex.raw('DROP TABLE products CASCADE'), knex.raw('DROP TABLE product_orders CASCADE'), knex.raw('DROP TABLE guests CASCADE'), knex.raw('DROP TABLE restaurants CASCADE'), knex.raw('DROP TABLE orders CASCADE'), ]) }; <reponame>cube-modules/bace !(function(){var ace = window.___ace___; ace.define("ace/snippets/protobuf",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = ""; exports.scope = "protobuf"; }); })(); <gh_stars>0 const exampleSet = new Set([1, 1, 1, 1, 2, 2, 2, 2]); exampleSet.add(5); exampleSet.add(5).add(17); console.log(exampleSet.delete(5)); console.log(exampleSet.has(5)); console.log(exampleSet); exampleSet.clear(); console.log(exampleSet.size);// Crea l'store de Reduce // Guarda l'estat actual del nostre sistema import {createStore} from 'redux'; // Import del dispathcer (reducer) de la nostra apliació import reducer from './reducers/reducer'; // Creem el reducer const store = createStore(reducer); export default store; <filename>examples/anime/script.js var bounceUp = anime({ autoplay: false, //We don't want to immediately start the animation targets: '#ball', //target the div '#ball' translateY: { value: ['160px', '0px'], //When bouncing up, start at 160px and end at 0px duration: 575, easing: 'easeOutQuad', }, complete: function(){ bounceDown.play() }, //Function encapsulation is necessary, otherwise we run into not defined error }); var bounceDown = anime({ autoplay: false, //See similar comments above targets: '#ball', translateY: { value: ['0px', '160px'], //When bouncing down, start at 0px and end at 160px duration: 575, easing: 'easeInQuad', }, complete: function(){ bounceUp.play() }, //After we bounce down, start the bounce up animation }); bounceDown.play(); //Start the animation!<reponame>budRich/LinkHints<gh_stars>1-10 // @flow strict-local import * as React from "preact"; import config from "../project.config"; import KeyboardShortcut, { shortcuts } from "./KeyboardShortcuts"; import Page from "./Page"; import render from "./render"; import Scripts from "./Scripts"; import ShortcutsSummary from "./ShortcutsSummary"; const STEPS = [ { title: "The basics", next: "Next step", content: ( <> <p> {shortcuts.EnterHintsMode_Click} is the main keyboard shortcut. Use it to click things. </p> <p className="large"> Try it! Press the shortcut, and then type the letter <dfn>(hint)</dfn>{" "} that appears on the “Next step” button. </p> <p>Press {shortcuts.ExitHintsMode} to cancel.</p> <Info title="Having trouble?"> <p> If your keyboard layout does not have the{" "} <KeyboardShortcut press="J" /> character, you need to flip an option. </p> <p> Click the Link Hints toolbar button{" "} <span className="ToolbarButton" /> and then “Options.” Check “I use multiple keyboard layouts.” </p> <p> Alternatively, you can change the keyboard shortcuts to ones that fit your keyboard better. </p> </Info> </> ), }, { title: "Good to know", next: "Got it", content: ( <> <p> The Link Hints toolbar button looks like this:{" "} <span className="ToolbarButton" /> </p> <p> The toolbar button provides some handy info and a way to open the Options page. </p> <br /> <p> On some pages, the toolbar button is faded:{" "} <span className="ToolbarButtonDisabled" /> </p> <p>This means that Link Hints cannot be used on the page.</p> <p> Browser extensions are not allowed to run on some pages, such as Chrome’s and Firefox’s extension stores, the New Tab page and internal settings pages. </p> </> ), }, { title: "Opening links in tabs", next: "Continue", content: ( <> <p> {shortcuts.EnterHintsMode_BackgroundTab} lets you open a link in a new tab. </p> <p> {shortcuts.EnterHintsMode_ForegroundTab} also switches to the new tab. </p> <p>Try the shortcuts on these links to get a feel for it:</p> <ul> <li> <a href="https://example.com/">example.com</a> </li> <li> <a href="https://www.mozilla.org/">mozilla.org</a> </li> </ul> </> ), }, { title: "Filter by text", next: "Alright", content: ( <> <p> The default hint characters are: <code>fjdkslaurieowhgmvcn</code>. Type other characters to <dfn>filter by text.</dfn> </p> <p> Try it! Open the below sections by typing part of their text instead of the letters in the yellow boxes <dfn>(hints)</dfn>. </p> <details> <summary>1984</summary> <p> <cite>1984</cite> is a novel by <NAME>. </p> </details> <details> <summary>2001</summary> <p> <cite>2001: A Space Odessey</cite> is a film by <NAME>. </p> </details> <p>This is especially useful for tiny pagination links:</p> <Pagination /> <p> If there’s no unique match, press {shortcuts.ActivateHint} to activate the green hint, or type some hint characters at the end. </p> </> ), }, { title: "Filter by text – letters", next: "Onwards", content: ( <> <p> Hints are <em>displayed</em> uppercase because it looks nicer, but they are all lowercase: <code>fjdkslaurieowhgmvcn</code> </p> <p> <em>Filtering by text</em> is case <strong>in</strong>sensitive. This means that you can hold <KeyboardShortcut shift /> while typing to filter by letters. </p> <p className="Choices"> <a tabIndex="-1">iPhone</a> <a tabIndex="-1">iPad</a> <a tabIndex="-1">iMac</a> </p> <Info title="Tip!"> <p> Change the hint characters to uppercase if you prefer to primarily{" "} <em>filter by text.</em> </p> <p> You can also disable auto-activation of unique matches, requiring{" "} {shortcuts.ActivateHint} to be pressed. </p> </Info> </> ), }, { title: "Click many things", next: "Keep going", content: ( <> <p> {shortcuts.EnterHintsMode_ManyClick} lets you click many things in one go. </p> <p>Check these boxes. Press {shortcuts.ExitHintsMode} when done.</p> <p className="Salad"> <input type="checkbox" id="lettuce" /> <label htmlFor="lettuce">🥬 Lettuce</label> <input type="checkbox" id="cucumber" /> <label htmlFor="cucumber">🥒 Cucumber</label> <input type="checkbox" id="tomato" /> <label htmlFor="tomato">🍅 Tomato</label> <output> 🥗 <strong>Enjoy your salad!</strong>{" "} </output> </p> <br /> <p>{shortcuts.EnterHintsMode_ManyTab} lets you open multiple links.</p> <ul> <li> <a href="https://example.com/">example.com</a> </li> <li> <a href="https://www.mozilla.org/">mozilla.org</a> </li> <li> <a href="https://www.wikipedia.org/">wikipedia.org</a> </li> </ul> </> ), }, { title: "Selecting text", next: "Almost there", content: ( <> <p> {shortcuts.EnterHintsMode_Select} lets you select elements. This is useful for copying text and using the context menu. </p> <p> When text is selected, you can use the standard keyboard shortcuts for adjusting the selection, such as{" "} <KeyboardShortcut shift press="ArrowRight" />. And of course{" "} <KeyboardShortcut ctrl={{ mac: "cmd" }} press="C" /> to copy. </p> <p>Link Hints adds two extra shortcuts:</p> <ul> <li> {shortcuts.ReverseSelection} swaps which end of a text selection to work on. This lets you extend the selection not only to the right, but also to the left. Try selecting{" "} <KeyboardShortcut press="ArrowUp" /> on this line, and then going in both directions! </li> <li> {shortcuts.Escape} unselects. This lets you get rid of text selection, unfocus text fields and cancel hinting. </li> </ul> <p> Finally, you can hold {shortcuts.Alt} while activating a hint (typing the last character) to copy its text or link address! </p> </> ), }, { title: "Tips & Tricks", next: "Finish", content: ( <> <p> <KeyboardShortcut press="F6" /> can be pressed once or twice to bring back focus to the web page area of the browser. Due to browser extension limitations, Link Hint’s shortcuts only work when the page has focus. </p> <p> Hold {shortcuts.Alt} while activating a hint (typing the last character) to force links to open in a new tab. </p> <p> Too many hints near each other? Press {shortcuts.RotateHintsForward}{" "} and {shortcuts.RotateHintsBackward} to rotate which hint is on top. </p> <p> Do the hints cover too much of a group of small links? Press{" "} {shortcuts.TogglePeek} to peek through them. </p> <p> Finally, {shortcuts.RefreshHints} refreshes the hints. Useful if the page changes while you use hints. </p> <p> Here are the tiny pagination links again, for trying out rotation and peeking: </p> <Pagination /> </> ), }, { title: "The End", next: { href: config.docs.root, text: "Home", }, content: ( <> <p>Well done! 🎉</p> <p>Recap:</p> <ShortcutsSummary /> <p> Check out the Options page to see <em>all</em> shortcuts, or if you feel like tweaking something. </p> </> ), }, ]; export default () => render( <Page title="Link Hints Tutorial" description="A tutorial for the Link Hints browser extension." css={config.docs.tutorialCss.output} > <nav> <a href={config.docs.root}>⬅️ Home</a> </nav> <main className={`${config.meta.slug}Tutorial`}> <Intro /> {STEPS.map((step, index) => { const num = index + 1; return ( <section key={num} id={`step-${num}`} className="Step"> <a href={`#step-${num}`} title={`Step ${num}`} /> <div className="Step-inner"> <h2>{step.title}</h2> {step.content} {typeof step.next === "string" ? ( <a href={`#step-${num + 1}`} className="Button"> {step.next} </a> ) : ( <a href={step.next.href} className="Button"> {step.next.text} </a> )} </div> </section> ); })} <div className="Cover" /> </main> <Scripts macifyKbd autoCloseDetails /> </Page> ); function Intro() { return ( <section className="Intro"> <h1>Link Hints Tutorial</h1> <section className="not-installed"> <p> <strong>You don’t seem to have installed Link Hints yet.</strong> </p> <p> You can still go through the tutorial, but you’ll get more out of it by installing Link Hints first. </p> </section> <section className="installed"> <p> <strong>Thank you for using Link Hints!</strong> </p> <p>Go through this short tutorial to learn how to use Link Hints.</p> </section> <section className="small"> <p> <strong> It’s recommended to use a bigger screen for the tutorial. </strong> </p> </section> <a href="#step-1" className="Button"> Get started </a> </section> ); } function Info({ title, children }: { title: string, children: React.Node }) { return ( <div className="Info"> <h3>ℹ️ {title}</h3> {children} </div> ); } function Pagination() { return ( <p className="Pagination"> {Array.from({ length: 12 }, (_, index) => ( <a tabIndex="-1">{index + 1}</a> ))} </p> ); } module.exports = { env: { browser: true, 'jest/globals': true, node: true, }, extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:import/errors', 'plugin:import/warnings', 'plugin:import/typescript', 'esnext', 'plugin:promise/recommended', 'plugin:unicorn/recommended', 'plugin:prettier/recommended', ], overrides: [ { files: ['*.js'], rules: { 'import/no-commonjs': 0, 'unicorn/prefer-module': 0, }, }, { files: ['*.test.ts', '*.test.tsx'], plugins: ['@typescript-eslint', 'jest'], }, { files: ['*.test.js'], plugins: ['jest'], }, ], parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2021, sourceType: 'module', }, plugins: ['@typescript-eslint', 'json-format', 'sort-keys-fix'], rules: { '@typescript-eslint/array-type': [ 'warn', { default: 'array-simple', }, ], '@typescript-eslint/consistent-type-assertions': [ 'error', { assertionStyle: 'as', objectLiteralTypeAssertions: 'allow', }, ], '@typescript-eslint/consistent-type-imports': 2, '@typescript-eslint/explicit-function-return-type': 0, '@typescript-eslint/explicit-module-boundary-types': 0, '@typescript-eslint/method-signature-style': 'error', '@typescript-eslint/no-duplicate-imports': 2, '@typescript-eslint/no-unused-vars': [ 'error', { args: 'after-used', argsIgnorePattern: '^_', ignoreRestSiblings: true, vars: 'all', varsIgnorePattern: '^_', }, ], 'import/newline-after-import': ['error', { count: 1 }], 'import/no-cycle': 2, 'import/no-default-export': 1, 'import/no-nodejs-modules': 0, 'import/order': [ 'error', { alphabetize: { caseInsensitive: true, order: 'asc', }, groups: ['builtin', 'external', 'parent', 'sibling', 'index', 'object'], 'newlines-between': 'always', }, ], 'import/prefer-default-export': 0, 'no-console': 'error', 'no-duplicate-imports': 'off', 'no-empty-function': 0, 'no-undef': 0, 'no-unused-vars': 0, 'no-use-before-define': 0, 'padding-line-between-statements': [ 'error', { blankLine: 'always', next: 'return', prev: '*' }, ], 'sort-keys-fix/sort-keys-fix': [ 'error', 'asc', { caseSensitive: true, natural: false }, ], 'unicorn/catch-error-name': [ 'error', { name: 'exception', }, ], 'unicorn/no-array-reduce': [ 'error', { allowSimpleOperations: true, }, ], 'unicorn/prefer-node-protocol': 0, 'unicorn/prevent-abbreviations': [ 'error', { replacements: { props: false, }, }, ], }, settings: { 'import/resolver': { typescript: {}, // this loads <rootdir>/tsconfig.json to eslint }, react: { version: 'detect', }, }, }; /** * @desc: 单向链表 * @author: tankm * @since: 2021-05-23 23:03:20 */ // import CreateNode from './common'; /** * 单向链表 */ function LinkList() { /** * 链表头部指针 */ this.head = null; /** * 链表长度 */ this.length = 0; } /** * 链表子节点构造函数 * @param {any} data */ function CreateNode(data) { /** * 链表节点的数据 */ this.data = data; /** * 链表节点的下一个节点的指针 */ this.next = null; } /** * 增加链表子节点 * @param {any} data */ function append(data) { const node = new CreateNode(data); if (!this.head) { this.head = node; this.length += 1; } else { let point = this.head; while (point.next) { point = point.next; } point.next = node; this.length += 1; } } /** * 插入链表子节点 * @param {any} data * @param {number} position */ function insert(data, position) { if (position > this.length || position < 0) return false; const node = new CreateNode(data); let current = this.head; if (position === 0) { this.head = node; node.next = current; } else { let prev = null; let index = 0; while (index <= position) { if (index === position) { prev.next = node; node.next = current; this.length += 1; } else { prev = current; current = current.next; } index += 1; } } } /** * 根据节点值移除链表子节点 * @param {any} data * @returns {any} */ function remove(data) { // 链表为空 if (!this.head) return null; // 链表第一项即是目标值 if (this.head.data === data) { const temp = this.head; this.head = this.head.next; return temp; } let prev = this.head; let current = this.head.next; while(current) { if (current.data === data) { prev.next = current.next; this.length -= 1; return current; } else { prev = current; current = current.next; } } return current; } /** * 根据index移除链表子节点 * @param {number} position * @returns {any} */ function removeAt(position) { if (position < 0 || position >= this.length) return null; if (position === 0) { const temp = this.head; this.head = this.head.next; return temp; } let index = 1; let prev = this.head; let current = this.head.next; while(index <= position) { if (position === index) { prev.next = current.next; this.length -= 1; return current; } prev = current; current = current.next; index += 1; } } /** * 获取链表子节点 * @param {number} position * @returns {number} */ function getNode(position) { let result = null; if (position < 0 || position >= this.length) return result; if (position === 0) { result = this.head; } else { let index = 0; let current = this.head; while (index <= position) { if (index === position) { result = current; } current = current.next; index += 1; } } return result; } /** * 更新链表子节点 * @param {number} position * @param {any} data */ function update(position, data) { const target = this.getNode(position); target.data = data; } /** * 链表的indexOf方法 * @param {any} data * @returns {number} */ function indexOf(data) { let index = 0; let current = this.head; while (current) { if (current.data === data) { return index; } current = current.next; index += 1; } return -1; } /** * 链表序列化 * @returns {string} */ function toString() { let str = ""; let current = this.head; while (current) { str += `${current.data} `; current = current.next; } return str; } LinkList.prototype = { ...LinkList.prototype, append, insert, remove, removeAt, getNode, update, indexOf, toString, }; const linkList = new LinkList(); linkList.append("abc"); linkList.append("def"); linkList.append("ghi"); linkList.append("jkl"); console.log(linkList.length); console.log(linkList.toString()); linkList.insert("xyz", 2); console.log(linkList.length); console.log(linkList.toString()); console.log(linkList.getNode(1)); console.log(linkList.indexOf("xyz")); linkList.update(1, "uvw") console.log(linkList.toString()); console.log(linkList.remove('uvw')); console.log(linkList.removeAt(3)); console.log(linkList.toString()); <filename>build/webpack.demo.config.js<gh_stars>1-10 const path = require("path"); const merge = require("webpack-merge"); const baseWebpackConfig = require("./webpack.base.config"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const HtmlWebpackStringReplacePlugin = require("html-webpack-string-replace-plugin"); const CleanWebpackPlugin = require("clean-webpack-plugin"); module.exports = merge(baseWebpackConfig, { entry: "./docs/demo.js", output: { path: path.resolve("./", "docs"), filename: "bundle-[contenthash].js" }, optimization: { minimizer: [ new UglifyJsPlugin({}), new OptimizeCssAssetsPlugin({}) ] }, module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader }, { loader: "css-loader" } ] } ] }, plugins: [ new CleanWebpackPlugin(["docs/bundle-*"], {root: path.dirname(__dirname)}), new MiniCssExtractPlugin({ filename: "bundle-[contenthash].css" }), new HtmlWebpackPlugin({ template: "docs/working.html", excludeChunks: ["demo.js"] // Already included in template. }), new HtmlWebpackStringReplacePlugin({ "\t<script src=\"built-bundle.js\"></script>\n\n": "" }) ] }); <reponame>Adrinalin4ik/wowser<gh_stars>1-10 import LiquidType from '../../pipeline/liquid/type'; import ColliderManager from './collider-manager'; class TerrainManager { constructor(map, zeropoint) { this.map = map; this.view = map.exterior; this.zeropoint = zeropoint; } loadChunk(_index, terrain) { this.view.add(terrain); ColliderManager.collidableMeshList.set(terrain.uuid, terrain); terrain.updateMatrix(); } unloadChunk(_index, terrain) { this.view.remove(terrain); terrain.dispose(); ColliderManager.collidableMeshList.delete(terrain.uuid); } animate(delta, camera, cameraMoved) { LiquidType.materials.forEach((material) => { material.animate(delta, camera, cameraMoved); }); } } export default TerrainManager; <reponame>RinMinase/anidb-angularjs const { readdirSync } = require("fs"); const { join } = require("path"); const { registry, task, series } = require("gulp"); const log = require("fancy-log"); const fwdRef = require("undertaker-forward-reference"); registry(fwdRef()); /** * This will load all js files to load all gulp tasks */ readdirSync("./src/assets/gulp") .filter((file) => (/\.(js)$/i).test(file)) .map((file) => { require("./src/assets/gulp/" + file); //eslint-disable-line }); task("default", series("build")); exports.paths = { root: join(__dirname), src: "src", dist: "dist", www: "www", tmp: ".tmp", }; exports.errorHandler = function(title) { return function(err) { log(`[ ${title} ]`, err.toString()); this.emit("end"); }; }; const bestmovedb = require('bestmovedb'); const fs = require('fs'); const baseSerializer = require('./base-serializer'); const baseOptimizer = require('./optimization/base-optimizer'); const baseIterator = require('./base-iterator'); const converter = require('../converter'); var base = {m: '', n: 0, c: 'b', t: 'wb'}; var filename = 'base.json'; module.exports.getFen = ({fen, depth}) => { const fenData = bestmovedb.getFen({fen, depth}); if(fenData && !fenData.sp) { fenData.sp = fenData.score * 100; } return fenData; }; module.exports.getFenBase = () => bestmovedb.toJSON(); let isSaving = false; module.exports.saveBaseSync = () => { if(isSaving) return; isSaving = true; try { const content = baseSerializer.stringify(base, true); fs.writeFileSync(filename, content); } catch(err) { console.error(err); } finally { isSaving = false; } }; module.exports.saveBase = () => { if(isSaving) return Promise.resolve(); return new Promise(resolve => { this.saveBaseSync(); resolve(); }).catch(console.error); }; var createChildPositionObject = function(parentObject, childMove, isBest) { var n; var c; if (parentObject.c === 'w') { n = parentObject.n; c = 'b'; } else { n = parentObject.n + 1; c = 'w'; } var newChildObject = {m: childMove, n: n, c: c}; if (!parentObject.s) { parentObject.s = []; } if (isBest) { parentObject.s.unshift(newChildObject); } else { parentObject.s.push(newChildObject); } return newChildObject; }; var improveEvaluation = function(positionObject, evaluationObject) { if (!positionObject.e || (evaluationObject.d > positionObject.e.d)) { positionObject.e = evaluationObject; } }; module.exports.addToBase = (moves, bestMove, score, depth) => { this.addToJsonBase(moves, bestMove, score, depth); const fen = converter.moves2fen(moves); bestmovedb.add({ fen, bestMove, score, depth }); }; module.exports.addToJsonBase = function(moves, bestAnswer, scoreValue, depth) { var evaluationObject = {v: scoreValue, d: depth}; var positionObject = base; var parent; for (var i = 0; i < moves.length; i++) { parent = positionObject; positionObject = baseIterator.findSubPositionObject(parent, moves[i]); if (!positionObject) { positionObject = createChildPositionObject(parent, moves[i]); } } if(!positionObject.e || positionObject.e.d <= evaluationObject.d) { improveEvaluation(positionObject, evaluationObject); parent = positionObject; var index; var subPositionObject = (function() { if (positionObject && positionObject.s) { let l = positionObject.s.length; for (index = 0; index < l; index++) { if (positionObject.s[index].m === bestAnswer) { return positionObject.s[index]; } } } return null; })(); if (subPositionObject) { positionObject.s.splice(index, 1); positionObject.s.unshift(subPositionObject); } else { createChildPositionObject(parent, bestAnswer, true); } this.saveBase(); } }; module.exports.getBase = function() { return base; }; module.exports.index = () => { console.log('base index start'); return new Promise((resolve, reject) => { setTimeout(() => { try { converter.json2fenbase(base, bestmovedb); } catch (err) { reject(err); } console.log('base index finished'); resolve(); }, 0); }).catch(err => console.error(err)); }; module.exports.readBase = function() { try { let baseFileContent = fs.readFileSync(filename); base = baseSerializer.parse(baseFileContent); } catch (err) { console.error('Could not read ' + filename + ': ' + err); } }; module.exports.getBaseAsString = function() { return baseSerializer.stringify(base); }; module.exports.optimize = function({settings}) { return baseOptimizer.optimize({base, baseIterator, settings}); }; <reponame>Johnys/k123<filename>frontend/src/app/components/people/list/people.list.component.js import template from './people.list.html'; import controller from './people.list.controller'; const PeopleList = { restrict: 'E', scope: {}, template, controller, controllerAs: 'vm', bindToController: true, }; export default PeopleList; <filename>model/enemy.js var util = require("util"), CONST = require('../game-constants'), Actor = require("./actor").Actor; function Enemy(startX, startY, sides, color, age, id) { Actor.call(this, startX, startY, color); this.age = age || Math.floor(Math.random() * 128); this.xVelocity = 0; this.yVelocity = 1.5; //life changes number of polygon sides 3 is minimum poly size this.sides = sides || 3; this.lives = this.sides - 2; this.id = id || this.born.toString(36); this.width = 32; this.height = 32; } Enemy.prototype = new Actor(); Enemy.prototype.inBounds = function() { return this.x >= 0 && this.x <= CONST.CANVAS_WIDTH && this.y >= 0 && this.y <= CONST.CANVAS_HEIGHT; }; Enemy.prototype.draw = function(sides) { canvas.beginPath(); Polygon(canvas, this.x + (this.width/2) ,this.y +(this.height/2), this.width/2 , this.sides,-Math.PI/2); canvas.strokeStyle = this.color; canvas.stroke(); }; Enemy.prototype.update = function(transX, transY) { this.x += this.xVelocity; this.y += this.yVelocity; // this.x += transX; // this.y += transY; this.xVelocity = 3 * Math.sin(this.age * Math.PI / 64); this.age++; this.active = this.active && this.inBounds(); }; Enemy.prototype.getSides = function() { return this.sides; }; Enemy.prototype.getAge = function() { return this.age; }; Enemy.prototype.setlives = function(newLives) { this.lives = newLives; this.sides = newLives - 2; }; Enemy.prototype.removeLife = function() { this.lives--; this.sides--; if (this.lives == 0){ this.explode(); } util.log("damage enemy :" + this.id + " lives: " + this.lives + " sides: " + this.sides); }; Enemy.prototype.explode = function() { this.active = false; this.diedAt = Date.now(); util.log("Enemy destroyed: " + this.id); // socket.emit("damage enemy", { // id: this.id // }); }; // Enemy.prototype.takeDamage = function(damage) { // this.life --; // this.sides --; // if (this.life == 0){ // this.explode(); // } else { // socket.emit("damage enemy", { // id: this.id // }); // } // }; // Enemy.prototype.damage = function(damage) { // this.life --; // this.sides --; // if (this.life === 0){ // this.explode(); // } // }; exports.Enemy = Enemy; import createConstants from './ConstantsCreator'; const REQUEST_CONSTANTS = [ 'SEND', 'SUCCEED', 'REJECTED', 'ERROR_ENCOUNTERED', ]; export default (module, submodule, additionalConstants = []) => createConstants( module, submodule, ...REQUEST_CONSTANTS, ...additionalConstants, ); <filename>src/components/home/home.js import './home.scss'; <gh_stars>0 import videoSites from '../utils/consts/videoSites' class Video { constructor(data) { this.id = data.id this.key = data.key this.name = data.name this.site = data.site this.size = data.size this.type = data.type this.fullVideoPath = null } generateFullVideoPath() { for (const site of Object.keys(videoSites)) if (videoSites[site].NAME === this.site) this.fullVideoPath = videoSites[site].URL + this.key } } export default Video const jwt = require('jsonwebtoken'); module.exports = function checkUser(req, res, next) { console.log('Checking user'); console.log(req.cookies); const token = req.cookies.nToken; const decodedToken = jwt.decode(token, { complete: true }) || {}; req.user = decodedToken.payload; console.log(req.user); next(); }; import initMixin from './init.js' import eventMixin from './event.js' import stateMixin from './state.js' import renderMixin from './render.js' function Ezay(options) { this._init(options); } initMixin(Ezay); eventMixin(Ezay); stateMixin(Ezay); renderMixin(Ezay); export default Ezay;<reponame>xiaojie96528/Dove import { h } from "vue" import EditIconButton from "../../components/button/EditIconButton.vue" import Details from "../../components/button/Details.vue" import { NButton, useMessage, NSpace } from "naive-ui"; export default () => { return [ { type: "selection", }, { title: "编号", key: "id", align: "center", }, { title: "名称", key: "name", align: "center", }, { title: "分类", key: "type", }, { title: "库存(份)", key: "stock", }, { title: "价格(元)", key: "price", }, { title: "简介", key: "introduce", }, { title: "操作", key: "actions", render(row) { let action = [ h( EditIconButton, { size: "small", onClick: () => { }, text: true }, null ), h( Details, { size: "small", onClick: () => { }, text: true }, null ), ]; return h(NSpace, {}, { default: () => action }); }, }, ]; };<reponame>truesrc/CodeceptJS const getParamNames = require('./utils').getParamNames; const fsPath = require('path'); const fileExists = require('./utils').fileExists; module.exports = function (hook, done, stage) { stage = stage || 'bootstrap'; if (typeof hook === 'string') { const pluginFile = fsPath.join(global.codecept_dir, hook); if (!fileExists(pluginFile)) { throw new Error(`Hook ${pluginFile} doesn't exist`); } const callable = require(pluginFile); if (typeof callable === 'function') { callSync(callable, done); return; } if (typeof callable === 'object' && callable[stage]) { callSync(callable[stage], done); return; } } else if (typeof hook === 'function') { callSync(hook, done); return; } // if async - call done if (done) done(); }; function callSync(callable, done) { if (isAsync(callable)) { callable(done); } else { callable(); if (done) done(); } } function isAsync(fn) { const params = getParamNames(fn); return params && params.length; } module.exports.get = function (req, res) { req.models.systemInformation.findOne(function (err, systemInformation) { if (err) { res.status(400).json({err: err.message}); } else { res.json({ total_users: systemInformation.total_users, total_active_users: systemInformation.total_active_users }); } }); };<filename>src/containers/court/CourtSagas.js /* * @flow */ import { DateTime } from 'luxon'; import { Constants } from 'lattice'; import { SearchApiActions, SearchApiSagas } from 'lattice-sagas'; import { fromJS, Map, Set } from 'immutable'; import { call, put, select, takeEvery } from '@redux-saga/core/effects'; import type { SequenceAction } from 'redux-reqseq'; import Logger from '../../utils/Logger'; import { getEntitySetIdFromApp } from '../../utils/AppUtils'; import { getEntityProperties } from '../../utils/DataUtils'; import { PSA_STATUSES } from '../../utils/consts/Consts'; import { APP_TYPES, PROPERTY_TYPES } from '../../utils/consts/DataModelConsts'; import { PSA_ASSOCIATION, PSA_NEIGHBOR } from '../../utils/consts/FrontEndStateConsts'; import { STATE } from '../../utils/consts/redux/SharedConsts'; import { APP_DATA } from '../../utils/consts/redux/AppConsts'; import { FILTER_PEOPLE_IDS_WITH_OPEN_PSAS, filterPeopleIdsWithOpenPSAs, } from './CourtActionFactory'; const LOG :Logger = new Logger('CourtSagas'); const { CONTACT_INFORMATION, HEARINGS, JUDGES, PEOPLE, PSA_SCORES, SUBSCRIPTION, STAFF } = APP_TYPES; const { DATE_TIME } = PROPERTY_TYPES; const { searchEntityNeighborsWithFilter } = SearchApiActions; const { searchEntityNeighborsWithFilterWorker } = SearchApiSagas; const { OPENLATTICE_ID_FQN } = Constants; const getApp = (state) => state.get(STATE.APP, Map()); const getOrgId = (state) => state.getIn([STATE.APP, APP_DATA.SELECTED_ORG_ID], ''); function* filterPeopleIdsWithOpenPSAsWorker(action :SequenceAction) :Generator<*, *, *> { try { yield put(filterPeopleIdsWithOpenPSAs.request(action.id)); const { personIds, hearingDateTime, personIdsToHearingIds } = action.value; let { scoresAsMap, hearingNeighborsById } = action.value; if (!scoresAsMap) { scoresAsMap = Map(); } let filteredPersonIds = Set(); let openPSAIds = Set(); let personIdsToOpenPSAIds = Map(); let personIdsWhoAreSubscribed = Set(); let peopleWithMultiplePSAs = Set(); const app = yield select(getApp); const orgId = yield select(getOrgId); const entitySetIdsToAppType = app.getIn([APP_DATA.ENTITY_SETS_BY_ORG, orgId]); const contactInformationEntitySetId = getEntitySetIdFromApp(app, CONTACT_INFORMATION); const subscriptionEntitySetId = getEntitySetIdFromApp(app, SUBSCRIPTION); const hearingsEntitySetId = getEntitySetIdFromApp(app, HEARINGS); const peopleEntitySetId = getEntitySetIdFromApp(app, PEOPLE); const psaEntitySetId = getEntitySetIdFromApp(app, PSA_SCORES); const staffEntitySetId = getEntitySetIdFromApp(app, STAFF); if (personIds.size) { let peopleNeighborsById = yield call( searchEntityNeighborsWithFilterWorker, searchEntityNeighborsWithFilter({ entitySetId: peopleEntitySetId, filter: { entityKeyIds: personIds.toJS(), sourceEntitySetIds: [psaEntitySetId, contactInformationEntitySetId], destinationEntitySetIds: [hearingsEntitySetId, subscriptionEntitySetId, contactInformationEntitySetId] } }) ); if (peopleNeighborsById.error) throw peopleNeighborsById.error; peopleNeighborsById = fromJS(peopleNeighborsById.data); peopleNeighborsById.entrySeq().forEach(([id, neighbors]) => { let hasValidHearing = false; let hasActiveSubscription = false; let hasPreferredContact = false; let mostCurrentPSA; let currentPSADateTime; let mostCurrentPSAEntityKeyId; let psaCount = 0; neighbors.forEach((neighbor) => { const entitySetId = neighbor.getIn([PSA_NEIGHBOR.ENTITY_SET, 'id']); const entityKeyId = neighbor.getIn([PSA_NEIGHBOR.DETAILS, OPENLATTICE_ID_FQN, 0]); let { [DATE_TIME]: entityDateTime } = getEntityProperties(neighbor, [DATE_TIME]); entityDateTime = DateTime.fromISO(entityDateTime); if (entitySetId === hearingsEntitySetId) { const hearingDateIsSame = hearingDateTime.hasSame(entityDateTime, 'day'); if (entityDateTime.isValid && hearingDateIsSame) { hasValidHearing = true; } } if (entitySetId === subscriptionEntitySetId) { const subscriptionIsActive = neighbor.getIn([PSA_NEIGHBOR.DETAILS, PROPERTY_TYPES.IS_ACTIVE, 0], false); if (subscriptionIsActive) { hasActiveSubscription = true; } } if (entitySetId === contactInformationEntitySetId) { const contactIsPreferred = neighbor.getIn([PSA_NEIGHBOR.DETAILS, PROPERTY_TYPES.IS_PREFERRED, 0], false); if (contactIsPreferred) { hasPreferredContact = true; } } else if (entitySetId === psaEntitySetId && neighbor.getIn([PSA_NEIGHBOR.DETAILS, PROPERTY_TYPES.STATUS, 0]) === PSA_STATUSES.OPEN) { if (!mostCurrentPSA || currentPSADateTime.valueOf() < entityDateTime.valueOf()) { mostCurrentPSA = neighbor; mostCurrentPSAEntityKeyId = entityKeyId; currentPSADateTime = entityDateTime; } psaCount += 1; openPSAIds = openPSAIds.add(entityKeyId); } }); if (hasActiveSubscription && hasPreferredContact) { personIdsWhoAreSubscribed = personIdsWhoAreSubscribed.add(id); } if (psaCount > 1) peopleWithMultiplePSAs = peopleWithMultiplePSAs.add(id); if (hasValidHearing && mostCurrentPSA) { const hearingId = personIdsToHearingIds.get(id); scoresAsMap = scoresAsMap.set( mostCurrentPSAEntityKeyId, mostCurrentPSA.get(PSA_NEIGHBOR.DETAILS) ); if (hearingId) { hearingNeighborsById = hearingNeighborsById.setIn( [hearingId, PSA_SCORES], mostCurrentPSA ); } filteredPersonIds = filteredPersonIds.add(id); personIdsToOpenPSAIds = personIdsToOpenPSAIds.set(id, mostCurrentPSAEntityKeyId); } }); } let psaIdToMostRecentEditDate = Map(); if (openPSAIds.size) { let psaNeighborsById = yield call( searchEntityNeighborsWithFilterWorker, searchEntityNeighborsWithFilter({ entitySetId: psaEntitySetId, filter: { entityKeyIds: openPSAIds.toJS(), sourceEntitySetIds: [peopleEntitySetId], destinationEntitySetIds: [staffEntitySetId] } }) ); if (psaNeighborsById.error) throw psaNeighborsById.error; psaNeighborsById = fromJS(psaNeighborsById.data); psaNeighborsById.entrySeq().forEach(([id, neighbors]) => { const psaCreationDate = scoresAsMap.getIn([id, PROPERTY_TYPES.DATE_TIME, 0], ''); let mostRecentEditDate = psaCreationDate; let mostRecentNeighbor = Map(); neighbors.forEach((neighbor) => { const entitySetId = neighbor.getIn([PSA_NEIGHBOR.ENTITY_SET, 'id']); const appTypeFqn = entitySetIdsToAppType.get(entitySetId, JUDGES); if (appTypeFqn === STAFF) { const neighborObj = neighbor.get(PSA_ASSOCIATION.DETAILS, Map()); const editDate = neighborObj.getIn( [PROPERTY_TYPES.COMPLETED_DATE_TIME, 0], neighborObj.getIn([PROPERTY_TYPES.DATE_TIME], '') ); const editDateTime = DateTime.fromISO(editDate); const isMostRecent = mostRecentEditDate ? DateTime.fromISO(mostRecentEditDate).valueOf() < editDateTime.valueOf() : true; if (isMostRecent) { mostRecentEditDate = editDate; mostRecentNeighbor = neighbor; } } }); if (mostRecentEditDate) { psaIdToMostRecentEditDate = psaIdToMostRecentEditDate.set( id, mostRecentNeighbor.set(PROPERTY_TYPES.DATE_TIME, mostRecentEditDate) ); } }); } yield put(filterPeopleIdsWithOpenPSAs.success(action.id, { filteredPersonIds, scoresAsMap, personIdsToOpenPSAIds, personIdsWhoAreSubscribed, openPSAIds, hearingNeighborsById, peopleWithMultiplePSAs, psaIdToMostRecentEditDate })); } catch (error) { LOG.error(error); yield put(filterPeopleIdsWithOpenPSAs.failure(action.id, error)); } finally { yield put(filterPeopleIdsWithOpenPSAs.finally(action.id)); } } function* filterPeopleIdsWithOpenPSAsWatcher() :Generator<*, *, *> { yield takeEvery(FILTER_PEOPLE_IDS_WITH_OPEN_PSAS, filterPeopleIdsWithOpenPSAsWorker); } export { // eslint-disable-next-line import/prefer-default-export filterPeopleIdsWithOpenPSAsWatcher }; /* Name: Gachapon12 Place: Singapore and Kampung */ var status = -1; function action(mode, type, selection) { if (mode == 1) { status++; } else { status--; } if (status == 0) { if (cm.haveItem(5220000)) { cm.sendYesNo("You have some #bGachapon Tickets#k there.\r\nWould you like to try your luck?"); } else { cm.sendOk("You don't have a single ticket with you. Please buy the ticket at the department store before coming back to me. Thank you."); cm.safeDispose(); } } else if (status == 1) { var item; if (Math.floor(Math.random() * 300) == 0) { var rareList = new Array(2049100, 2340000, 1372040, 3010029, 3010030, 3010031, 3010032, 3010033); item = cm.gainGachaponItem(rareList[Math.floor(Math.random() * rareList.length)], 1); } else { var itemList = new Array(2044110, 2000004, 2000005, 2022025, 2022027, 4001014, 1442013, 1302022, 1432017, 1302027, 1402013, 1332020, 1032006, 1302014, 1432048, 1102086, 1402044, 1032002, 1442014, 1402009, 1442009, 1442025, 1442007, 1422007, 1432005, 1372007, 1372000, 1372031, 1372036, 1372011, 1472023, 1472054, 1332012, 1462002, 2044903, 2044904, 2044803, 2044804); item = cm.gainGachaponItem(itemList[Math.floor(Math.random() * itemList.length)], 1); } if (item != -1) { cm.gainItem(5220000, -1); cm.sendOk("You have obtained #b#t" + item + "##k."); } else { cm.sendOk("Please check your item inventory and see if you have the ticket, or if the inventory is full."); } cm.safeDispose(); } }<filename>resources/js/mixins/websocketsTabla.js const websocketsTabla = tipoM => ({ methods: { closeEliminar() { window.Echo.private("desbloquearBtns" + tipoM).whisper( "desbloquearBtns" + tipoM, { id: this.id } ); this.$events.fire("eliminarMiBloqueo" + tipoM, { id: this.id }); }, actualizarTabla() { if (this.mostrarTabla) { if (this.$refs.tabla) { this.$refs.tabla.refreshDatos(); } } } }, created() { this.$events.on("actualizartabla" + tipoM, e => this.actualizarTabla()); }, destroyed() { this.$events.off("actualizartabla" + tipoM); } }); export default websocketsTabla; <reponame>yarkeev/har-viewer<gh_stars>10-100 define([ 'jquery' ], function ($) { 'use strict'; function SourceFile(options) { this.options = $.extend(true, {}, options); Array.prototype.forEach.call(this.options.files, function (item) { var reader = new FileReader(); reader.onload = function (event) { var har = JSON.parse(event.target.result), startPageTime, entries = [], arFileName, fileName; if (item.name.indexOf('.') !== -1) { arFileName = item.name.split('.'); arFileName.pop(); fileName = arFileName.join('.'); } else { fileName = item.name; } if (har && har.log && har.log.pages && har.log.pages[0]) { startPageTime = new Date(har.log.pages[0].startedDateTime).getTime(); har.log.entries.forEach(function (item) { var start = new Date(item.startedDateTime).getTime() - startPageTime; entries.push({ name: item.request.url, startTime: start, responseEnd: start + item.time }); }); if (this.options.callback) { this.options.callback({ entries: entries, name: fileName, title: har.log.pages[0].title }); } } else { this.options.callback({ err: 'invalid file', name: fileName }); } }.bind(this); reader.readAsText(item); }.bind(this)); } return SourceFile; });<gh_stars>0 import React from 'react' import { Modal, ModalHeader, ModalBody, FormGroup, Label, NavbarBrand } from 'reactstrap' const initialState = { toptext: '', bottomtext: '', isTopDragging: false, isBottomDragging: false, topY: '10%', topX: '50%', bottomX: '50%', bottomY: '90%', textStyle: { fontFamily: 'Helvetica', fontSize: '50px', fill: '#FFF', userSelect: 'none' } } class MainPage extends React.Component { constructor(props) { super(props) this.state = { currentImage: 0, modalIsOpen: false, currentImagebase64: null, ...initialState } } openImage = index => { const image = this.props.photos[index] const base_image = new Image() base_image.src = image.src.base64 const base64 = this.getBase64Image(base_image) this.setState(prevState => ({ currentImage: index, modalIsOpen: !prevState.modalIsOpen, currentImagebase64: base64, ...initialState })) } toggle = () => { this.setState(prevState => ({ modalIsOpen: !prevState.modalIsOpen })) } changeText = event => { this.setState({ [event.currentTarget.name]: event.currentTarget.value }) } changeFont = event => { this.setState({ textStyle: { fontFamily: event.currentTarget.value, fontSize: this.state.textStyle.fontSize, fill: this.state.textStyle.fill, userSelect: 'none' } }) } changeSize = event => { this.setState({ textStyle: { fontSize: event.currentTarget.value, fill: this.state.textStyle.fill, userSelect: 'none' } }) } changeColor = event => { this.setState({ textStyle: { fontSize: this.state.textStyle.fontSize, fill: event.currentTarget.value, userSelect: 'none' } }) } getStateObj = (e, type) => { let rect = this.imageRef.getBoundingClientRect() const xOffset = e.clientX - rect.left const yOffset = e.clientY - rect.top let stateObj = {} if (type === 'bottom') { stateObj = { isBottomDragging: true, isTopDragging: false, bottomX: `${xOffset}px`, bottomY: `${yOffset}px` } } else if (type === 'top') { stateObj = { isTopDragging: true, isBottomDragging: false, topX: `${xOffset}px`, topY: `${yOffset}px` } } return stateObj } handleMouseDown = (e, type) => { const stateObj = this.getStateObj(e, type) document.addEventListener('mousemove', event => this.handleMouseMove(event, type) ) this.setState({ ...stateObj }) } handleMouseMove = (e, type) => { if (this.state.isTopDragging || this.state.isBottomDragging) { let stateObj = {} if (type === 'bottom' && this.state.isBottomDragging) { stateObj = this.getStateObj(e, type) } else if (type === 'top' && this.state.isTopDragging) { stateObj = this.getStateObj(e, type) } this.setState({ ...stateObj }) } } handleMouseUp = event => { document.removeEventListener('mousemove', this.handleMouseMove) this.setState({ isTopDragging: false, isBottomDragging: false }) } convertSvgToImage = () => { const svg = this.svgRef let svgData = new XMLSerializer().serializeToString(svg) const canvas = document.createElement('canvas') canvas.setAttribute('id', 'canvas') const svgSize = svg.getBoundingClientRect() canvas.width = svgSize.width canvas.height = svgSize.height const img = document.createElement('img') img.setAttribute( 'src', 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData))) ) img.onload = function() { canvas.getContext('2d').drawImage(img, 0, 0) const canvasdata = canvas.toDataURL('image/png') const a = document.createElement('a') a.download = 'meme.png' a.href = canvasdata document.body.appendChild(a) a.click() } } getBase64Image(img) { var canvas = document.createElement('canvas') canvas.width = img.width canvas.height = img.height var ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0) var dataURL = canvas.toDataURL('image/png') return dataURL } render() { let photos = this.props.photos const image = photos[this.state.currentImage] const base_image = new Image() base_image.src = image.src.base64 var wrh = base_image.width / base_image.height var newWidth = base_image.width var newHeight = newWidth / wrh return ( <div> <Modal className="meme-gen-modal" isOpen={true}> <ModalHeader toggle={this.toggle}> Apply some text directly to the image and drag the text as you see fit before downloading the image. </ModalHeader> <ModalBody> <svg width={newWidth} id="svg_ref" height={newHeight} ref={el => { this.svgRef = el }} xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" > <image ref={el => { this.imageRef = el }} xlinkHref={this.props.photos[0].src.base64} height={newHeight} width={newWidth} /> <text style={{ ...this.state.textStyle, zIndex: this.state.isTopDragging ? 4 : 1 }} x={this.state.topX} y={this.state.topY} dominantBaseline="middle" textAnchor="middle" onMouseDown={event => this.handleMouseDown(event, 'top')} onMouseUp={event => this.handleMouseUp(event, 'top')} > {this.state.toptext} </text> <text style={this.state.textStyle} dominantBaseline="middle" textAnchor="middle" x={this.state.bottomX} y={this.state.bottomY} onMouseDown={event => this.handleMouseDown(event, 'bottom')} onMouseUp={event => this.handleMouseUp(event, 'bottom')} > {this.state.bottomtext} </text> </svg> <div className="meme-form"> <FormGroup> <Label for="fontChange">Change Font Family</Label> <select onChange={this.changeFont}> <option value="Helvetica">Helvetica</option> <option value="Impact">Impact</option> <option value="Bank Gothic">Bank Gothic</option> <option value="Arial">Arial</option> <option value="Serif Bold">Serif Bold</option> <option value="Comic Sans MS">Comic Sans</option> <option value="Monospace">Monospace</option> </select> <Label for="fontSize">Change Font Size</Label> <input className="form-control" type="number" name="fontSize" id="fontSize" onChange={this.changeSize} /> <Label for="fontChange">Change Font Color</Label> <select onChange={this.changeColor}> <option value="white">White</option> <option value="blue">Blue</option> <option value="red">Red</option> <option value="green">Green</option> <option value="black">Black</option> <option value="yellow">Yellow</option> <option value="pink">Pink</option> <option value="purple">Purple</option> </select> <Label for="toptext">Top Text</Label> <input className="form-control" type="text" name="toptext" id="toptext" placeholder="Add text to the top" onChange={this.changeText} /> </FormGroup> <FormGroup> <Label for="bottomtext">Bottom Text</Label> <input className="form-control" type="text" name="bottomtext" id="bottomtext" placeholder="Add text to the bottom" onChange={this.changeText} /> </FormGroup> <button onClick={() => this.convertSvgToImage()} className="btn btn-primary" > Download image </button> </div> </ModalBody> </Modal> </div> ) } } export default MainPage import React, { Component } from 'react'; import Layout from 'antd/lib/layout'; import axios from '../../axios'; import Input from 'antd/lib/input'; import message from 'antd/lib/message'; import ClipboardJS from 'clipboard/dist/clipboard.min'; import Button from '../../components/Button'; import SiteHeader from '../../components/SiteHeader'; import SiteFooter from '../../components/SiteFooter'; const { Header, Footer, Content } = Layout; class HomePage extends Component { constructor(props) { super(props); this.state = { longUrl : '', shortUrl : 'Get your link here', }; this.clip = new ClipboardJS('#copyBtn'); this.clip.on('success', e => { e.clearSelection(); message.success('Copied'); }); } getShortUrl = async () => { this.setState({ loading: true }, () => { axios({ method: 'post', url: `api/add/${encodeURIComponent(this.state.longUrl)}`, }) .then((response) => { this.setState({ shortUrl: `${window.location.origin}/${response.data}` }); }) .catch((error) => { console.log(error.data); }); }); }; setLongURL(url) { this.setState({ longUrl: url }); } render() { return ( <Layout> <Header> <SiteHeader/> </Header> <Content className="content"> <div className="shorten"> <div className="constrain"> <h1>Transform your long link into tiny one :)</h1> <div> <Input name="urlInput" onChange={e => this.setLongURL(e.target.value)} value={this.state.longUrl} placeholder="Paste your link here" className="inputLong" /> <Button className="tinyMeBtn" onClick={this.getShortUrl} text="Tiny me !!!" /> </div> <div className="tagline"> All tiny.me URLs are public and can be accessed by anyone </div> </div> </div> <div className="shortenResult"> <div className="constrain"> <h1>Your Tiny URL: </h1> <div> <Input id="foo" value={this.state.shortUrl} className="inputLong" /> <button id="copyBtn" data-clipboard-target="#foo" className="tinyMeBtn" > COPY </button> </div> </div> </div> </Content> <Footer> <SiteFooter /> </Footer> </Layout> ); } } export default HomePage; <filename>work/exampleurOB.js function my_function410(){ //78791925195534602383477457059445dHYAtZduZBLDWeCHQlXQuUEgFIpzcDMQ } function my_function254(){ //35470550763107498062392927282207MHFYmsniWnByvdvlhQlxjWsxMXOPjksA } function my_function983(){ //23218577267392971945424665995049hNgFAFMvHcDQaCLsYnIuAgRrkhyxpuxf } function my_function462(){ //81940091194875205287763063958949DmEpdSfZUFZAyjumaqwApKvwDghzitfT } function my_function364(){ //90872291323511825302978119874715WFAUPqzAtcDxrJfUEjuvcsFxAhYteGGE } function my_function835(){ //60306190748442452931969916040059qncJUKTbpazwBvMCpHMbtDlZTGSKJiXF } function my_function399(){ //89226249782169192134984632850307kZVrjmfGacQBDoAqTULYayPRjnECEEbQ } function my_function394(){ //56604312967634222392164087352755mQvQzqbeCSoHqwnAL<KEY> } function my_function367(){ //46518105474561910218602810047649HIMLQbTknKVmalWgqAXDDTfKnTBirnEb } function my_function070(){ //07077193104547311895567046355575iMHXGiQftlqtzISAmOxxYEqaAwbajqUL } function my_function796(){ //60718421686976714475998064773484whcEvgSfBfzrlbSqXYpoWMQDMhRrcqVd } function my_function671(){ //04175356234121708424093760410502VqfZkvhoPKTDWJRgERKnLogjBUcQRkMI } function my_function295(){ //96351655463334094748850084276782klNtlbtyfZbAFVpiABprwoRkjePbPLEr } function my_function408(){ //69903775757265317227578342202526LqlGQUKEmhpmNIDuPnFRuPpsdabLIFPR } function my_function030(){ //60258859952016752086370544246677cVUhVwqJBMJFvSpsyzHOxwaHLjiJbqhE } function my_function881(){ //29530732256723596940372993774272AsRCmFcfUigjggCKBEVIqScharGBICqu } function my_function649(){ //12956433793962035519670547801293qhKEsUTxrylOavnfRnVFIJmLQWssaUTj } function my_function236(){ //02430014382245519226050180912408GaBXbUCrVGtPZaPbXDNulxhtPLVwPAjC } function my_function460(){ //24507536453146497553204245396505ysSJWPsZWqAXGHNaaDSquGKOuOAgUYgm } function my_function978(){ //63345728959426646185793523560917bJIeVrfdCjtcemLGeGdgNquTGCcwtjWA } function my_function159(){ //22553328807633238225363489231999pGLnqvDfMcySJCoNdjoQiDywkCDuSsSQ } function my_function821(){ //63751912174170930463098461451007qjYzxOVMtJCJoGZWBSQHNdnYWGHGjmPy } function my_function623(){ //30277914188112814929896881217806VMVUXSOdMiuXDgihZpSiceWyYglhgcem } function my_function826(){ //11006242135324280570965523162527wILiphBhBthnjIqJdXiQVgnjFQVePVdb } function my_function811(){ //17584280373693058530591804661437cJOGOwoaTErwurMLUkKfuUYaApIbxCTa } function my_function654(){ //11287103293198868871239068726435QYhfrzFRHAJMiBTjMtlpgPMoWjgFXbGj } function my_function586(){ //20216908920932658992245685053430gccuOmMThvMVmjwobdYNPvNzcGVLzwyM } function my_function111(){ //35882720026561490163342679250320VfaCrgFmKiuMCjwzDTwfmmjDVRclkwcq } function my_function520(){ //18211410093543378648608814262136ZvmtMTOuILUcXDlsMxraNPlrzsElPCjU } function my_function304(){ //21446197947417901081513055813497eKGyvovbABgcMqadZUQPydOzQvAGfsvk } function my_function398(){ //14795460058282766386988643901845TtvVrEcLGFdSGBWzUZvFeDzejPpWeOvD } function my_function255(){ //05393373157018387129102536396006UtKvumgVAVbznDAYOfISWsJlABgauRUs } function my_function670(){ //94101852756816349605368019044697yPKmgMaisNABSpYAqxclSofKLPfwNXGj } function my_function697(){ //77416599893389847752238950644882sZiWqjvKZzoljMNuBspcfeIReyKhsUlx } function my_function374(){ //64586597901729861040816447414722ePYTUeqTgaUIabCfTYbtMHkAGeAIiMzO } function my_function827(){ //17154522713564669637012480710123rPcUnSfsVaPwTKEnqUvVTADlGpqbyQKZ } function my_function647(){ //18465297844407574508919420890582YJUGsrOsMmZHDxstFOBgtkglbSQTKUuo } function my_function689(){ //02341285188014330475496552203753bQZjIOsyjePnunxfmshoqmbNtWrVNoML } function my_function610(){ //16359071381339365369518934088438ivJDhIjoKEXziymWXeydPOWHeqzfPuyH } function my_function989(){ //50439016464606491966221653929050HnBFthXwfykUXwlMGpSLDXpZDNoPNcRR } var copernicus = angular.module('copernicus'); /** * @ngdoc controller * @name copernicus.controller:radioController * * @description * Este controlador es utilizado para comunicar al usuario con 'RadioManager', de modo que pueda enviar y recibir la URL * de una emisora o canción. * */ copernicus.controller('radioController', function ($scope, $rootScope, webSocketService) { /** * @ngdoc property * @name usuario * @propertyOf copernicus.controller:radioController * @description * Almacena los datos del usuario. * **/ var usuario; /** * @ngdoc property * @name sala * @propertyOf copernicus.controller:radioController * @description * Almacena los datos de la sala accedida. * **/ var sala; /** * @ngdoc method * @name inicializacion * @methodOf copernicus.controller:radioController * @description * Inicializa el controlador, obteniendo los datos de la sala y del usuario e inicializa 'RadioManager' * enviándole el nombre de usuario del usuario y el id de la sala. * **/ var inicializacion = function () { //Usuario almacenado en el rootScope usuario = $rootScope.usuario; //Id de la sala a la que se accedió sala = JSON.parse(window.sessionStorage.getItem("salaSeleccionada")); webSocketService.radioManager.inicializar(usuario.username, sala.idSala); }; inicializacion(); /** * @ngdoc method * @name play * @methodOf copernicus.controller:radioController * @description * Indica a 'RadioManager' que el usuario quiere reproducir la emisora o canción. * **/ $scope.play = function () { webSocketService.radioManager.play(); }; /** * @ngdoc method * @name cambiarEmisora * @methodOf copernicus.controller:radioController * @description * Indica a 'RadioManager' que el usuario quiere cambiar la URL utilizada. * **/ $scope.cambiarEmisora = function () { webSocketService.radioManager.cambiarEmisora($scope.url); }; /** * @ngdoc method * @name setVolumen * @methodOf copernicus.controller:radioController * @description * Indica a 'RadioManager' que el usuario quiere cambiar el volumen. * **/ $scope.setVolumen = function () { webSocketService.radioManager.setVolumen($scope.volumen); }; });/** * Pivot builder class */ function PivotBuilder () { } /** * Builds Array of Rows or Columns with values of corresponding names * @param data {Object[]} - input data [ {year:2016, fruit: "Apples"} ... { } ] * @param rowNames {String[]} - names array, like ['year','fruit'] * @returns {String[][]} - it's line [['2014', 'Apples'] ... ['2017', 'Bananas']] */ PivotBuilder.prototype.getRowsArray = function (data, rowNames) { let result = []; for (let item of data) { let dummy = []; for (let name of rowNames) { dummy.push(item[name]); } if (JSON.stringify(result).indexOf(JSON.stringify(dummy)) < 0) { result.push(dummy); } } result.sort(function (a, b) { for (let i = 0; i < a.length; ++i) { if (a[i] < b[i]) return -1; if (a[i] > b[i]) return 1; } return 0 }); return result; }; /** * Find and returns data items witch fields values matches every input fields values * @param data {Object[]} * @param fields {String[]} * @param values {String[]} * @returns {Array} */ PivotBuilder.prototype.findMatched = function (data, fields, values) { let result = []; for (let item of data) { // iterate data array let objectFound = false; let obj = {}; for (let prop in fields) { // iterate array of searched props names let field = fields[prop]; let value = values[prop]; obj[field] = value; if (item[field] === value) { objectFound = true } else { objectFound = false; break; } } if (objectFound) result.push(item); } return result }; /** * Gets pivot table, each cell contains array of matched data items * @param data {Object[]} - input data * @param rowNames {String[]} - names array, like ['year','fruit'] * @param colNames {String[]} - names array, like ['year','fruit'] * @returns {Any[][]} - result like [[[{dataItem},...], ... ], ... ] */ PivotBuilder.prototype.pivotResultsRaw = function (data, rowNames, colNames) { let result = []; let allProps = rowNames.concat(colNames); let rowProps = this.getRowsArray(data, rowNames); let colProps = this.getRowsArray(data, colNames); for (let rowIdx in rowProps) { // iterate rows values result[rowIdx] = []; for (let colIdx in colProps) { // iterate cols values let allValues = rowProps[rowIdx].concat(colProps[colIdx]); result[rowIdx][colIdx] = this.findMatched(data, allProps, allValues); } } return result; }; /** * Calculate result using raw array of results for each pivot cell * @param rawResultsTable {Any[][]} - like [ [ [ {dataItem},... ], ... ], ... ] * @param callback {Function} - function that takes cell items array as parameter and expected to return single value * @returns {Array[]} - calculated results for each cell, like: [ [ [45], ... ], ... ] */ PivotBuilder.prototype.calculateResults = function (rawResultsTable, callback) { let refinedResults = []; for (let rowId in rawResultsTable) { refinedResults[rowId] = []; for (let colId in rawResultsTable[rowId]) { let matchedItems = rawResultsTable[rowId][colId]; refinedResults[rowId][colId] = callback(matchedItems); } } return refinedResults }; /** * Compose table head * @param rowNames {Array} * @param colNames {Array} * @param cols {Array} * @returns {Element} */ PivotBuilder.prototype.composeTHead = function (rowNames, colNames, cols) { let $thead = document.createElement('thead'); for (let colInnerIdx in colNames) { colInnerIdx = +colInnerIdx; let $row = document.createElement('tr'); for (let i = 0; i < rowNames.length + 1; ++i) { let $cell = document.createElement('th'); $cell.classList.add('col-name'); if (i === rowNames.length) $cell.innerText = colNames[colInnerIdx]; $row.appendChild($cell); } let colspan = 1; cols.map(function (rowVal, i) { // header prop values let nextColVal = (cols[i + 1]) ? cols[i + 1][colInnerIdx] : undefined; let curColVal = rowVal[colInnerIdx]; let $th = document.createElement('th'); $th.innerText = rowVal[colInnerIdx]; if (colNames.length === colInnerIdx + 1) $th.setAttribute('rowspan', 2); if (nextColVal === curColVal) { // if next value is the same then increment colspan and pass colspan++; } else { // else add cell and reset colspan $th.setAttribute('colspan', colspan); colspan = 1; $row.appendChild($th); } }); $thead.appendChild($row); } let newRow = $thead.insertRow(); for (let i = 0, l = rowNames.length + 1; i < l; ++i) { let $th = document.createElement('th'); if (rowNames[i]) { $th.classList.add('col-name'); $th.innerText = rowNames[i]; } newRow.appendChild($th); } return $thead; }; /** * * @param results {Array} * @param rows {String[][]} * @returns {Element} */ PivotBuilder.prototype.composeTBody = function (results, rows) { let $tbody = document.createElement('tbody'); let rowspan = []; let cellToSpan = []; for (let rowIdx in results) { rowIdx = +rowIdx; let $row = document.createElement('tr'); // headers for (let rowColIdx in rows[rowIdx]) { rowColIdx = +rowColIdx; let prevRowVal = (rows[rowIdx - 1]) ? rows[rowIdx - 1][rowColIdx] : undefined; let nextRowVal = (rows[rowIdx + 1]) ? rows[rowIdx + 1][rowColIdx] : undefined; let currRowVal = rows[rowIdx][rowColIdx]; let $td = document.createElement('td'); $td.innerText = rows[rowIdx][rowColIdx]; $td.classList.add('rowLabel'); if (currRowVal !== nextRowVal && currRowVal !== prevRowVal) { $row.appendChild($td); } // start of repeating row headers if (currRowVal === nextRowVal) { if (!rowspan[rowColIdx]) rowspan[rowColIdx] = 1; if (rowspan[rowColIdx] === 1) { cellToSpan[rowColIdx] = $td; $row.appendChild(cellToSpan[rowColIdx]); } rowspan[rowColIdx]++; } // end of repeating row headers if (currRowVal !== nextRowVal && currRowVal === prevRowVal) { if (cellToSpan[rowColIdx]) { cellToSpan[rowColIdx].setAttribute('rowspan', rowspan[rowColIdx] + ''); } rowspan[rowColIdx] = 1; } if (rows[rowIdx].length === rowColIdx + 1) { $td.setAttribute('colspan', 2); } } // results for (let result of results[rowIdx]) { let $td = document.createElement('td'); $td.innerText = result || ''; $td.classList.add('cell'); $row.appendChild($td); } $tbody.appendChild($row); } return $tbody }; /** * Main method, returns resulted HTMLElement with calculated Pivot table * @param data {Object[]} - input data * @param rowNames {String[]} - names array, like ['year','fruit'] * @param colNames {String[]} - names array, like ['year','fruit'] * @param calculateResultCallback {Function} - function that takes cell items array as parameter and expected * to return single value * @returns {HTMLElement} */ PivotBuilder.prototype.renderFknTable = function (data, rowNames, colNames, calculateResultCallback) { let resultsRaw = this.pivotResultsRaw(data, rowNames, colNames); let results = this.calculateResults(resultsRaw, calculateResultCallback); let rows = this.getRowsArray(data, rowNames); let cols = this.getRowsArray(data, colNames); let $table = document.createElement('table'); $table.classList.add('pivot-table'); let $thead = this.composeTHead(rowNames, colNames, cols); let $tbody = this.composeTBody(results, rows); $table.appendChild($thead); $table.appendChild($tbody); return $table; }; export {PivotBuilder} <filename>screens/competition/components/LoadingText.js import React from "react"; import Loading from "react-native-dynamic-text-loading"; import { StyleSheet, LogBox } from "react-native"; function LoadingText(props) { LogBox.ignoreLogs(["Animated: `useNativeDriver` was not specified. This is a required option and must be explicitly set to `true` or `false`"]); return ( <Loading list={props.text} textStyle={styles.loading} spinnerIsVisible={false} /> ) }; const styles = StyleSheet.create({ loading: { fontSize: 24, marginTop: 50, color: "#fff", fontWeight: "800", width: 260, textAlign: "center", alignSelf: "baseline", } }); export default LoadingText;/** * Search section view */ var _ = require('underscore'), Backbone = require('backbone'); var templates = require('../dist'); var SearchSection = require('../collections/searchsection'), SearchItemView = require('../views/searchitem'); module.exports = Backbone.View.extend({ template : templates.searchsection, initialize : function (options) { options = options || {}; this.name = options.name; }, render : function (list) { var tmpl = _.template(this.template, { variable : 'data' }); this.$el.html(tmpl({ name : this.name.capitalize() })); this.$el.find('ul').empty(); if(!Array.isArray(list)) list = this.collection.models; _.each(list, function (item) { this.renderItem(item); }, this); return this; }, renderItem : function (item) { var searchItemView = new SearchItemView({ model: item }); this .$el .find('ul') .append(searchItemView.render().el); return this; }, /** * Filter section */ filter : function (filters, search) { this.render(this.collection.byFiltersAndSearch(filters, search)); return this; } }); <reponame>GongDexing/work-board /*jshint esversion:6*/ export function putLocal(key, json){ localStorage.setItem(key, JSON.stringify(json)); } export function getLocal(key){ return JSON.parse(localStorage.getItem(key)); } export function clearLocal(){ localStorage.clear(); } (function () { /* Exports */ Package._define("keepnox:perfect-scrollbar"); })(); import React from 'react' import Page from '../layouts/page' import styled from "styled-components" const CardInformationContainer = styled.div` text-align: center; iframe { margin: 0; width: 100%; height: 3250px; overflow: hidden; } ` const CardInformationPage = () => { const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'auto' }) return ( <Page> <CardInformationContainer> <h1>Form for Chandraveena Cards</h1> <p>Please fill in the required details below.</p> <iframe title='Chandraveena Card Information Form' src="https://docs.google.com/forms/d/e/1FAIpQLSdYD0UNSEJ9ZC1bLOZ3w8xznXt6wXyiPnsfEnXg1kMD2Kdzog/viewform?embedded=true" frameBorder="0" marginHeight="0" marginWidth="0" scrolling="no" onLoad={scrollToTop}>Loading…</iframe> </CardInformationContainer> </Page> ) } export default CardInformationPage<gh_stars>0 'use strict'; class ArrayMatching { constructor(sample) { this.sample = sample; } asymmetricMatch(other, customTesters) { const className = Object.prototype.toString.call(this.sample); if (className !== '[object Array]') { throw new Error('You must provide an array to arrayMatching, not \'' + this.sample + '\'.'); } if (this.sample.length !== other.length) return false; const thisArray = this.sample.slice().sort(), otherArray = other.slice().sort(); for (var i = 0; i < thisArray.length; i++) { if (!jasmine.matchersUtil.equals(thisArray[i], otherArray[i], customTesters)) { return false; } } return true; } jasmineToString() { return '<jasmineHelper.arrayMatching(' + jasmine.pp(this.sample) +')>'; } } module.exports = { arrayMatching: array => new ArrayMatching(array) }; <reponame>AnoXDD/Hack-JavaScript<filename>src/persistor/transforms.js<gh_stars>0 import {createTransform} from "redux-persist"; import Interface from "../data/Interface"; // Will be called before the state is serialized to string, i.e. // state is Immutable function serialize(state, key) { switch (key) { case "output": // Store id only let interf = state.get("interface"); return state.set("interface", new Interface({ id : interf.get("id"), parentId: interf.get("parentId"), property: interf.get("property"), })); default: return state; } } // Will be called after the state is deserialized to Immutable, i.e. // state is Immutable function deserialize(state, key) { switch (key) { case "output": // let id = state.get("interface").get("id"); // // return state.set("interface", INTERFACES[id]); default: return state; } } export const transforms = createTransform(serialize, deserialize, {}); <gh_stars>0 import React from "react"; import PropTypes from "prop-types"; import "./index.css"; const Button = ({ text }) => ( <button className="btn">这是一个组件按钮{text}</button> ); Button.propTypes = { text: PropTypes.any, }; export default Button; // (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P. import '../scss/index.scss'; import React from 'react'; import ReactDOM from 'react-dom'; import TodoApp from './TodoApp'; var element = document.getElementById('content'); ReactDOM.render(React.createElement(TodoApp), element); document.body.classList.remove('loading'); <reponame>MathieuDoyon/toggle import React from "react"; import ReactDOM from "react-dom"; import { createToggle } from "@mathdoy/toggle"; import { ToggleProvider } from "@mathdoy/toggle-react"; import { createToggleQuerystring } from "@mathdoy/toggle-querystring"; import "./index.css"; import App from "./App"; import * as serviceWorker from "./serviceWorker"; const toggleQuerystring = createToggleQuerystring({ // Query string parameter param: "features", // Default features features: { logo: true, }, }); const toggle = createToggle({ features: toggleQuerystring(window.location.search), }); ReactDOM.render( <ToggleProvider toggle={toggle}> <App /> </ToggleProvider>, document.getElementById("root") ); // 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: http://bit.ly/CRA-PWA serviceWorker.unregister(); var fs = require('fs'); const index = require('../index.js'); const data = require('./data.js'); const colors = require('colors/safe'); const folderName = index.folderName; const currentGame = './' + folderName + '/deck/currentGame.txt'; const currentCategory = './' + folderName + '/deck/currentCategory.txt'; const currentRunner = './' + folderName + '/deck/currentRunner.txt'; const next1Game = './' + folderName + '/deck/next1Game.txt'; const next1Category = './' + folderName + '/deck/next1Category.txt'; const next1Runner = './' + folderName + '/deck/next1Runner.txt'; const next2Game = './' + folderName + '/deck/next2Game.txt'; const next2Category = './' + folderName + '/deck/next2Category.txt'; const next2Runner = './' + folderName + '/deck/next2Runner.txt'; const next3Game = './' + folderName + '/deck/next3Game.txt'; const next3Category = './' + folderName + '/deck/next3Category.txt'; const next3Runner = './' + folderName + '/deck/next3Runner.txt'; const deckArray = [currentGame, currentCategory, currentRunner, next1Game, next1Category, next1Runner, next2Game, next2Category, next2Runner, next3Game, next3Category, next3Runner]; const scheduleLength = data.scheduleLength; var schedulejson = data.schedulejson; const horaroItems = ['Game', 'Category', 'Runners'] var deckruns = []; var horaroColumns = []; module.exports = { create: function() { if (!fs.existsSync('./' + folderName + '/deck')) { //If folder doesn't exist, make one fs.mkdirSync(folderName + '/deck'); } try { if (fs.existsSync()) { //Program checks if currentGame exists, otherwise makes it. Not best way ofc } else { for (var i = 0; i < deckArray.length; i++) { fs.writeFile(deckArray[i], '', function(err) { if (err) throw err; }); } } } catch (err) { console.error(err); } }, fill: function(currentRun) { schedulejson = data.schedulejson; for (var i = 0; i < 12; i++) { deckruns[i] = ''; } if (data.method === 'oengus') { try { for (var i = 0; i < 4; i++) { if ((currentRun + i) < data.scheduleLength) { if (schedulejson.lines[currentRun + i].gameName !== null) { deckruns[(i * 3) + 0] = schedulejson.lines[currentRun + i].gameName; } if (schedulejson.lines[currentRun + i].categoryName !== null) { deckruns[(i * 3) + 1] = schedulejson.lines[currentRun + i].categoryName; } if (schedulejson.lines[currentRun + i].runners[0] !== null) { try { for (var k = 0; k < schedulejson.lines[currentRun + i].runners.length; k++) { deckruns[(i * 3) + 2] += schedulejson.lines[currentRun + i].runners[k].username + ', '; } deckruns[(i * 3) + 2] = deckruns[(i * 3) + 2].substring(0, deckruns[(i * 3) + 2].length-2); } catch (err) {} } } } } catch (err) { console.error(err); } } else if (data.method === 'horaro') { horaroColumns[0] = schedulejson.data.columns.indexOf(horaroItems[0]); horaroColumns[1] = schedulejson.data.columns.indexOf(horaroItems[1]); horaroColumns[2] = schedulejson.data.columns.indexOf(horaroItems[2]); for (var i = 0; i < horaroColumns.length; i++) { if (horaroColumns[i] === -1) { horaroColumns[i] = 0; //If a field is empty (most often category name), this is done to not crash the program } } for (var i = 0; i < 4; i++) { if ((currentRun + i) < data.scheduleLength) { deckruns[(i * 3) + 0] = schedulejson.data.items[currentRun + i].data[horaroColumns[0]]; deckruns[(i * 3) + 1] = schedulejson.data.items[currentRun + i].data[horaroColumns[1]]; deckruns[(i * 3) + 2] = schedulejson.data.items[currentRun + i].data[horaroColumns[2]]; } } } writeToFiles(); } } function writeToFiles() { for (var i = 0; i < 12; i++) { try { fs.writeFileSync(deckArray[i], deckruns[i], (err) => { if (err) throw err; console.log("bla"); }); } catch (err) {} } console.log(colors.yellow('Deck Files are updated successfully.')); } function clearFiles() { for (var i = 0; i < 12; i++) { deckruns[i] = ''; //Make sure that all files are emptied before written to again } } event="dataScattergeo" data=JSON.stringify( { scope : 'europe', resolution : 50, locations : [ 'FRA', 'DEU', 'RUS', 'ESP' ], marker : { size : [ 20, 30, 15, 10 ], }, } ); const Promise = require('bluebird'); const assert = require('assert'); const sinon = require('sinon'); const moment = require('moment'); const conf = require('../../../src/conf'); const { duration, simpleDispatcher, afterAgreementExecution } = require('../../utils'); const { initChrome, closeChrome, approveSubscription } = require('../../helpers/chrome'); const paypalUtils = require('../../../src/utils/paypal'); const { PAYPAL_DATE_FORMAT } = require('../../../src/constants'); describe('Agreements suite', function AgreementSuite() { const sandbox = sinon.createSandbox(); const Payments = require('../../../src'); const getAgreementStub = () => { return sandbox.stub(paypalUtils.agreement, 'get'); }; const { agreement: { cancel: billingAgreementCancel }, handleError, } = paypalUtils; const paypalConfig = conf.get('/paypal', { env: process.env.NODE_ENV }); const { testAgreementData, testPlanData } = require('../../data/paypal'); const createPlan = 'payments.plan.create'; const deletePlan = 'payments.plan.delete'; const getAgreement = 'payments.agreement.get'; const createAgreement = 'payments.agreement.create'; const executeAgreement = 'payments.agreement.execute'; const stateAgreement = 'payments.agreement.state'; const listAgreement = 'payments.agreement.list'; const forUserAgreement = 'payments.agreement.forUser'; const finalizeExecution = 'payments.agreement.finalize-execution'; const billAgreement = 'payments.agreement.bill'; let billingAgreement; let futureAgreement; let planId; let payments; let dispatch; this.timeout(duration * 16); function assertHookPublishing(publishSpy, event, payload) { sinon.assert.calledWithExactly( publishSpy, 'payments.hook.publish', sinon.match({ event, payload: sinon.match(payload), }), sinon.match({ confirm: true, deliveryMode: 2, mandatory: true, priority: 0 }) ); } function assertExecutionSuccessHookCalled(publishSpy, payload) { assertHookPublishing(publishSpy, 'paypal:agreements:execution:success', payload); } function assertExecutionFailureHookCalled(publishSpy, payload) { assertHookPublishing(publishSpy, 'paypal:agreements:execution:failure', payload); } function assertFinalizationSuccessHookCalled(publishSpy, payload) { assertHookPublishing(publishSpy, 'paypal:agreements:finalization:success', payload); } function assertBillingSuccessHookCalled(publishSpy, payload) { assertHookPublishing(publishSpy, 'paypal:agreements:billing:success', payload); } function assertBillingFailureHookCalled(publishSpy, payload) { assertHookPublishing(publishSpy, 'paypal:agreements:billing:failure', payload); } function assertStateSuccessHookCalled(publishSpy, payload) { assertHookPublishing(publishSpy, 'paypal:agreements:state:success', payload); } before('startService', async () => { payments = new Payments(); await payments.connect(); dispatch = simpleDispatcher(payments); }); before('initPlan', async () => { const data = await dispatch(createPlan, testPlanData); const id = data.plan.id.split('|')[0]; planId = data.plan.id; testAgreementData.plan.id = id; }); after(() => { return dispatch(deletePlan, planId).reflect(); }); beforeEach('init Chrome', initChrome); afterEach('close chrome', closeChrome); afterEach('reset sandbox', () => { sandbox.reset(); sandbox.restore(); }); describe('unit tests', function UnitSuite() { it('Should fail to create agreement on invalid schema', async () => { await assert.rejects(dispatch(createAgreement, { random: true }), { name: 'HttpStatusError', statusCode: 400, message: 'agreement.create validation failed: data should NOT have additional properties, ' + 'data should have required property \'owner\', data should have required property \'agreement\'', }); }); it('By default user should have free agreement', async () => { const result = await dispatch(forUserAgreement, { user: '<EMAIL>' }); assert.strictEqual(result.id, 'free'); assert.strictEqual(result.agreement.id, 'free'); }); it('Should create an agreement', async () => { const data = { agreement: testAgreementData, owner: '<EMAIL>', creatorTaskId: 'fake-task-id', }; billingAgreement = await dispatch(createAgreement, data); }); it('Should create an agreement with different start_date', async () => { const now = Date.now(); const startDate = moment().add(3, 'days'); const data = { agreement: testAgreementData, owner: '<EMAIL>', startDate, }; futureAgreement = await dispatch(createAgreement, data); const dateDiff = moment(futureAgreement.agreement.start_date).diff(now, 'days'); assert.ok(dateDiff >= 31, 'agreement should start in next 31~33 days'); }); it('Should create an agreement with custom setupFee and discount, discount ignored', async () => { const data = { agreement: testAgreementData, owner: '<EMAIL>', setupFee: '10.00', trialDiscount: 10, }; const { agreement } = await dispatch(createAgreement, data); assert.strictEqual(agreement.plan.merchant_preferences.setup_fee.value, '10'); }); it('Should create an agreement without setup fee and use passed startDate without changes', async () => { const now = moment().add(1, 'month'); const data = { agreement: testAgreementData, owner: '<EMAIL>', setupFee: '24.99', trialDiscount: 0, startDate: now, skipSetupFee: true, }; const { agreement } = await dispatch(createAgreement, data); assert.strictEqual(agreement.plan.merchant_preferences.setup_fee.value, '0'); assert.strictEqual( moment(agreement.start_date).format(PAYPAL_DATE_FORMAT), now.format(PAYPAL_DATE_FORMAT) ); }); it('Should create an agreement with setup fee and use passed startDate without changes', async () => { const now = moment().add(2, 'days'); const data = { agreement: testAgreementData, owner: '<EMAIL>', setupFee: '24.99', trialDiscount: 0, startDate: now, forceStartDate: true, }; const { agreement } = await dispatch(createAgreement, data); assert.strictEqual(agreement.plan.merchant_preferences.setup_fee.value, '24.99'); assert.strictEqual( moment(agreement.start_date).format(PAYPAL_DATE_FORMAT), now.format(PAYPAL_DATE_FORMAT) ); }); it('Should create an agreement with BillingcreatorTaskId', async () => { const now = moment().add(1, 'month'); const data = { agreement: testAgreementData, owner: '<EMAIL>', trialDiscount: 0, startDate: now, creatorTaskId: 'some-weird-id', }; const result = await dispatch(createAgreement, data); assert.strictEqual(result.creatorTaskId, 'some-weird-id'); }); it('Should create an agreement with custom setupFee', async () => { const data = { agreement: testAgreementData, owner: '<EMAIL>', setupFee: '0.00', creatorTaskId: 'future-agreement-task-id', }; futureAgreement = await dispatch(createAgreement, data); assert.strictEqual(futureAgreement.agreement.plan.merchant_preferences.setup_fee.value, '0'); }); it('Should fail to execute on an unknown token', async () => { await assert.rejects(dispatch(executeAgreement, 'random token'), { name: 'HttpStatusError', statusCode: 400, message: 'agreement.execute validation failed: data should be object', }); }); it('Should reject unapproved agreement', async () => { const publishSpy = sandbox.spy(payments.amqp, 'publish'); const { token } = billingAgreement; await assert.rejects(dispatch(executeAgreement, { token }), { name: 'HttpStatusError', statusCode: 400, message: `Agreement execution failed. Reason: Paypal considers token "${token}" as invalid`, }); assertExecutionFailureHookCalled(publishSpy, { error: sinon.match({ message: `Agreement execution failed. Reason: Paypal considers token "${token}" as invalid`, code: 'invalid-subscription-token', params: sinon.match({ token, owner: '<EMAIL>' }), }), }); }); it('Should call hook when executed agreement cancelled', async () => { const data = { agreement: testAgreementData, owner: '<EMAIL>', creatorTaskId: 'fake-task-id-to-find', }; const ppGetStub = getAgreementStub().callsFake(async (agreementId, paypal) => { const result = await ppGetStub.wrappedMethod(agreementId, paypal); return { ...result, state: 'cancelled', }; }); const publishSpy = sandbox.spy(payments.amqp, 'publish'); const agreement = await dispatch(createAgreement, data); const params = await approveSubscription(agreement.url); await assert.rejects(dispatch(executeAgreement, { token: agreement.token }), /Agreement ".*" has status "cancelled"/); assertExecutionFailureHookCalled(publishSpy, { error: sinon.match({ message: sinon.match(/Agreement ".*" has status "cancelled"/), code: 'agreement-status-forbidden', params: sinon.match({ token: params.token, owner: '<EMAIL>', agreementId: sinon.match(/I-/), status: 'cancelled', creatorTaskId: 'fake-task-id-to-find', }), }), }); }); it('Should execute an approved agreement', async () => { const params = await approveSubscription(billingAgreement.url); const publishSpy = sandbox.spy(payments.amqp, 'publish'); const result = await dispatch(executeAgreement, { token: params.token }); result.plan.payment_definitions.forEach((definition) => { assert.ok(definition.id); assert.ok(definition.name); }); billingAgreement.id = result.id; assertExecutionSuccessHookCalled(publishSpy, { agreement: sinon.match({ id: result.id, owner: '<EMAIL>', status: 'active', token: params.token, }), creatorTaskId: 'fake-task-id', }); await afterAgreementExecution(payments, dispatch, result, planId); }); it('Should pull updates for an agreement', async () => { this.timeout(duration); const publishSpy = sandbox.spy(payments.amqp, 'publish'); async function waitForAgreementToBecomeActive(attempts) { const finalizationResult = await dispatch(finalizeExecution, { agreementId: billingAgreement.id }); const agreement = await dispatch(getAgreement, { id: billingAgreement.id }); // NOTE: transaction count is 2 because of transaction with agreement id and other transaction if (finalizationResult.agreement.status.toLowerCase() === 'pending' || !finalizationResult.agreementFinalized) { // Takes too long to finalize if (attempts > 50) { payments.log.error('Unable to finalize agreement!'); return null; } return Promise.delay(5000).then(() => waitForAgreementToBecomeActive(attempts + 1)); } assertFinalizationSuccessHookCalled(publishSpy, { agreement: sinon.match({ id: billingAgreement.id, owner: '<EMAIL>', status: 'active', token: billingAgreement.token, }), agreementFinalized: true, creatorTaskId: 'fake-task-id', transactionRequired: true, transaction: sinon.match.object, }); agreement.agreement.plan.payment_definitions.forEach((definition) => { assert.ok(definition.id); assert.ok(definition.name); }); return null; } return waitForAgreementToBecomeActive(0); }); it('Should execute an future approved agreement', async () => { const params = await approveSubscription(futureAgreement.url); const publishSpy = sandbox.spy(payments.amqp, 'publish'); const result = await dispatch(executeAgreement, { token: params.token }); result.plan.payment_definitions.forEach((definition) => { assert.ok(definition.id); assert.ok(definition.name); }); futureAgreement.id = result.id; assertExecutionSuccessHookCalled(publishSpy, { agreement: sinon.match({ id: result.id, owner: '<EMAIL>', status: 'active', token: params.token, }), creatorTaskId: 'future-agreement-task-id', }); await afterAgreementExecution(payments, dispatch, result, planId); }); it('Should pull updates for an agreement without setup fee', async () => { this.timeout(duration); const publishSpy = sandbox.spy(payments.amqp, 'publish'); async function waitForAgreementToBecomeActive(attempts) { const finalizationResult = await dispatch(finalizeExecution, { agreementId: futureAgreement.id }); const agreement = await dispatch(getAgreement, { id: futureAgreement.id }); if (finalizationResult.agreement.status.toLowerCase() === 'pending' || !finalizationResult.agreementFinalized) { // Takes too long to finalize if (attempts > 50) { payments.log.error('Unable to finalize agreement!'); return null; } return Promise.delay(5000).then(() => waitForAgreementToBecomeActive(attempts + 1)); } assertFinalizationSuccessHookCalled(publishSpy, { agreement: sinon.match({ id: futureAgreement.id, owner: '<EMAIL>', status: 'active', token: futureAgreement.token, }), creatorTaskId: 'future-agreement-task-id', agreementFinalized: true, transactionRequired: false, }); agreement.agreement.plan.payment_definitions.forEach((definition) => { assert.ok(definition.id); assert.ok(definition.name); }); return null; } return waitForAgreementToBecomeActive(0); }); // sorry for being verbose, will deal with it later it('should bill agreement', async () => { const { id } = billingAgreement; const publishSpy = sandbox.spy(payments.amqp, 'publish'); const result = await dispatch(billAgreement, { agreement: id, subscriptionInterval: 'month', username: '<EMAIL>' }); assert.strictEqual(result, 'OK'); assertBillingSuccessHookCalled(publishSpy, { cyclesBilled: sinon.match.in([0, 1]), agreement: sinon.match({ id, owner: '<EMAIL>', status: 'active', }), }); }); it('should bill agreement: send billing failed when no new cycles and failed count increased', async () => { const { id } = billingAgreement; const ppGetAgreementStub = getAgreementStub(); ppGetAgreementStub.resolves({ state: 'Active', agreement_details: { failed_payment_count: 777, }, }); const publishSpy = sandbox.spy(payments.amqp, 'publish'); const dispatchStub = sandbox.stub(payments, 'dispatch'); dispatchStub.withArgs('transaction.sync').resolves({ transactions: [] }); dispatchStub.callThrough(); const result = await dispatch(billAgreement, { agreement: id, subscriptionInterval: 'month', username: '<EMAIL>' }); assert.strictEqual(result, 'FAIL'); assertBillingFailureHookCalled(publishSpy, { error: sinon.match({ message: `Agreement billing failed. Reason: Agreement "${id}" has increased failed payment count`, code: 'agreement-payment-failed', params: sinon.match( ({ agreementId, owner }) => (agreementId === id && owner === '<EMAIL>') ), }), }); }); it('should bill agreement: send billing failure when new cycles billed and failed count increased', async () => { const { id } = billingAgreement; const ppGetAgreementStub = getAgreementStub(); ppGetAgreementStub.resolves({ state: 'Active', agreement_details: { failed_payment_count: 1, cycles_completed: 3, }, }); const publishSpy = sandbox.spy(payments.amqp, 'publish'); const dispatchStub = sandbox.stub(payments, 'dispatch'); dispatchStub.withArgs('transaction.sync').resolves({ transactions: [] }); dispatchStub.callThrough(); const result = await dispatch(billAgreement, { agreement: id, nextCycle: moment().subtract(1, 'day').valueOf(), username: '<EMAIL>' }); assert.strictEqual(result, 'FAIL'); assertBillingFailureHookCalled(publishSpy, { error: sinon.match({ message: `Agreement billing failed. Reason: Agreement "${id}" has increased failed payment count`, code: 'agreement-payment-failed', params: sinon.match( ({ agreementId, owner }) => (agreementId === id && owner === '<EMAIL>') ), }), }); }); it('Should create a trial agreement', async () => { const data = { agreement: testAgreementData, owner: '<EMAIL>', trialDiscount: 10, }; billingAgreement = await dispatch(createAgreement, data); }); it('Should execute an approved trial agreement', async () => { const params = await approveSubscription(billingAgreement.url); const publishSpy = sandbox.spy(payments.amqp, 'publish'); const result = await dispatch(executeAgreement, { token: params.token }); billingAgreement.id = result.id; assertExecutionSuccessHookCalled(publishSpy, { agreement: sinon.match({ id: result.id, owner: '<EMAIL>', status: 'active', token: params.token, }), }); await afterAgreementExecution(payments, dispatch, result, planId); }); it('Should get agreement for user', async () => { const result = await dispatch(forUserAgreement, { user: '<EMAIL>' }); assert.strictEqual(result.agreement.id, billingAgreement.id); result.agreement.plan.payment_definitions.forEach((definition) => { assert.ok(definition.id); assert.ok(definition.name); }); }); // this test is perf it('Should cancel agreement', async () => { const { id } = billingAgreement; const publishSpy = sandbox.spy(payments.amqp, 'publish'); await dispatch(stateAgreement, { agreement: id, owner: '<EMAIL>', state: 'cancel' }); assertStateSuccessHookCalled(publishSpy, { agreement: sinon.match({ id, owner: '<EMAIL>', status: 'cancelled', }), }); }); // sorry for being verbose, will deal with it later it('should fail when billing is not permitted', async () => { const { id } = billingAgreement; const publishSpy = sandbox.spy(payments.amqp, 'publish'); const result = await dispatch(billAgreement, { agreement: id, nextCycle: Date.now(), username: '<EMAIL>' }); assert.strictEqual(result, 'FAIL'); assertBillingFailureHookCalled(publishSpy, { error: sinon.match({ message: `Agreement "${id}" has status "cancelled"`, code: 'agreement-status-forbidden', params: sinon.match({ status: 'cancelled', agreementId: id, owner: '<EMAIL>' }), }), }); }); it('Should create and execute an agreement for a case when statuses for Paypal and Redis are different', async () => { const data = { agreement: { ...testAgreementData, description: 'Redis and Paypal', }, owner: '<EMAIL>', trialDiscount: 20, }; billingAgreement = await dispatch(createAgreement, data); const params = await approveSubscription(billingAgreement.url); const result = await dispatch(executeAgreement, { token: params.token }); billingAgreement.id = result.id; await afterAgreementExecution(payments, dispatch, result, planId); }); it('should deactivate agreement on Paypal only', async () => { await billingAgreementCancel(billingAgreement.id, { note: 'Canceled for testing scenario' }, paypalConfig) .catch(handleError) .then((result) => { assert.deepStrictEqual(result, { httpStatusCode: 204 }); // the same billing agreement in Paypal is CANCELLED return null; }); }); it('Should cancel the agreement with unsynchronized statuses', async () => { const { id } = billingAgreement; const publishSpy = sandbox.spy(payments.amqp, 'publish'); await dispatch(stateAgreement, { agreement: id, owner: '<EMAIL>', state: 'cancel' }); const agreement = await dispatch(getAgreement, { id }); assertStateSuccessHookCalled(publishSpy, { agreement: sinon.match({ id, owner: '<EMAIL>', status: 'cancelled', }), }); console.debug('=== UPDATED', agreement); }); it('Should list all agreements', () => { return dispatch(listAgreement, {}); }); }); }); <filename>src/subscriptions/subscriptionBalance.js /** * Subscription manager for 'balance' */ 'use strict'; const logs = require('../logs.js')(module); const validate = require('../validators'); const jsonHash = require('json-hash'); const getBalance = require('../tasks/getBalance')(); const blockHeaderTask = require('../scheduler/blockHeaderTask')(); /** * clean up a task from the scheduler when socket wants to unsubscribe * * @param {Object} task The task * @return {Promise} result of removing the task (no return value) */ function cancelSubscription(task) { return Promise.resolve( blockHeaderTask.removeTask(task) ); } /** * Creates a subscription. * * @param {Function} emitToSubscriber the function to call when you want to emit data * @param {Object} args The parameters sent with the subscription * @return {Promise} resolves with the subscription object */ function createSubscription(emitToSubscriber, args) { // check arguments if (!args || !args.address || !validate.isAddress(args.address)) { return Promise.reject('Cannot subscribe to a balance without a valid address.'); } logs.debug('Subscribing to balance for %s', args.address); // create task let _task = { func: (task) => { return Promise.resolve(getBalance.getBalance(task.data).then((res) => { if (!task.data.lastReplyHash) { let replyHash = jsonHash.digest(res); task.data.lastReplyHash = replyHash; logs.debug('no lastReplyhash, setting it to %s', replyHash); } return (res); })); }, responsehandler: (res, task) => { logs.debug('received getBalance RES=%j', res); let replyHash = jsonHash.digest(res); if (task.data.lastReplyHash !== replyHash) { logs.debug('getBalance => data has changed. New value: %j', res); emitToSubscriber('balanceChanged', res); task.data.lastReplyHash = replyHash; } else { // logs.debug('getBalance => data hasn\'t changed.'); } return blockHeaderTask.addTask(task); }, data: { address: args.address, }, }; blockHeaderTask.addTask(_task); // run it a first time return subscription return _task.func(_task).then((reply) => { return Promise.resolve({ task: _task, initialResponse: reply, cancelSubscription: cancelSubscription, }); }); } module.exports = function() { return ({ name: 'balance', createSubscription: createSubscription, }); }; TodoMVC.module('TodoList.Views', function(Views, App, Backbone, Marionette, $, _){ Views.ItemView = Marionette.ItemView.extend({ tagName: 'li', template: '#template-todoItemView', ui: { edit: '.edit' }, events: { 'click .destroy': 'destroy', 'dbclick label': 'onEditClick', 'keypress .edit': 'onEditKeypress', 'blur .edit': 'onEditBlur', 'click .toggle': 'toggle' }, initialize: function() { this.listenTo(this.model, 'change', this.render); }, onRender: function() { this.$el.removeClass('active completed'); if(this.model.get('completed')) { this.$el.addClass('completed'); } else { this.$el.addClass('active'); } }, destroy: function() { this.model.destroy(); }, toggle: function() { this.model.toggle().save(); }, onEditClick: function() { this.$el.addClass('editing'); this.ui.edit.focus(); }, updateTodo: function() { var todoVal = this.ui.edit.val().trim(); if(todoVal === '') { return this.destroy(); } this.setTodoVal(todoVal); this.completeEdit(); }, onEditBlur: function() { this.updateTodo(); }, onEditKeypress: function() { var ENTER = 13; var todoVal = this.ui.edit.val().trim(); if(e.which === ENTER && todoVal) { this.model.set('title', todoVal).save(); this.completeEdit(); } }, setTodoVal: function(todoVal) { this.model.set('title', todoVal).save(); }, completeEdit: function() { this.$el.removeClass('editing'); } }); Views.ListView = Backbone.Marionette.CompositeView.extend({ template: '#template-todoListCompositeView', childView: Views.ItemView, childViewContainer: '#todo-list', ui: { toggle: '#toggle-all' }, events: { 'click #toggle-all': 'onToggleAllClick' }, initialize: function() { this.listenTo(this.collection, 'all', this.update); }, onRender: function() { this.update(); }, update: function() { function reduceCompleted(left, right) { return left && right.get('completed'); } var allCompleted = this.collection.reduce(reduceCompleted, true); this.ui.toggle.prop('checked', allCompleted); this.$el.parent().toggle(!!this.collection.length); }, onToggleAllClick: function(e) { var isChecked = e.currentTarget.checked; this.collection.each(function(todo) { todo.save({'completed': isChecked}); }); } }); App.vent.on('todoList:filter', function(filter) { filter = filter || 'all'; $('#todo-app').attr('class', 'filter-' + filter); }); });<gh_stars>1-10 import { Alarm24 } from '..'; export default Alarm24; pc.getDefaultMaterial = function () { return pc.Application.getApplication().scene.defaultMaterial; }; <filename>src/upload.js const upload = () => { console.log('----- upload start -----') console.log('----- schedule upload sdk -----') console.log('----- upload -----') } export default upload<reponame>SvanBoxel/node-expressjs-example const st = (delay) => { return setTimeout(() => { console.log('...go!') }, delay) } module.exports = st const fs = require('fs') const data = require('../data/values.js') const addNote = (title, body) => { const notes = loadNotes(), duplicateNote = notes.find(note => note.title === title) if (duplicateNote) { console.log('Title taken!') } else { notes.push({ title: title, body: body }) saveNotes(notes) console.log('Note added!') } } const deleteNote = (title) => { console.log(data.delete.message) const notes = loadNotes(), requestedNote = notes.filter( note => note.title === title ) if (requestedNote.length > 0) { filteredNotes = notes.filter( note => note.title !== title ) saveNotes(filteredNotes) } else ( console.log('Requested note was not found') ) } const listNote = () => { console.log(data.list.message) const notes = loadNotes() for (note of notes) { console.log(`Title: ${note.title}`) console.log(`Preview: ${note.body.slice(0, 10)}...`) } } const readNote = (title) => { console.log(data.read.message) const notes = loadNotes(), existingNote = notes.find(note => note.title === title) if (existingNote) { console.log(`Title: ${existingNote.title}`) console.log(`Note:\n${existingNote.body}`) } else { console.log('Requested note does not exists') } } const loadNotes = () => { try { const notes = fs.readFileSync('./data/notes.json'), notesJSON = notes.toString(), notesObject = JSON.parse(notesJSON) return notesObject } catch (e) { return [] } } const saveNotes = (notes) => { const textNotes = JSON.stringify(notes) fs.writeFileSync('./data/notes.json', textNotes) } module.exports = { addNote: addNote, deleteNote: deleteNote, listNote: listNote, readNote: readNote, } E2.p = E2.plugins["scene_renderer_emitter"] = function(core, node) { this.desc = 'Render the supplied <b>scene</b>. If no <b>shader</b> is specified, the internal shaders of the scene meshes are used.'; this.input_slots = [ { name: 'scene', dt: core.datatypes.SCENE, desc: 'The scene to be rendered.', def: 'Render nothing.' }, { name: 'material', dt: core.datatypes.MATERIAL, desc: 'If a material is specified, internal shaders are generated to render each scene mesh using this material as an overload.', def: 'Use scene materials and shaders.' }, { name: 'camera', dt: core.datatypes.CAMERA, desc: 'The camera to use for rendering.', def: 'Screenspace camera.' }, { name: 'transform', dt: core.datatypes.MATRIX, desc: 'The scene transform to use for rendering.', def: 'Identity' }, { name: 'inv. transform', dt: core.datatypes.BOOL, desc: 'Send true to this slot to apply <b>transform</b> in inverse order when rendering instances.', def: 'False' } ]; this.output_slots = []; this.gl = core.renderer.context; }; E2.p.prototype.reset = function() { this.scene = null; this.shader = null; }; E2.p.prototype.update_input = function(slot, data) { if(slot.index === 0) { if(data !== this.scene) { this.scene = data; if(!this.ext_camera) this.camera = this.scene.create_autofit_camera(); this.material_dirty = true; } } else if(slot.index === 1) { this.material = data; var caps = Material.get_caps_hash(null, data); if(this.material_caps !== caps) { this.material_caps = caps; this.material_dirty = true; } } else if(slot.index === 2) { this.camera = data; this.ext_camera = true; } else if(slot.index === 3) this.transform = data; }; E2.p.prototype.connection_changed = function(on, conn, slot) { if(!on) { if(slot.index === 0) { this.scene = null; this.material_dirty = true; } else if(slot.index === 1) { this.material = null; this.material_caps = ''; this.overload_shaders = null; } else if(slot.index === 2) { this.ext_camera = false; if(this.scene) this.camera = this.scene.create_autofit_camera(); } } }; E2.p.prototype.update_state = function() { if(this.scene) { if(this.material_dirty && this.material) { this.overload_shaders = this.scene.build_overload_shaders(this.material) this.material_dirty = false; } this.transform.invert = this.inv_transform; this.scene.render(this.gl, this.camera, this.transform, this.overload_shaders, this.material); } }; E2.p.prototype.state_changed = function(ui) { if(!ui) { this.material = null; this.material_caps = ''; this.material_dirty = false; this.overload_shaders = null; this.camera = new Camera(); this.transform = mat4.create(); mat4.identity(this.transform); this.ext_camera = false; this.inv_transform = false; } }; <reponame>sohwendy/telegram-bot-secretary<gh_stars>1-10 import test from 'ava'; import sinon from 'sinon'; const rewire = require('rewire'); const constants = require('../../config/constants').stock; const SheetApi = require('../../src/utility/google-sheet-api'); const sheetData = [ { code: 'GLD', name: 'gold', suffix: 'CUR', short: 'GLD' }, { code: 'A01.SI', name: 'Stock A', suffix: 'SI', short: 'A01' }, { code: 'B02.SI', name: 'Stock B', suffix: 'SI', short: 'B02' } ]; const stockData = [ { code: 'GLD', price: '115.2300', changeAmount: '-0.5500' }, { code: 'A01.SI', price: '2.5000', changeAmount: '0.0100' }, { code: 'C02.SI', price: '6.8600', changeAmount: '-0.0400' } ]; test.beforeEach(t => { t.context.worker = rewire('../../src/worker/stock-report-worker'); t.context.sandbox = sinon.createSandbox(); const { worker, sandbox } = t.context; t.context.sheetApiMock = sandbox.mock(SheetApi); const stockApiStub = sandbox.stub(); stockApiStub .withArgs('key', 'GLD', 0).returns(Promise.resolve(stockData[0])) .withArgs('key', 'A01.SI', 15000).returns(Promise.resolve(stockData[1])) .withArgs('key', 'B02.SI', 30000).returns(Promise.resolve(stockData[2])); worker.__set__('StockApi', { get: stockApiStub }); constants.file = './sample/google.json'; constants.secretFile = './sample/stock.json'; worker.__set__('constants', constants); }); test.afterEach.always(t => { t.context.sandbox.restore(); }); test('stringify works', async t => { const expected = ' AA 1 0.3 apple'; const actual = t.context.worker._stringify({ short: 'AA', name: 'apple', price: 1, changeAmount: '0.3' }); t.is(expected, actual); }); test('init() returns config', async t => { const expected = { title: constants.reportTitle, key: '<alpha_vantage_key_1>', code: { token: './sample/google.json', permission: [ 'https://www.googleapis.com/auth/spreadsheets.readonly' ], spreadsheetId: '<stock_sheet_id>', range: 'StockCode!A2:D' } }; const actual = await t.context.worker.init(constants); t.deepEqual(expected, actual.config); }); test('init() returns transform', async t => { const { worker, sandbox } = t.context; const arrayToHash = { bind: sandbox.stub() }; worker.__set__('arrayToHash', arrayToHash); await worker.init(constants); t.is(arrayToHash.bind.callCount, 1); t.is(arrayToHash.bind.calledWithExactly(constants.code.fields), true); }); test('execute() works', async t => { const { worker, sheetApiMock } = t.context; const settings = { key: 'key', config: { code: 'code' }, transform: () => {}, }; const expected = [ ' GLD 115.23 -0.55 gold', ' A01 2.5 0.01 Stock A' ]; sheetApiMock .expects('read') .withExactArgs('code', settings.transform) .once() .returns(sheetData); const actual = await worker.execute(settings); t.true(sheetApiMock.verify()); t.deepEqual(expected, actual); }); <reponame>hjyuan/reapoc $ = jQuery.noConflict(); var wpbs_unsaved_changes = false; var wpbs_form_submitting = false; jQuery(function ($) { if(!$("#wpbs-form-builder").length) return; var wpbs_form_builder = new WPBS_Form_Builder(wpbs_form_data, wpbs_available_field_types, wpbs_available_field_types_options, wpbs_languages); /** * Set the form_submitting variable. * */ $(".wpbs-save-form").click(function(){ wpbs_form_submitting = true; }) /** * Set the unsaved_changes variable. * */ $(".wpbs-wrap-edit-form").on('change keyup', 'input, select, textarea', function(){ wpbs_unsaved_changes = true; }) /** * Add new fields to the form builder * */ $(".wpbs-form-builder-add-form-fields a").click(function (e) { e.preventDefault(); // Add new field var form_field = $.extend(true, {}, wpbs_available_field_types[$(this).data('field-type')]); form_field['id'] = $("#wpbs_form_field_id_index").val(); $("#wpbs_form_field_id_index").val( parseInt(form_field['id']) + 1 ); wpbs_form_builder.form_data.push(form_field); wpbs_form_builder.render(); // Close all fields $("#wpbs-form-builder .form-field").removeClass('open').find(".form-field-content").hide(); // Open last field $("#wpbs-form-builder .form-field").last().addClass('open').find(".form-field-content").show(); // Show notice on notification pages wpbs_show_form_changed_notice(); }) /** * Update form object when interacting with fields * */ $("#wpbs-form-builder").on('keyup change', 'input, textarea', function () { field = $(this); eq = field.parents('.form-field').index(); if(!field.data('language')){ return; } if(typeof wpbs_form_builder.form_data[eq]['values'][field.data('language')] === 'undefined'){ wpbs_form_builder.form_data[eq]['values'][field.data('language')] = []; } if (field.attr('type') == 'checkbox') { wpbs_form_builder.form_data[eq]['values'][field.data('language')][field.data('key')] = field.prop('checked') == true ? 'on' : ''; } else { if(field.data('key') == 'options' || field.data('key') == 'options_pricing'){ if(typeof wpbs_form_builder.form_data[eq]['values'][field.data('language')][field.data('key')] === 'undefined'){ wpbs_form_builder.form_data[eq]['values'][field.data('language')][field.data('key')] = []; } wpbs_form_builder.form_data[eq]['values'][field.data('language')][field.data('key')][field.parent().index()] = field.val(); } else { wpbs_form_builder.form_data[eq]['values'][field.data('language')][field.data('key')] = field.val(); } } }) /** * Join pricing fields into one. * */ $("#wpbs-form-builder").on('keyup change', '.form-field-pricing-fields', function () { $parent = $(this).parent(); $parent.find('input').eq(2).val( $parent.find('.price').val() + '|' + $parent.find('.value').val()).trigger('keyup') }) /** * Duplicate the label option into the field header */ $("#wpbs-form-builder").on('keyup', 'input[data-key="label"][data-language="default"]', function () { field = $(this); field_value = field.val() ? field.val() : field.parents('.form-field').find('.form-field-header-label').data('field-type'); field.parents('.form-field').find('.form-field-header-label').html( field_value ); }) /** * Remove fields button */ $("#wpbs-form-builder").on('click', '.form-field-remove', function (e) { e.preventDefault(); if( ! confirm( "Are you sure you want to remove this field?" ) ) return false; field = $(this); eq = field.parents('.form-field').index(); wpbs_form_builder.form_data = wpbs_form_builder.form_data.filter(function (item, index) { return index !== eq }) wpbs_form_builder.render(); // Show notice on notification pages wpbs_show_form_changed_notice(); }) /** * Make fields collapsable */ $("#wpbs-form-builder").on('click', '.form-field-header', function (e) { e.preventDefault(); field = $(this); field.parents('.form-field').toggleClass('open').find(".form-field-content").slideToggle(); }) /** * Field options accordion */ $("#wpbs-form-builder").on('click', '.form-field-accordion-open', function (e) { e.preventDefault(); accordion = $(this); accordion.parents('.form-field-accordion').toggleClass('open').find(".form-field-accordion-inner").slideToggle(); if(accordion.parents('.form-field-accordion').find('.form-field-tabs').length){ accordion.parents('.form-field-accordion').find('.form-field-tabs .form-field-tabs-navigation a').first().trigger('click'); } }) /** * Field options tabs */ $("#wpbs-form-builder").on('click', '.form-field-tabs-navigation a', function (e) { e.preventDefault(); var tab = $(this); tab.parents('.form-field-tabs').find(".form-field-tab").hide(); tab.parents('.form-field-tabs').find(".form-field-tabs-navigation a").removeClass('active'); tab.addClass('active'); $(tab.data('tab')).show(); }) /** * Add option to dropdown, radio, checkboxes, etc. fields */ $("#wpbs-form-builder").on('click', '.form-field-add-option', function (e) { e.preventDefault(); options = $(this).parents('.form-field-options'); $field_option = options.find('.form-field-option-placeholder').clone(); $field_option.removeClass('form-field-option-placeholder').find('input[data-name]').attr('name', options.find('input[data-name]').data('name')) $field_option.appendTo(options.find('.form-field-options-inner-fields')); }) /** * Remove dropdown, radio, checkboxes, etc. option fields */ $("#wpbs-form-builder").on('click', '.form-field-option-field-remove', function (e) { e.preventDefault(); if (!confirm("Are you sure you want to remove this option?")) return false; var field = $(this).siblings('input[data-key]'); var field_parent = field.parents('.form-field-options'); var eq = field.parents('.form-field').index(); // Remove the field. $(this).parent().remove(); // Rebuild field options. wpbs_form_builder.form_data[eq]['values'][field.data('language')][field.data('key')] = []; field_parent.find('.form-field-options-inner-fields input[data-key]').each(function(){ var option_field = $(this); wpbs_form_builder.form_data[eq]['values'][field.data('language')][field.data('key')][option_field.parent().index()] = option_field.val(); }) }) /** * Make fields sortable */ $('#wpbs-form-builder').sortable({ handle: '.form-field-sort', placeholder: 'form-field-placeholder', containment: '#wpcontent', update: function () { form_sorted = []; $("#wpbs-form-builder .form-field").each(function (i) { new_position = $(this).data('order'); form_sorted[i] = wpbs_form_builder.form_data[new_position]; }) wpbs_form_builder.form_data = form_sorted; wpbs_form_builder.render(); } }); /** * Select all text when clicking on an email tag */ $(".wpbs-wrap-edit-form").on('click', '.wpbs-email-tag div', function (e) { node = $(this)[0]; if (document.body.createTextRange) { const range = document.body.createTextRange(); range.moveToElementText(node); range.select(); } else if (window.getSelection) { const selection = window.getSelection(); const range = document.createRange(); range.selectNodeContents(node); selection.removeAllRanges(); selection.addRange(range); } }); /** * Toggle confirmation messages */ $(".wpbs-wrap-edit-form").on('change', '#form_confirmation_type', function(){ $(this).parents('.wpbs-tab').find(".wpbs-confirmation-type").hide(); $(".wpbs-confirmation-type-" + $(this).val()).show(); }) /** * Show a warning on the notifications page if the form has changed */ function wpbs_show_form_changed_notice(){ $(".wpbs-form-changed-notice").show(); } // Build the form. wpbs_form_builder.render(); }); class WPBS_Form_Builder { constructor(form_data, available_field_types, available_field_types_options, languages){ this.wrapper = document.getElementById('wpbs-form-builder'); this.output; this.form_data = form_data; this.available_field_types = available_field_types; this.available_field_types_options = available_field_types_options; this.languages = languages; } build() { this.output = ''; if(this.form_data.length){ this.fields(); $(".wpbs-start-building").hide(); } else { $(".wpbs-start-building").show(); } } /** * Build the Fields */ fields(){ this.form_data.forEach(function (field, i) { this.field(field, i); }.bind(this)) } /** * Build each individual field * * @param field * @param i */ field(field, i){ this.output += '<div class="form-field form-field-type-' + field.type + '" data-order="' + i + '">'; this.output += '<div class="form-field-inner">'; this.field_header(field); this.output += '<div class="form-field-content"><div class="form-field-content-inner">'; this.output += '<input type="hidden" name="form_fields[' + i + '][type]" value="' + field.type + '" />'; this.output += '<input type="hidden" name="form_fields[' + i + '][id]" value="' + field.id + '" />'; this.field_options(field, i); this.field_translation_options(field, i); this.output += '</div></div>'; this.output += '</div>'; this.output += '</div>'; } /** * Build the header for a field * * @param field */ field_header(field){ var field_nice_name = field.type.replace('_', ' '); var label = (typeof field['values']['default'] !== 'undefined' && typeof field['values']['default']['label'] !== 'undefined' && field['values']['default']['label'] != '') ? field['values']['default']['label'] : '<span><span>' + field_nice_name + '</span> Field</span>'; this.output += '<div class="form-field-header">'; this.output += '<div class="form-field-header-buttons">'; this.output += '<span class="form-field-id">ID:'+field.id+'</span>'; this.output += '<a href="#" class="form-field-remove"><i class="wpbs-icon-close"></i></a>'; this.output += '<a href="#" class="form-field-sort"><i class="wpbs-icon-sort"></i></a>'; this.output += '<a href="#" class="form-field-toggle"><i class="wpbs-icon-down-arrow"></i></a>'; this.output += '</div>'; this.output += '<p><i class="wpbs-icon-'+field.type+'"></i> <span data-field-type="<span><span>' + field_nice_name + '</span> Field</span>" class="form-field-header-label">'+label+'</span></p>'; this.output += '</div>'; } /** * Build the field options * * @param field * @param i * @param language */ field_options(field, i, language = 'default'){ // Primary Fields if(this.available_field_types[field.type].supports.primary){ this.available_field_types[field.type].supports.primary.forEach(function (option) { this.field_option(option, i, language) }.bind(this)) } if(language == 'default' && this.available_field_types[field.type].supports.secondary){ this.output += '<div class="form-field-accordion">'; this.output += '<div class="form-field-accordion-header">'; this.output += '<a href="#" class="form-field-accordion-open">Advanced Options <i class="wpbs-icon-down-arrow"></i></a>'; this.output += '</div>'; this.output += '<div class="form-field-accordion-inner">'; } //Secondary Fields if(this.available_field_types[field.type].supports.secondary){ this.available_field_types[field.type].supports.secondary.forEach(function (option) { this.field_option(option, i, language) }.bind(this)) } if(language == 'default' && this.available_field_types[field.type].supports.secondary){ this.output += '</div>'; this.output += '</div>'; } } /** * Build the translatable options * * @param field * @param i */ field_translation_options(field, i){ // If there are no languages, we skip this section if(!this.available_field_types[field.type].languages) return; this.output += '<div class="form-field-accordion">'; this.output += '<div class="form-field-accordion-header">'; this.output += '<a href="#" class="form-field-accordion-open">Translations <i class="wpbs-icon-down-arrow"></i></a>'; this.output += '</div>'; this.output += '<div class="form-field-accordion-inner">'; this.output += '<div class="form-field-tabs">'; this.output += '<div class="form-field-tabs-navigation">'; this.available_field_types[field.type].languages.forEach(function (language, j) { this.output += '<a href="#" data-tab="#form-field-tab-'+language+'-'+i+'-'+j+'"><img src="'+wpbs_localized_data.wpbs_plugins_dir_url+'/assets/img/flags/'+language+'.png" />'+this.languages[language]+'</a>'; }.bind(this)) this.output += '</div>'; this.output += '<div class="form-field-tabs-inner">'; this.available_field_types[field.type].languages.forEach(function (language, j) { this.output += '<div id="form-field-tab-'+language+'-'+i+'-'+j+'" class="form-field-tab form-field-translation form-field-translation-'+language+'">'; this.field_options(field, i, language); this.output += '</div>'; }.bind(this)) this.output += '</div>'; this.output += '</div>'; this.output += '</div>'; this.output += '</div>'; } /** * Build the field option * * @param field * @param i */ field_option(option, i, language = 'default'){ // If we build translation options and the field does not support translation, we skip it if(language != 'default' && this.available_field_types_options[option].translatable == false) return; var key = this.available_field_types_options[option].key; var label = this.available_field_types_options[option].label; var input = typeof this.available_field_types_options[option].input !== 'undefined' ? this.available_field_types_options[option].input : 'text'; var options = typeof this.available_field_types_options[option].options !== 'undefined' ? this.available_field_types_options[option].options : false; this.output += '<div class="form-field-row form-field-row-type-'+key+'">'; switch(key){ case 'required': case 'hide_label': this.field_option_type_checkbox(key, label, input, language, i); break; case 'options': this.field_option_type_options(key, label, input, language, i); break; case 'options_pricing': this.field_option_type_options_pricing(key, label, input, language, i); break; case 'pricing_type': this.field_option_type_pricing_type(key, label, input, language, options, i); break; default: if(key.indexOf('notice_') === -1){ this.field_option_type_default(key, label, input, language, i); } else { this.field_option_type_notice(key, label); } } this.output += '</div>'; } /** * Build the field option inputs based on type * * @param key * @param label * @param language * @param i */ field_option_type_default(key, label, input, language, i){ var value = (typeof this.form_data[i]['values'][language] !== 'undefined' && typeof this.form_data[i]['values'][language][key] !== 'undefined') ? this.form_data[i]['values'][language][key] : ''; if(input == 'textarea'){ this.output += '<label for="form-field-'+ i +'-'+ key +'">' + label + '</label><textarea id="form-field-'+ i +'-'+ key +'" type="text" data-language="' + language + '" data-key="' + key + '" name="form_fields[' + i + '][values][' + language + '][' + key + ']">' + value + '</textarea>'; } else { this.output += '<label for="form-field-'+ i +'-'+ key +'">' + label + '</label><input id="form-field-'+ i +'-'+ key +'" type="text" data-language="' + language + '" data-key="' + key + '" value="' + value + '" name="form_fields[' + i + '][values][' + language + '][' + key + ']" />'; } } field_option_type_pricing_type(key, label, input, language, options, i){ var value = (typeof this.form_data[i]['values'][language] !== 'undefined' && typeof this.form_data[i]['values'][language][key] !== 'undefined') ? this.form_data[i]['values'][language][key] : ''; this.output += '<label for="form-field-'+ i +'-'+ key +'">' + label + '</label><select id="form-field-'+ i +'-'+ key +'" type="text" data-language="' + language + '" data-key="' + key + '" value="' + value + '" name="form_fields[' + i + '][values][' + language + '][' + key + ']">'; for(var option in options){ var selected = (value == option) ? 'selected' : ''; this.output += '<option value="'+option+'" '+selected+'>'+options[option]+'</option>'; } this.output += '</select>'; } field_option_type_notice(key, label){ this.output += '<div class="wpbs-page-notice notice-error"><p>' + label + '</p></div>'; } field_option_type_checkbox(key, label, input, language, i){ var value = (typeof this.form_data[i]['values'][language][key] !== 'undefined' && this.form_data[i]['values'][language][key] == 'on') ? 'checked' : ''; this.output += '<label for="form-field-'+ i +'-'+ key +'">' + label + '</label><label class="wpbs-checkbox-switch" for="form-field-'+ i +'-'+ key +'"><input id="form-field-'+ i +'-'+ key +'" type="checkbox" data-language="' + language + '" data-key="' + key + '" ' + value + ' name="form_fields[' + i + '][values][' + language + '][' + key + ']" /><div class="wpbs-checkbox-slider"></div></label>'; } field_option_type_options(key, label, input, language, i){ this.output += '<div class="form-field-options">'; this.output += '<label>'+label+'</label>'; this.output += '<div class="form-field-options-inner">'; this.output += '<div class="form-field-option-placeholder"><input type="text" data-name="form_fields[' + i + '][values][' + language + '][' + key + '][]" data-language="' + language + '" data-key="' + key + '" /><a href="#" class="form-field-option-field-remove"><i class="wpbs-icon-close"></i></a></div>'; this.output += '<div class="form-field-options-inner-fields">'; if (typeof this.form_data[i]['values'][language] !== 'undefined' && typeof this.form_data[i]['values'][language][key] !== 'undefined') { this.form_data[i]['values'][language][key].forEach(function (value) { if (value) this.output += '<div><input type="text" data-language="' + language + '" data-key="' + key + '" name="form_fields[' + i + '][values][' + language + '][' + key + '][]" value="' + value + '" /><a href="#" class="form-field-option-field-remove"><i class="wpbs-icon-close"></i></a></div>'; }.bind(this)) } this.output += '</div>'; this.output += '<a href="#" class="form-field-add-option button button-secondary">Add Option</a>'; this.output += '</div>'; this.output += '</div>'; } field_option_type_options_pricing(key, label, input, language, i){ this.output += '<div class="form-field-options">'; this.output += '<label>'+label+'</label>'; this.output += '<div class="form-field-options-inner">'; this.output += '<div class="form-field-option-placeholder"><input type="number" class="form-field-pricing-fields price" /><input type="text" class="form-field-pricing-fields value" /><input type="hidden" data-name="form_fields[' + i + '][values][' + language + '][' + key + '][]" data-language="' + language + '" data-key="' + key + '" /><a href="#" class="form-field-option-field-remove"><i class="wpbs-icon-close"></i></a></div>'; this.output += '<div class="form-field-options-inner-heading"><span>Price</span><span>Name</span></div>'; this.output += '<div class="form-field-options-inner-fields">'; if (typeof this.form_data[i]['values'][language] !== 'undefined' && typeof this.form_data[i]['values'][language][key] !== 'undefined') { this.form_data[i]['values'][language][key].forEach(function (value) { if (value) var values = value.split('|'); this.output += '<div><input type="number" class="form-field-pricing-fields price" value="'+values[0]+'" /><input type="text" class="form-field-pricing-fields value" value="'+values[1]+'" /><input type="hidden" data-language="' + language + '" data-key="' + key + '" name="form_fields[' + i + '][values][' + language + '][' + key + '][]" value="' + value + '" /><a href="#" class="form-field-option-field-remove"><i class="wpbs-icon-close"></i></a></div>'; }.bind(this)) } this.output += '</div>'; this.output += '<a href="#" class="form-field-add-option button button-secondary">Add Option</a>'; this.output += '</div>'; this.output += '</div>'; } /** * Render the form */ render(){ this.build(); this.wrapper.innerHTML = this.output; } }goog.provide('ol.test.style.Fill'); describe('ol.style.Fill', function() { describe('constructor', function() { it('accepts literal values', function() { var symbolizer = new ol.style.Fill({ color: '#BADA55' }); expect(symbolizer).to.be.a(ol.style.Fill); }); it('accepts expressions', function() { var symbolizer = new ol.style.Fill({ opacity: ol.expr.parse('value / 100'), color: ol.expr.parse('fillAttr') }); expect(symbolizer).to.be.a(ol.style.Fill); }); it('accepts zIndex', function() { var symbolizer = new ol.style.Fill({ opacity: ol.expr.parse('value / 100'), color: ol.expr.parse('fillAttr'), zIndex: 3 }); expect(symbolizer).to.be.a(ol.style.Fill); }); }); describe('#createLiteral()', function() { it('evaluates expressions with the given feature', function() { var symbolizer = new ol.style.Fill({ opacity: ol.expr.parse('value / 100'), color: ol.expr.parse('fillAttr') }); var feature = new ol.Feature({ value: 42, fillAttr: '#ff0000', geometry: new ol.geom.Polygon( [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]) }); var literal = symbolizer.createLiteral(feature); expect(literal).to.be.a(ol.style.PolygonLiteral); expect(literal.fillOpacity).to.be(42 / 100); expect(literal.fillColor).to.be('#ff0000'); expect(literal.zIndex).to.be(0); }); it('applies default opacity', function() { var symbolizer = new ol.style.Fill({ color: '#ff0000' }); var literal = symbolizer.createLiteral(ol.geom.GeometryType.POLYGON); expect(literal).to.be.a(ol.style.PolygonLiteral); expect(literal.fillColor).to.be('#ff0000'); expect(literal.fillOpacity).to.be(0.4); }); it('applies default color', function() { var symbolizer = new ol.style.Fill({ opacity: 0.8 }); var literal = symbolizer.createLiteral(ol.geom.GeometryType.POLYGON); expect(literal).to.be.a(ol.style.PolygonLiteral); expect(literal.fillColor).to.be('#ffffff'); expect(literal.fillOpacity).to.be(0.8); }); it('casts opacity to number', function() { var symbolizer = new ol.style.Fill({ opacity: ol.expr.parse('opacity'), color: '#ff00ff' }); var feature = new ol.Feature({ opacity: '0.55', geometry: new ol.geom.Polygon( [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]) }); var literal = symbolizer.createLiteral(feature); expect(literal).to.be.a(ol.style.PolygonLiteral); expect(literal.fillOpacity).to.be(0.55); }); it('handles zIndex', function() { var symbolizer = new ol.style.Fill({ opacity: 0.8, zIndex: 2 }); var literal = symbolizer.createLiteral(ol.geom.GeometryType.POLYGON); expect(literal).to.be.a(ol.style.PolygonLiteral); expect(literal.fillColor).to.be('#ffffff'); expect(literal.fillOpacity).to.be(0.8); expect(literal.zIndex).to.be(2); }); it('applies default zIndex', function() { var symbolizer = new ol.style.Fill({ opacity: 0.8 }); var literal = symbolizer.createLiteral(ol.geom.GeometryType.POLYGON); expect(literal).to.be.a(ol.style.PolygonLiteral); expect(literal.zIndex).to.be(0); }); it('casts zIndex to number', function() { var symbolizer = new ol.style.Fill({ zIndex: ol.expr.parse('zIndex'), color: '#ff00ff' }); var feature = new ol.Feature({ zIndex: '11', geometry: new ol.geom.Polygon( [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]) }); var literal = symbolizer.createLiteral(feature); expect(literal).to.be.a(ol.style.PolygonLiteral); expect(literal.zIndex).to.be(11); }); }); describe('#getColor()', function() { it('returns the fill color', function() { var symbolizer = new ol.style.Fill({ color: '#ff0000' }); var color = symbolizer.getColor(); expect(color).to.be.a(ol.expr.Literal); expect(color.getValue()).to.be('#ff0000'); }); }); describe('#getOpacity()', function() { it('returns the fill opacity', function() { var symbolizer = new ol.style.Fill({ color: '#ffffff', opacity: 0.123 }); var opacity = symbolizer.getOpacity(); expect(opacity).to.be.a(ol.expr.Literal); expect(opacity.getValue()).to.be(0.123); }); }); describe('#getZIndex()', function() { it('returns the zIndex', function() { var symbolizer = new ol.style.Fill({ color: '#ffffff', zIndex: 11 }); var zIndex = symbolizer.getZIndex(); expect(zIndex).to.be.a(ol.expr.Literal); expect(zIndex.getValue()).to.be(11); }); }); describe('#setColor()', function() { it('sets the fill color', function() { var symbolizer = new ol.style.Fill({ color: '#ff0000' }); symbolizer.setColor(new ol.expr.Literal('#0000ff')); var color = symbolizer.getColor(); expect(color).to.be.a(ol.expr.Literal); expect(color.getValue()).to.be('#0000ff'); }); it('throws when not provided an expression', function() { var symbolizer = new ol.style.Fill({ color: '#ff0000' }); expect(function() { symbolizer.setColor('#0000ff'); }).throwException(function(err) { expect(err).to.be.a(goog.asserts.AssertionError); }); }); }); describe('#setOpacity()', function() { it('sets the fill opacity', function() { var symbolizer = new ol.style.Fill({ color: '#ff0000' }); symbolizer.setOpacity(new ol.expr.Literal(0.321)); var opacity = symbolizer.getOpacity(); expect(opacity).to.be.a(ol.expr.Literal); expect(opacity.getValue()).to.be(0.321); }); it('throws when not provided an expression', function() { var symbolizer = new ol.style.Fill({ color: '#ff0000' }); expect(function() { symbolizer.setOpacity(0.123); }).throwException(function(err) { expect(err).to.be.a(goog.asserts.AssertionError); }); }); }); }); goog.require('goog.asserts.AssertionError'); goog.require('ol.Feature'); goog.require('ol.expr'); goog.require('ol.expr.Literal'); goog.require('ol.geom.GeometryType'); goog.require('ol.geom.Polygon'); goog.require('ol.style.Fill'); goog.require('ol.style.PolygonLiteral'); /// ========================================================================== /// MODULE: Observable /// DESCRIPTION: Simple implementation of the observable pattern. /// /// Copyright 2019 by <NAME> /// 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: /// 1. The origin of this source code must not be misrepresented; you must not /// claim that you wrote the original source code. If you use this source code /// in a product, an acknowledgment in the product documentation would be /// appreciated but is not required. /// 2. Altered source versions must be plainly marked as such, and must not be /// misrepresented as being the original source code. /// 3. This notice may not be removed or altered from any source distribution. /// /// 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. /// ========================================================================== class Observable { constructor () { this.observers = []; this.data = null; } subscribe (fn) { this.observers.push(fn); } unsubscribe(fn) { this.observers = this.observers.filter((subscriber) => subscriber !== fn); } getValue () { return this.data; } setValue (dat) { this.data = dat; this.observers.forEach((subscriber) => subscriber(this.data)); } } <reponame>beads89/pizza-parlor // Business Logic function Pizza(pizzaSize, pizzaTopping) { this.pizzaSize = pizzaSize; this.pizzaTopping = pizzaTopping; this.pizzaPrice = 0 } Pizza.prototype.size = function(pizzaSize) { if (this.pizzaSize === "Large") { this.pizzaPrice += 15 } else { this.pizzaPrice += 20 } } Pizza.prototype.topping = function(pizzaTopping) { for (let i = 0; i < this.pizzaTopping.length; i++) { this.pizzaPrice += 3; } }; // UI Logic $(document).ready(function() { $("form#pizzaOrder").submit(function(event) { event.preventDefault(); let sizeInput = $("input:radio[name=sizes]:checked").val(); let toppingInput = $(".toppings:checked"); let toppingOutput = []; toppingInput.each(function() { toppingOutput.push($(this).val()); }) let output = new Pizza(sizeInput, toppingOutput); output.size(); output.topping(); let toppingSpaced = (output.pizzaTopping).join(", "); $("#pizzaToppings").text(toppingSpaced); $(".ordered").show(); $("#sizeInput").text(output.pizzaSize); $("#pizzaCost").text("$" + output.pizzaPrice); }); }) (function(){ 'use strict'; angular.module('LighthouseApp', ['ngMaterial', 'users', 'questions', 'assignments', 'dashboard', 'restangular','ui.router']) .config(function($mdThemingProvider, $mdIconProvider, RestangularProvider,$stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise("/login"); $stateProvider .state('login', { url: "/login", templateUrl: "assets/partials/login.html" }) .state('dashboard', { url: "/dashboard", templateUrl: "assets/partials/dashboard.html" }) .state('assignment_details', { url: "/assignment_details/:assignmentId", templateUrl: "assets/partials/assignment_details.html" }); $mdIconProvider .defaultIconSet("./assets/svg/avatars.svg", 128) .icon("menu" , "./assets/svg/menu.svg" , 24) .icon("share" , "./assets/svg/share.svg" , 24) .icon("google_plus", "./assets/svg/google_plus.svg" , 512) .icon("hangouts" , "./assets/svg/hangouts.svg" , 512) .icon("twitter" , "./assets/svg/twitter.svg" , 512) .icon("phone" , "./assets/svg/phone.svg" , 512); $mdThemingProvider.theme('default') .primaryPalette('brown') .accentPalette('red'); RestangularProvider.setBaseUrl('http://sandbox.api.hmhco.com/v1'); RestangularProvider.setFullRequestInterceptor(function(element, operation, route, url, headers, params, httpConfig) { debugger; if (url == 'http://sandbox.api.hmhco.com/v1/sample_token'){ debugger; headers['Content-Type'] = 'application/x-www-form-urlencoded' } else { headers['Authorization']='SIF_HMACSHA256 <KEY>' } headers['Vnd-HMH-Api-Key']='<KEY>' return { element: element, params: params, headers: headers, httpConfig: httpConfig }; }); }); })(); <reponame>ajstrand/text-buffer<filename>lib/marker-layer.js (function() { var Emitter, Marker, MarkerIndex, MarkerLayer, Point, Range, SerializationVersion, clone, filterSet, intersectSet; clone = require("underscore-plus").clone; Emitter = require('event-kit').Emitter; Point = require("./point"); Range = require("./range"); Marker = require("./marker"); MarkerIndex = require("superstring").MarkerIndex; intersectSet = require("./set-helpers").intersectSet; SerializationVersion = 2; module.exports = MarkerLayer = (function() { MarkerLayer.deserialize = function(delegate, state) { var store; store = new MarkerLayer(delegate, 0); store.deserialize(state); return store; }; MarkerLayer.deserializeSnapshot = function(snapshot) { var layerId, markerId, markerSnapshot, markerSnapshots, result; result = {}; for (layerId in snapshot) { markerSnapshots = snapshot[layerId]; result[layerId] = {}; for (markerId in markerSnapshots) { markerSnapshot = markerSnapshots[markerId]; result[layerId][markerId] = clone(markerSnapshot); result[layerId][markerId].range = Range.fromObject(markerSnapshot.range); } } return result; }; /* Section: Lifecycle */ function MarkerLayer(delegate1, id3, options) { var ref, ref1, ref2; this.delegate = delegate1; this.id = id3; this.maintainHistory = (ref = options != null ? options.maintainHistory : void 0) != null ? ref : false; this.destroyInvalidatedMarkers = (ref1 = options != null ? options.destroyInvalidatedMarkers : void 0) != null ? ref1 : false; this.role = options != null ? options.role : void 0; if (this.role === "selections") { this.delegate.registerSelectionsMarkerLayer(this); } this.persistent = (ref2 = options != null ? options.persistent : void 0) != null ? ref2 : false; this.emitter = new Emitter; this.index = new MarkerIndex; this.markersById = {}; this.markersWithChangeListeners = new Set; this.markersWithDestroyListeners = new Set; this.displayMarkerLayers = new Set; this.destroyed = false; this.emitCreateMarkerEvents = false; } MarkerLayer.prototype.copy = function() { var copy, marker, markerId, ref, snapshot; copy = this.delegate.addMarkerLayer({ maintainHistory: this.maintainHistory, role: this.role }); ref = this.markersById; for (markerId in ref) { marker = ref[markerId]; snapshot = marker.getSnapshot(null); copy.createMarker(marker.getRange(), marker.getSnapshot()); } return copy; }; MarkerLayer.prototype.destroy = function() { if (this.destroyed) { return; } this.clear(); this.delegate.markerLayerDestroyed(this); this.displayMarkerLayers.forEach(function(displayMarkerLayer) { return displayMarkerLayer.destroy(); }); this.displayMarkerLayers.clear(); this.destroyed = true; this.emitter.emit('did-destroy'); return this.emitter.clear(); }; MarkerLayer.prototype.clear = function() { this.markersWithDestroyListeners.forEach(function(marker) { return marker.destroy(); }); this.markersWithDestroyListeners.clear(); this.markersById = {}; this.index = new MarkerIndex; this.displayMarkerLayers.forEach(function(layer) { return layer.didClearBufferMarkerLayer(); }); return this.delegate.markersUpdated(this); }; MarkerLayer.prototype.isDestroyed = function() { return this.destroyed; }; MarkerLayer.prototype.isAlive = function() { return !this.destroyed; }; /* Section: Querying */ MarkerLayer.prototype.getMarker = function(id) { return this.markersById[id]; }; MarkerLayer.prototype.getMarkers = function() { var id, marker, ref, results; ref = this.markersById; results = []; for (id in ref) { marker = ref[id]; results.push(marker); } return results; }; MarkerLayer.prototype.getMarkerCount = function() { return Object.keys(this.markersById).length; }; MarkerLayer.prototype.findMarkers = function(params) { var end, i, key, len, markerIds, position, ref, ref1, ref2, ref3, ref4, ref5, result, start, value; markerIds = null; ref = Object.keys(params); for (i = 0, len = ref.length; i < len; i++) { key = ref[i]; value = params[key]; switch (key) { case 'startPosition': markerIds = filterSet(markerIds, this.index.findStartingAt(Point.fromObject(value))); break; case 'endPosition': markerIds = filterSet(markerIds, this.index.findEndingAt(Point.fromObject(value))); break; case 'startsInRange': ref1 = Range.fromObject(value), start = ref1.start, end = ref1.end; markerIds = filterSet(markerIds, this.index.findStartingIn(start, end)); break; case 'endsInRange': ref2 = Range.fromObject(value), start = ref2.start, end = ref2.end; markerIds = filterSet(markerIds, this.index.findEndingIn(start, end)); break; case 'containsPoint': case 'containsPosition': position = Point.fromObject(value); markerIds = filterSet(markerIds, this.index.findContaining(position, position)); break; case 'containsRange': ref3 = Range.fromObject(value), start = ref3.start, end = ref3.end; markerIds = filterSet(markerIds, this.index.findContaining(start, end)); break; case 'intersectsRange': ref4 = Range.fromObject(value), start = ref4.start, end = ref4.end; markerIds = filterSet(markerIds, this.index.findIntersecting(start, end)); break; case 'startRow': markerIds = filterSet(markerIds, this.index.findStartingIn(Point(value, 0), Point(value, 2e308))); break; case 'endRow': markerIds = filterSet(markerIds, this.index.findEndingIn(Point(value, 0), Point(value, 2e308))); break; case 'intersectsRow': markerIds = filterSet(markerIds, this.index.findIntersecting(Point(value, 0), Point(value, 2e308))); break; case 'intersectsRowRange': markerIds = filterSet(markerIds, this.index.findIntersecting(Point(value[0], 0), Point(value[1], 2e308))); break; case 'containedInRange': ref5 = Range.fromObject(value), start = ref5.start, end = ref5.end; markerIds = filterSet(markerIds, this.index.findContainedIn(start, end)); break; default: continue; } delete params[key]; } if (markerIds == null) { markerIds = new Set(Object.keys(this.markersById)); } result = []; markerIds.forEach((function(_this) { return function(markerId) { var marker; marker = _this.markersById[markerId]; if (!marker.matchesParams(params)) { return; } return result.push(marker); }; })(this)); return result.sort(function(a, b) { return a.compare(b); }); }; MarkerLayer.prototype.getRole = function() { return this.role; }; /* Section: Marker creation */ MarkerLayer.prototype.markRange = function(range, options) { if (options == null) { options = {}; } return this.createMarker(this.delegate.clipRange(range), Marker.extractParams(options)); }; MarkerLayer.prototype.markPosition = function(position, options) { if (options == null) { options = {}; } position = this.delegate.clipPosition(position); options = Marker.extractParams(options); options.tailed = false; return this.createMarker(this.delegate.clipRange(new Range(position, position)), options); }; /* Section: Event subscription */ MarkerLayer.prototype.onDidUpdate = function(callback) { return this.emitter.on('did-update', callback); }; MarkerLayer.prototype.onDidCreateMarker = function(callback) { this.emitCreateMarkerEvents = true; return this.emitter.on('did-create-marker', callback); }; MarkerLayer.prototype.onDidDestroy = function(callback) { return this.emitter.on('did-destroy', callback); }; /* Section: Private - TextBuffer interface */ MarkerLayer.prototype.splice = function(start, oldExtent, newExtent) { var invalidated; invalidated = this.index.splice(start, oldExtent, newExtent); return invalidated.touch.forEach((function(_this) { return function(id) { var marker, ref; marker = _this.markersById[id]; if ((ref = invalidated[marker.getInvalidationStrategy()]) != null ? ref.has(id) : void 0) { if (_this.destroyInvalidatedMarkers) { return marker.destroy(); } else { return marker.valid = false; } } }; })(this)); }; MarkerLayer.prototype.restoreFromSnapshot = function(snapshots, alwaysCreate) { var existingMarkerIds, i, id, j, len, len1, marker, newMarker, range, results, snapshot, snapshotIds; if (snapshots == null) { return; } snapshotIds = Object.keys(snapshots); existingMarkerIds = Object.keys(this.markersById); for (i = 0, len = snapshotIds.length; i < len; i++) { id = snapshotIds[i]; snapshot = snapshots[id]; if (alwaysCreate) { this.createMarker(snapshot.range, snapshot, true); continue; } if (marker = this.markersById[id]) { marker.update(marker.getRange(), snapshot, true, true); } else { marker = snapshot.marker; if (marker) { this.markersById[marker.id] = marker; range = snapshot.range; this.index.insert(marker.id, range.start, range.end); marker.update(marker.getRange(), snapshot, true, true); if (this.emitCreateMarkerEvents) { this.emitter.emit('did-create-marker', marker); } } else { newMarker = this.createMarker(snapshot.range, snapshot, true); } } } results = []; for (j = 0, len1 = existingMarkerIds.length; j < len1; j++) { id = existingMarkerIds[j]; if ((marker = this.markersById[id]) && (snapshots[id] == null)) { results.push(marker.destroy(true)); } else { results.push(void 0); } } return results; }; MarkerLayer.prototype.createSnapshot = function() { var i, id, len, marker, ranges, ref, result; result = {}; ranges = this.index.dump(); ref = Object.keys(this.markersById); for (i = 0, len = ref.length; i < len; i++) { id = ref[i]; marker = this.markersById[id]; result[id] = marker.getSnapshot(Range.fromObject(ranges[id])); } return result; }; MarkerLayer.prototype.emitChangeEvents = function(snapshot) { return this.markersWithChangeListeners.forEach(function(marker) { var ref; if (!marker.isDestroyed()) { return marker.emitChangeEvent(snapshot != null ? (ref = snapshot[marker.id]) != null ? ref.range : void 0 : void 0, true, false); } }); }; MarkerLayer.prototype.serialize = function() { var i, id, len, marker, markersById, ranges, ref, snapshot; ranges = this.index.dump(); markersById = {}; ref = Object.keys(this.markersById); for (i = 0, len = ref.length; i < len; i++) { id = ref[i]; marker = this.markersById[id]; snapshot = marker.getSnapshot(Range.fromObject(ranges[id]), false); markersById[id] = snapshot; } return { id: this.id, maintainHistory: this.maintainHistory, role: this.role, persistent: this.persistent, markersById: markersById, version: SerializationVersion }; }; MarkerLayer.prototype.deserialize = function(state) { var id, markerState, range, ref; if (state.version !== SerializationVersion) { return; } this.id = state.id; this.maintainHistory = state.maintainHistory; this.role = state.role; if (this.role === "selections") { this.delegate.registerSelectionsMarkerLayer(this); } this.persistent = state.persistent; ref = state.markersById; for (id in ref) { markerState = ref[id]; range = Range.fromObject(markerState.range); delete markerState.range; this.addMarker(id, range, markerState); } }; /* Section: Private - Marker interface */ MarkerLayer.prototype.markerUpdated = function() { return this.delegate.markersUpdated(this); }; MarkerLayer.prototype.destroyMarker = function(marker, suppressMarkerLayerUpdateEvents) { if (suppressMarkerLayerUpdateEvents == null) { suppressMarkerLayerUpdateEvents = false; } if (this.markersById.hasOwnProperty(marker.id)) { delete this.markersById[marker.id]; this.index.remove(marker.id); this.markersWithChangeListeners["delete"](marker); this.markersWithDestroyListeners["delete"](marker); this.displayMarkerLayers.forEach(function(displayMarkerLayer) { return displayMarkerLayer.destroyMarker(marker.id); }); if (!suppressMarkerLayerUpdateEvents) { return this.delegate.markersUpdated(this); } } }; MarkerLayer.prototype.hasMarker = function(id) { return !this.destroyed && this.index.has(id); }; MarkerLayer.prototype.getMarkerRange = function(id) { return Range.fromObject(this.index.getRange(id)); }; MarkerLayer.prototype.getMarkerStartPosition = function(id) { return Point.fromObject(this.index.getStart(id)); }; MarkerLayer.prototype.getMarkerEndPosition = function(id) { return Point.fromObject(this.index.getEnd(id)); }; MarkerLayer.prototype.compareMarkers = function(id1, id2) { return this.index.compare(id1, id2); }; MarkerLayer.prototype.setMarkerRange = function(id, range) { var end, ref, start; ref = Range.fromObject(range), start = ref.start, end = ref.end; start = this.delegate.clipPosition(start); end = this.delegate.clipPosition(end); this.index.remove(id); return this.index.insert(id, start, end); }; MarkerLayer.prototype.setMarkerIsExclusive = function(id, exclusive) { return this.index.setExclusive(id, exclusive); }; MarkerLayer.prototype.createMarker = function(range, params, suppressMarkerLayerUpdateEvents) { var id, marker, ref; if (suppressMarkerLayerUpdateEvents == null) { suppressMarkerLayerUpdateEvents = false; } id = this.delegate.getNextMarkerId(); marker = this.addMarker(id, range, params); this.delegate.markerCreated(this, marker); if (!suppressMarkerLayerUpdateEvents) { this.delegate.markersUpdated(this); } marker.trackDestruction = (ref = this.trackDestructionInOnDidCreateMarkerCallbacks) != null ? ref : false; if (this.emitCreateMarkerEvents) { this.emitter.emit('did-create-marker', marker); } marker.trackDestruction = false; return marker; }; /* Section: Internal */ MarkerLayer.prototype.addMarker = function(id, range, params) { range = Range.fromObject(range); Point.assertValid(range.start); Point.assertValid(range.end); this.index.insert(id, range.start, range.end); return this.markersById[id] = new Marker(id, this, range, params); }; MarkerLayer.prototype.emitUpdateEvent = function() { return this.emitter.emit('did-update'); }; return MarkerLayer; })(); filterSet = function(set1, set2) { if (set1) { intersectSet(set1, set2); return set1; } else { return set2; } }; }).call(this); <reponame>Graphiy/actionman /** * This class represents html component * Recieves container to render to * Can fire events through shared instance of Actionman */ import * as uuid from '@graphiy/uuid62' export default class Component { constructor (p = {}) { this.id = p.id || `id${uuid.v4()}` this.$el = $('<div/>').attr('id', this.id) this.$el.addClass(this.constructor.name) p.container.append(this.$el) this.el = document.querySelector(`#${this.id}`) this.actionman = p.actionman _.each(this.constructor.actions, (action) => { this.actionman.set(action, this, this.id) }) } } <gh_stars>10-100 const React = require('react'); const schema = require('../schema'); /** * Rendering for a slate node. It doesn't consider children. * * @type {React} */ const NodeWrapper = React.createClass({ propTypes: { node: React.PropTypes.object.isRequired, attributes: React.PropTypes.object.isRequired, original: React.PropTypes.object, children: React.PropTypes.node }, render() { const { node, attributes, original, children } = this.props; const Renderer = schema.nodes[node.type] || ( node.kind == 'block' ? schema.defaultBlock : schema.defaultInline ); return ( <Renderer node={node} attributes={attributes} original={original}> {children} </Renderer> ); } }); module.exports = NodeWrapper; const DatabaseObject = require("./DatabaseObject"); const TagsManager = require("./TagsManager"); const H_ALIGN_CODES = ["left", "center", "right"]; const V_ALIGN_CODES = ["baseline", "bottom", "middle", "top"]; class Text extends DatabaseObject { /** * @param {number} x - x * @param {number} y - y * @param {number} height - Text height * @param {number} rotation - Text rotation * @param {string} value - the string itself * @param {string} [horizontalAlignment="left"] left | center | right * @param {string} [verticalAlignment="baseline"] baseline | bottom | middle | top */ constructor( x, y, height, rotation, value, horizontalAlignment = "left", verticalAlignment = "baseline" ) { super(["AcDbEntity", "AcDbText"]); this.x = x; this.y = y; this.height = height; this.rotation = rotation; this.value = value; this.hAlign = horizontalAlignment; this.vAlign = verticalAlignment; } tags() { const manager = new TagsManager(); //https://www.autodesk.com/techpubs/autocad/acadr14/dxf/text_al_u05_c.htm manager.addTag(0, "TEXT"); manager.addTags(super.tags()); manager.addTag(8, this.layer.name); manager.addPointTags(this.x, this.y); manager.addTag(40, this.height); manager.addTag(1, this.value); manager.addTag(50, this.rotation); if ( H_ALIGN_CODES.includes(this.hAlign, 1) || V_ALIGN_CODES.includes(this.vAlign, 1) ) { manager.addTag(72, Math.max(H_ALIGN_CODES.indexOf(this.hAlign), 0)); manager.addTagsByElements([ [11, this.x], [21, this.y], [31, 0], ]); /* AutoCAD needs this one more time, yes, exactly here. */ manager.addTag(100, "AcDbText"); manager.addTag(73, Math.max(V_ALIGN_CODES.indexOf(this.vAlign), 0)); } else { /* AutoCAD needs this one more time. */ manager.addTag(100, "AcDbText"); } return manager.tags(); } } module.exports = Text; "use strict"; // The browser platform with a compiler var platform_browser_dynamic_1 = require('@angular/platform-browser-dynamic'); // The app module var app_module_1 = require('./app.module'); // Compile and launch the module platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(app_module_1.AppModule); /* Copyright 2016 Google Inc. All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at http://angular.io/license */ //# sourceMappingURL=main.js.map<filename>index.js const moment = require('moment') const http = require('http') const url = require('url') let port = process.env.PORT if (port === undefined) {port = 3000} const unix2natural = require('./unix2natural.js') const app = http.createServer(function(req, res){ let myres = { unix: null, natural: null } if (req.method === 'GET') { var str = url.parse(req.url).pathname.split('%20').join(' ').substr(1).trim() if (isNaN(str) === false) {str = Number(str)} else { str += ' UTC' } const d = new Date(str) if (d.toString() !== 'Invalid Date') { myres.unix = d.getTime() myres.natural = unix2natural(d.getTime()) myres.roughly = moment(d).from(Date.now()) } } res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'}); res.write(JSON.stringify(myres)) res.end() }) app.listen(port, function(a){ console.log('server started at http://localhost:'+port+'/') }) <reponame>rogergcc/cinema-films-trivia<filename>server.js 'use strict' if (process.env.NODE_ENV !== 'production') { require('dotenv').config() } const DBconnection = require('./config/database') const CONFIG = require('./config/config') const App = require('./app/app') const errorHandler = require('./app/middleware/error') DBconnection() App.use(errorHandler) App.listen(CONFIG.PORT, function (error) { if (error) return console.log(error) // console.log(`Servidor corriendo en el Puerto: ${CONFIG.HOST}:${CONFIG.PORT}`); console.log( `We are live on ${process.env.NODE_ENV} mode on port ${CONFIG.PORT}`.yellow.bold ) console.log(`My list Movies json: ${CONFIG.HOST}:${CONFIG.PORT}/api/v1/getMovies`) }) // Handle unhandled promise rejections process.on('unhandledRejection', (err, promise) => { console.log(`Error: ${err.message}`.red) // Close server & exit process server.close(() => process.exit(1)) }) import React from 'react' import PropTypes from 'prop-types' import Layout from '../layouts' import { css } from 'react-emotion' import * as styles from '../components/IndexPageStyles/TermsAndLicensesStyles/styles' import ShopNavigation from '../components/ShopNavigation/index' import SEO from '../components/SEO' import ScrollTop from '../components/ScrollToTop/index' const TermsAndLicenses = ({ location }) => ( <Layout location={location}> <SEO title={'HAHA Studio Terms and Licenses'} description={'HAHA Studio terms, licenses, conditions'} //location={location} /> <ScrollTop /> <div className={css(styles.termsLicensesWrapper)}> <div className={css(styles.termsLicensesTitle)}> Terms/Licenses <br /> <br /> <br /> </div> <div className={css(styles.termsLicensesTextWrapper)}> Terms and Conditions of HAHA studio <br /> <br /> The following Terms and Conditions shall apply exclusively to any and all contracts, agreements and interactions between HAAH AB/Mr Arash Eskafi, <NAME>, Pipersgatan 14, 11224 Stockholm, Sweden (“HAHA studio”) and the customer (“Customer”), including through the website www.hahastudio.se (“Website”). Any additional or inconsistent terms used by the Customer shall not be binding upon HAHA studio, unless HAHA studio gives its express agreement in writing. <br /> <br /> § 1 Offers and Service <br /> <br /> Any offer, quotation or price information by HAHA studio regarding the fonts, text, graphics and any other items accessed from or via this Website or otherwise through the internet (“Own Content”) is without obligation and subject to change without notice unless an offer has been designated as binding. <br /> HAHA studio expressly reserves itself the right to change, amend, cancel or close down parts or the entire Own Content and the Website definitively or from time to time. HAHA studio makes no warranties, express or implied, that its services will be uninterrupted, error-free or free of viruses or other harmful components, unless respective faults were caused by HAHA studio by act of gross negligence or intent. <br /> <br /> § 2 Contract <br /> <br /> By entering and using the Website, the Costumer accepts the Terms and Conditions and expressly adheres to the following: <br /> A contract for digital goods is made effective between the costumer and HAHA studio by placing an order. <br /> When placing an order for physical goods, the order shall be deemed to be accepted by HAHA studio either upon subsequent (e-mail) acceptance of the order or by dispatching the product. <br /> <br /> § 3 Right to Withdrawal <br /> <br /> A) Digital Goods <br /> The Customer is informed about his/her rights of withdrawal in accordance with § 356 (5) Swedish Civil Code (SGB) and hereby expressly consents to and accepts by placing an order: (i) that HAHA studio executes the contract prior to the end of the withdrawal period; and (ii) that the Customer forfeits his respective withdrawal rights pertaining to digital media files such as downloads or email attachments (“Digital Goods”) with execution of the contract, i.e. by starting the download. <br /> <br /> B) Physical Goods <br /> The following rights of withdrawal apply to Customers only who act as a consumer acc. to § 13 BGB, i.e. predominantly not for business purposes. <br /> <br /> (1) Right of withdrawal The Customer has the right to withdraw from the contract with HAHA studio within 14 days without giving any reason. <br /> The withdrawal period will expire after 14 days from the day on which the Customers acquires, or a third party other than the carrier and indicated by the Customer acquires, physical possession of the goods. <br /> To exercise the right of withdrawal, the Customer must inform HAHA studio, Pipersgatan 14, 11224 Stockholm, of the decision to withdraw from the contract by an unequivocal statement (e.g. a letter sent by post, fax or e-mail). The Customer may use the attached model withdrawal form, but this is not mandatory. <br /> To meet the withdrawal deadline, it is sufficient for the Customer to send the communication concerning the exercise of the right of withdrawal before the withdrawal period has expired. <br /> <br /> Effects of withdrawal <br /> <br /> If the Customer withdraws from this contract, HAHA studio shall reimburse to the Customer all payments received from the Customer, including the costs of delivery (with the exception of the supplementary costs resulting from the Customer’s choice of a type of delivery other than the least expensive type of standard delivery offered by HAHA studio), without undue delay and in any event not later than 14 days from the day on which HAHA studio is informed about the Customer’s decision to withdraw from the contract. HAHA studio will carry out such reimbursement using the same means of payment as the Customer used for the initial transaction, unless the Customer has expressly agreed otherwise; in any event, the Customer will not incur any fees as a result of such reimbursement. HAHA studio may withhold reimbursement until HAHA studio has received the goods back or the Customer has supplied evidence of having sent back the goods, whichever is the earliest. <br /> <br /> The Customer shall send back the goods or hand them over to HAHA studio, without undue delay and in any event not later than 14 days from the day on which the Customer communicates its withdrawal from the contract to HAHA studio. The deadline is met if The Customer sends back the goods before the period of 14 days has expired. The Customer will have to bear the direct cost of returning the goods. The Customer is only liable for any diminished value of the goods resulting from the handling other than what is necessary to establish the nature, characteristics and functioning of the goods. <br /> (2) Personalized/Customized products as well as goods on disks where the license seal is destroyed are excluded from the right to withdrawal. <br /> <br /> § 4 Third Party Content <br /> <br /> HAHA studio shall not be liable for content in guest books, discussion forums and chats which are provided by third parties (“Third Party Content”). Any of such Third Party Content does not necessarily represent the opinions, beliefs, or positions of HAHA studio. Please notify HAHA studio to info[at]hahastudio.se of any illegal or offensive Third Party Content. <br /> <br /> § 5 Privacy Policy/Data Protection <br /> <br /> HAHA studio may save and process any data relating to the Customer, to the extent necessary for the purpose of the execution and implementation of the contracts and as long as HAHA studio is required to keep such data in accordance with applicable law. HAHA studio shall not make available any personal data of the Customer to other third parties without the express consent of the Customer, except to the extent that a disclosure is required under applicable law. <br /> <br /> Copyright © 2016-2018 HAHA studio (hahastudio.se) <br /> All Rights Reserved. </div> <ShopNavigation /> </div> </Layout> ) TermsAndLicenses.proptypes = { location: PropTypes.object.isRequired, } export default TermsAndLicenses /** * Module dependencies */ const { PubSub, Topic } = require('@google-cloud/pubsub'); const _ = require('lodash'); class ExtendedPubSub extends PubSub { // Get topic by name async getTopicMatchName(topicName) { const [topics] = await this.getTopics(); const foundTopic = topics.find(topic => topic.name.endsWith(topicName)); // console.log(foundTopic); if (foundTopic) { return foundTopic; } return null; } async createSubscriptionIfNotExists(topicName, name, options = {}) { const topic = await (() => { if (_.isString(topicName)) { return this.createOrGetTopic(topicName); } throw new Error('topicName must be string.'); })(); const [subscriptions] = await topic.getSubscriptions(); if (subscriptions.find(subscription => subscription.name.endsWith(name))) { return Promise.resolve(); } return this.createSubscription(topicName, name, options); } /** * Get topic or create. * @param {string} name The name of the topic * @returns {Topic} */ async createOrGetTopic(name) { const topic = await this.getTopicMatchName(name); if (!topic) { const createdTopic = await this.createTopic(name); // https://googleapis.dev/nodejs/pubsub/1.7.1/PubSub.html#createTopic // [0]: The new topic. // [1]: The full API response. return createdTopic[0]; } return topic; } async createOrGetSubscription(topicOrName, name, options = {}) { await this.createSubscriptionIfNotExists(topicOrName, name, options); return this.subscription(name, options); } } module.exports = ExtendedPubSub; <gh_stars>100-1000 "use strict"; const OAuth = require("./lib/oauth"); module.exports = OAuth; module.exports = { getMongoConnection: function() { return 'mongodb://testuser:testpass@ds149030.mlab.com:49030/mongo-restify-api' } }<gh_stars>0 import React from 'react'; import styled, { keyframes, css } from 'styled-components'; function getShadow(props) { if (props.strength === "1") { if (props.depth === "1") return '0px 2px 4px rgba(0,0,0,0.1)'; if (props.depth === "2") return '0px 4px 16px rgba(0,0,0,0.2)'; if (props.depth === "3") return '0px 6px 22px rgba(0,0,0,0.3)'; return '0px 2px 4px rgba(0,0,0,0.1)'; } if (props.strength === "2") { if (props.depth === "1") return '0px 2px 4px rgba(0,0,0,0.4)'; if (props.depth === "2") return '0px 4px 16px rgba(0,0,0,0.5)'; if (props.depth === "3") return '0px 6px 22px rgba(0,0,0,0.6)'; return '0px 2px 4px rgba(0,0,0,0.3)'; } if (props.strength === "3") { if (props.depth === "1") return '0px 2px 4px rgba(0,0,0,0.7)'; if (props.depth === "2") return '0px 4px 16px rgba(0,0,0,0.8)'; if (props.depth === "3") return '0px 6px 22px rgba(0,0,0,0.9)'; return '0px 2px 4px rgba(0,0,0,0.7)'; } return '0px 2px 4px rgba(0,0,0,0.1)'; } function getCardAnimation(props) { let dir = 'translateY'; let sign = -1; if (props.animDir === 'left' || props.animDir === 'right') dir = 'translateX'; if (props.animDir === 'top' || props.animDir === 'bottom') dir = 'translateY'; if (props.animDir === 'bottom' || props.animDir === 'right') sign = 1; return keyframes` from { opacity: 0; transform: ${dir}(${sign * 22}px); } to { opacity: 1; transform: ${dir}(0px); } `; } const Outer = styled.div` display: flex; flex-direction: column; background-color: ${props => (props.background ? props.background : '#fff')}; ${props => props.color && css`color: ${props.color};`}; border-radius: 4px; width: 100%; box-shadow: ${props => getShadow(props)}; @media print { box-shadow: none; padding: 16px; } `; const Inner = styled.div` padding: 32px; `; const Card = props => <Outer {...props}><Inner>{props.children}</Inner></Outer>; export const CardAnimated = styled(Card)` opacity: 0; transition: opacity 0.2s ease, transform 0.4s ease-in; animation: ${props => getCardAnimation(props)} 1s forwards; animation-delay: 0.2s; `; export default Card; <filename>src/strange-printer/index.js /** * @param {string} s * @return {number} */ const strangePrinter = function (s) { let cache = []; for (let i = 0; i < s.length; ++i) { cache[i] = []; } return printHelper(s, 0, s.length - 1, 0, cache); }; function printHelper(s, begin, end, firstLetterPrinted, cache) { if (begin > end) { return 0; } if (cache[begin][end] !== undefined) { return cache[begin][end] - firstLetterPrinted; } while (begin < end && s[begin + 1] === s[begin]) { ++begin; } let minSteps = 1 - firstLetterPrinted + printHelper(s, begin + 1, end, 0, cache); for (let m = begin + 1; m <= end; ++m) { if (s[m] === s[begin]) { minSteps = Math.min(minSteps, 1 - firstLetterPrinted + printHelper(s, begin + 1, m - 1, 0, cache) + printHelper(s, m, end, 1, cache)); } } cache[begin][end] = minSteps + firstLetterPrinted; return minSteps; } module.exports = strangePrinter;<gh_stars>1-10 (function () { 'use strict'; angular .module('app') .directive('settingsGrid', settingsGrid) function settingsGrid(FlashService) { // return { // restrict: 'E', // replace: true, // templateUrl: 'partials/common/settingsGrid.tpl.html', // link: function (scope, elm, attrs) { // console.log('directive1', attrs); // console.log('directive2', attrs.settings); // scope.settings = scope.$eval(attrs.settings); // console.log('directive3', scope.settings); // } // } return { restrict: 'EA', scope: { settings: '=', }, replace: true, templateUrl: 'partials/common/settingsGrid.tpl.html', link: function (scope, elm, attrs) { } } } })(); <filename>agents/modules_meshcore/apfclient.js /** * @description APF/CIRA Client for duktape * @author <NAME> * @copyright Intel Corporation 2019 * @license Apache-2.0 * @version v0.0.1 */ function CreateAPFClient(parent, args) { var obj = {}; obj.parent = parent; obj.args = args; obj.http = require('http'); //obj.common = require('common'); obj.net = require('net'); obj.forwardClient = null; obj.downlinks = {}; obj.pfwd_idx = 0; // keep alive timer obj.timer = null; // some function copied from common.js function ReadInt(v, p) { return (v.charCodeAt(p) * 0x1000000) + (v.charCodeAt(p + 1) << 16) + (v.charCodeAt(p + 2) << 8) + v.charCodeAt(p + 3); }; // We use "*0x1000000" instead of "<<24" because the shift converts the number to signed int32. function IntToStr(v) { return String.fromCharCode((v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF); }; function hex2rstr(d) { var r = '', m = ('' + d).match(/../g), t; while (t = m.shift()) { r += String.fromCharCode('0x' + t); } return r; }; // Convert decimal to hex function char2hex(i) { return (i + 0x100).toString(16).substr(-2).toUpperCase(); }; // Convert a raw string to a hex string function rstr2hex(input) { var r = '', i; for (i = 0; i < input.length; i++) { r += char2hex(input.charCodeAt(i)); } return r; }; function d2h(d) { return (d / 256 + 1 / 512).toString(16).substring(2, 4); } function buf2hex(input) { var r = '', i; for (i = 0; i < input.length; i++) { r += d2h(input[i]); } return r; }; function Debug(str) { if (obj.parent.debug) { console.log(str); } } // CIRA state var CIRASTATE = { INITIAL: 0, PROTOCOL_VERSION_SENT: 1, AUTH_SERVICE_REQUEST_SENT: 2, AUTH_REQUEST_SENT: 3, PFWD_SERVICE_REQUEST_SENT: 4, GLOBAL_REQUEST_SENT: 5, FAILED: -1 } obj.cirastate = CIRASTATE.INITIAL; // REDIR state var REDIR_TYPE = { REDIR_UNKNOWN: 0, REDIR_SOL: 1, REDIR_KVM: 2, REDIR_IDER: 3 } // redirection start command obj.RedirectStartSol = String.fromCharCode(0x10, 0x00, 0x00, 0x00, 0x53, 0x4F, 0x4C, 0x20); obj.RedirectStartKvm = String.fromCharCode(0x10, 0x01, 0x00, 0x00, 0x4b, 0x56, 0x4d, 0x52); obj.RedirectStartIder = String.fromCharCode(0x10, 0x00, 0x00, 0x00, 0x49, 0x44, 0x45, 0x52); // AMT forwarded port list for non-TLS mode var pfwd_ports = [16992, 623, 16994, 5900]; // protocol definitions var APFProtocol = { UNKNOWN: 0, DISCONNECT: 1, SERVICE_REQUEST: 5, SERVICE_ACCEPT: 6, USERAUTH_REQUEST: 50, USERAUTH_FAILURE: 51, USERAUTH_SUCCESS: 52, GLOBAL_REQUEST: 80, REQUEST_SUCCESS: 81, REQUEST_FAILURE: 82, CHANNEL_OPEN: 90, CHANNEL_OPEN_CONFIRMATION: 91, CHANNEL_OPEN_FAILURE: 92, CHANNEL_WINDOW_ADJUST: 93, CHANNEL_DATA: 94, CHANNEL_CLOSE: 97, PROTOCOLVERSION: 192, KEEPALIVE_REQUEST: 208, KEEPALIVE_REPLY: 209, KEEPALIVE_OPTIONS_REQUEST: 210, KEEPALIVE_OPTIONS_REPLY: 211 } var APFDisconnectCode = { HOST_NOT_ALLOWED_TO_CONNECT: 1, PROTOCOL_ERROR: 2, KEY_EXCHANGE_FAILED: 3, RESERVED: 4, MAC_ERROR: 5, COMPRESSION_ERROR: 6, SERVICE_NOT_AVAILABLE: 7, PROTOCOL_VERSION_NOT_SUPPORTED: 8, HOST_KEY_NOT_VERIFIABLE: 9, CONNECTION_LOST: 10, BY_APPLICATION: 11, TOO_MANY_CONNECTIONS: 12, AUTH_CANCELLED_BY_USER: 13, NO_MORE_AUTH_METHODS_AVAILABLE: 14, INVALID_CREDENTIALS: 15, CONNECTION_TIMED_OUT: 16, BY_POLICY: 17, TEMPORARILY_UNAVAILABLE: 18 } var APFChannelOpenFailCodes = { ADMINISTRATIVELY_PROHIBITED: 1, CONNECT_FAILED: 2, UNKNOWN_CHANNEL_TYPE: 3, RESOURCE_SHORTAGE: 4, } var APFChannelOpenFailureReasonCode = { AdministrativelyProhibited: 1, ConnectFailed: 2, UnknownChannelType: 3, ResourceShortage: 4, } obj.onSecureConnect = function onSecureConnect(resp, ws, head) { Debug("APF Secure WebSocket connected."); //console.log(JSON.stringify(resp)); obj.forwardClient.tag = { accumulator: [] }; obj.forwardClient.ws = ws; obj.forwardClient.ws.on('end', function () { Debug("APF: Connection is closing."); if (obj.timer != null) { clearInterval(obj.timer); obj.timer = null; } }); obj.forwardClient.ws.on('data', function (data) { obj.forwardClient.tag.accumulator += hex2rstr(buf2hex(data)); try { var len = 0; do { len = ProcessData(obj.forwardClient); if (len > 0) { obj.forwardClient.tag.accumulator = obj.forwardClient.tag.accumulator.slice(len); } if (obj.cirastate == CIRASTATE.FAILED) { Debug("APF: in a failed state, destroying socket.") obj.forwardClient.ws.end(); } } while (len > 0); } catch (e) { Debug(e); } }); obj.forwardClient.ws.on('error', function (e) { Debug("APF: Connection error, ending connecting."); if (obj.timer != null) { clearInterval(obj.timer); obj.timer = null; } }); obj.state = CIRASTATE.INITIAL; SendProtocolVersion(obj.forwardClient.ws, obj.args.clientuuid); SendServiceRequest(obj.forwardClient.ws, '<EMAIL>'); } function guidToStr(g) { return g.substring(6, 8) + g.substring(4, 6) + g.substring(2, 4) + g.substring(0, 2) + "-" + g.substring(10, 12) + g.substring(8, 10) + "-" + g.substring(14, 16) + g.substring(12, 14) + "-" + g.substring(16, 20) + "-" + g.substring(20); } function strToGuid(s) { s = s.replace(/-/g, ''); var ret = s.substring(6, 8) + s.substring(4, 6) + s.substring(2, 4) + s.substring(0, 2); ret += s.substring(10, 12) + s.substring(8, 10) + s.substring(14, 16) + s.substring(12, 14) + s.substring(16, 20) + s.substring(20); return ret; } function binzerostring(len) { var res=''; for (var l=0; l< len ; l++) { res+=String.fromCharCode(0 & 0xFF); } return res; } function SendProtocolVersion(socket, uuid) { var buuid = strToGuid(uuid); var data = String.fromCharCode(APFProtocol.PROTOCOLVERSION) + '' + IntToStr(1) + IntToStr(0) + IntToStr(0) + hex2rstr(buuid) + binzerostring(64); socket.write(data); Debug("APF: Send protocol version 1 0 " + uuid); obj.cirastate = CIRASTATE.PROTOCOL_VERSION_SENT; } function SendServiceRequest(socket, service) { var data = String.fromCharCode(APFProtocol.SERVICE_REQUEST) + IntToStr(service.length) + service; socket.write(data); Debug("APF: Send service request " + service); if (service == '<EMAIL>') { obj.cirastate = CIRASTATE.AUTH_SERVICE_REQUEST_SENT; } else if (service == '<EMAIL>') { obj.cirastate = CIRASTATE.PFWD_SERVICE_REQUEST_SENT; } } function SendUserAuthRequest(socket, user, pass) { var service = "<EMAIL>"; var data = String.fromCharCode(APFProtocol.USERAUTH_REQUEST) + IntToStr(user.length) + user + IntToStr(service.length) + service; //password auth data += IntToStr(8) + 'password'; data += binzerostring(1) + IntToStr(pass.length) + pass; socket.write(data); Debug("APF: Send username password authentication to MPS"); obj.cirastate = CIRASTATE.AUTH_REQUEST_SENT; } function SendGlobalRequestPfwd(socket, amthostname, amtport) { var tcpipfwd = 'tcpip-forward'; var data = String.fromCharCode(APFProtocol.GLOBAL_REQUEST) + IntToStr(tcpipfwd.length) + tcpipfwd + binzerostring(1, 1); data += IntToStr(amthostname.length) + amthostname + IntToStr(amtport); socket.write(data); Debug("APF: Send tcpip-forward " + amthostname + ":" + amtport); obj.cirastate = CIRASTATE.GLOBAL_REQUEST_SENT; } function SendKeepAliveRequest(socket) { var data = String.fromCharCode(APFProtocol.KEEPALIVE_REQUEST) + IntToStr(255); socket.write(data); Debug("APF: Send keepalive request"); } function SendKeepAliveReply(socket, cookie) { var data = String.fromCharCode(APFProtocol.KEEPALIVE_REPLY) + IntToStr(cookie); socket.write(data); Debug("APF: Send keepalive reply"); } function ProcessData(socket) { var cmd = socket.tag.accumulator.charCodeAt(0); var len = socket.tag.accumulator.length; var data = socket.tag.accumulator; if (len == 0) { return 0; } // respond to MPS according to obj.cirastate switch (cmd) { case APFProtocol.SERVICE_ACCEPT: { var slen = ReadInt(data, 1); var service = data.substring(5, 6 + slen); Debug("APF: Service request to " + service + " accepted."); if (service == 'auth@amt.<EMAIL>') { if (obj.cirastate >= CIRASTATE.AUTH_SERVICE_REQUEST_SENT) { SendUserAuthRequest(socket.ws, obj.args.mpsuser, obj.args.mpspass); } } else if (service == '<EMAIL>') { if (obj.cirastate >= CIRASTATE.PFWD_SERVICE_REQUEST_SENT) { SendGlobalRequestPfwd(socket.ws, obj.args.clientname, pfwd_ports[obj.pfwd_idx++]); } } return 5 + slen; } case APFProtocol.REQUEST_SUCCESS: { if (len >= 5) { var port = ReadInt(data, 1); Debug("APF: Request to port forward " + port + " successful."); // iterate to pending port forward request if (obj.pfwd_idx < pfwd_ports.length) { SendGlobalRequestPfwd(socket.ws, obj.args.clientname, pfwd_ports[obj.pfwd_idx++]); } else { // no more port forward, now setup timer to send keep alive Debug("APF: Start keep alive for every " + obj.args.mpskeepalive + " ms."); obj.timer = setInterval(function () { SendKeepAliveRequest(obj.forwardClient.ws); }, obj.args.mpskeepalive);// } return 5; } Debug("APF: Request successful."); return 1; } case APFProtocol.USERAUTH_SUCCESS: { Debug("APF: User Authentication successful"); // Send Pfwd service request SendServiceRequest(socket.ws, '<EMAIL>'); return 1; } case APFProtocol.USERAUTH_FAILURE: { Debug("APF: User Authentication failed"); obj.cirastate = CIRASTATE.FAILED; return 14; } case APFProtocol.KEEPALIVE_REQUEST: { Debug("APF: Keep Alive Request with cookie: " + ReadInt(data, 1)); SendKeepAliveReply(socket.ws, ReadInt(data, 1)); return 5; } case APFProtocol.KEEPALIVE_REPLY: { Debug("APF: Keep Alive Reply with cookie: " + ReadInt(data, 1)); return 5; } // Channel management case APFProtocol.CHANNEL_OPEN: { //parse CHANNEL OPEN request var p_res = parseChannelOpen(data); Debug("APF: CHANNEL_OPEN request: " + JSON.stringify(p_res)); // Check if target port is in pfwd_ports if (pfwd_ports.indexOf(p_res.target_port) >= 0) { // connect socket to that port obj.downlinks[p_res.sender_chan] = obj.net.createConnection({ host: obj.args.clientaddress, port: p_res.target_port }, function () { //obj.downlinks[p_res.sender_chan].setEncoding('binary');//assume everything is binary, not interpreting SendChannelOpenConfirm(socket.ws, p_res); }); obj.downlinks[p_res.sender_chan].on('data', function (ddata) { //Relay data to fordwardclient SendChannelData(socket.ws, p_res.sender_chan, ddata.length, ddata); }); obj.downlinks[p_res.sender_chan].on('error', function (e) { Debug("Downlink connection error: " + e); }); obj.downlinks[p_res.sender_chan].on('end', function () { if (obj.downlinks[p_res.sender_chan]) { try { Debug("Socket ends."); SendChannelClose(socket.ws, p_res.sender_chan); // add some delay before removing... otherwise race condition setTimeout(function () { delete obj.downlinks[p_res.sender_chan];},100); } catch (e) { Debug("Downlink connection exception: " + e); } } }); } else { SendChannelOpenFailure(socket.ws, p_res); } return p_res.len; } case APFProtocol.CHANNEL_OPEN_CONFIRMATION: { Debug("APF: CHANNEL_OPEN_CONFIRMATION"); return 17; } case APFProtocol.CHANNEL_CLOSE: { var rcpt_chan = ReadInt(data, 1); Debug("APF: CHANNEL_CLOSE: " + rcpt_chan); SendChannelClose(socket.ws, rcpt_chan); try { obj.downlinks[rcpt_chan].end(); delete obj.downlinks[rcpt_chan]; } catch (e) { } return 5; } case APFProtocol.CHANNEL_DATA: { Debug("APF: CHANNEL_DATA: " + JSON.stringify(rstr2hex(data))); var rcpt_chan = ReadInt(data, 1); var chan_data_len = ReadInt(data, 5); var chan_data = data.substring(9, 9 + chan_data_len); if (obj.downlinks[rcpt_chan]) { try { obj.downlinks[rcpt_chan].write(chan_data, 'binary', function () { Debug("Write completed."); SendChannelWindowAdjust(socket.ws, rcpt_chan, chan_data_len);//I have full window capacity now }); } catch (e) { Debug("Cannot forward data to downlink socket."); } } return 9 + chan_data_len; } case APFProtocol.CHANNEL_WINDOW_ADJUST: { Debug("APF: CHANNEL_WINDOW_ADJUST "); return 9; } default: { Debug("CMD: " + cmd + " is not implemented."); obj.cirastate = CIRASTATE.FAILED; return 0; } } } function parseChannelOpen(data) { var result = { len: 0, //to be filled later cmd: APFProtocol.CHANNEL_OPEN, chan_type: "", //to be filled later sender_chan: 0, //to be filled later window_size: 0, //to be filled later target_address: "", //to be filled later target_port: 0, //to be filled later origin_address: "", //to be filled later origin_port: 0, //to be filled later }; var chan_type_slen = ReadInt(data, 1); result.chan_type = data.substring(5, 5 + chan_type_slen); result.sender_chan = ReadInt(data, 5 + chan_type_slen); result.window_size = ReadInt(data, 9 + chan_type_slen); var c_len = ReadInt(data, 17 + chan_type_slen); result.target_address = data.substring(21 + chan_type_slen, 21 + chan_type_slen + c_len); result.target_port = ReadInt(data, 21 + chan_type_slen + c_len); var o_len = ReadInt(data, 25 + chan_type_slen + c_len); result.origin_address = data.substring(29 + chan_type_slen + c_len, 29 + chan_type_slen + c_len + o_len); result.origin_port = ReadInt(data, 29 + chan_type_slen + c_len + o_len); result.len = 33 + chan_type_slen + c_len + o_len; return result; } function SendChannelOpenFailure(socket, chan_data) { var data = String.fromCharCode(APFProtocol.CHANNEL_OPEN_FAILURE) + IntToStr(chan_data.sender_chan) + IntToStr(2) + IntToStr(0) + IntToStr(0); socket.write(data); Debug("APF: Send ChannelOpenFailure"); } function SendChannelOpenConfirm(socket, chan_data) { var data = String.fromCharCode(APFProtocol.CHANNEL_OPEN_CONFIRMATION) + IntToStr(chan_data.sender_chan) + IntToStr(chan_data.sender_chan) + IntToStr(chan_data.window_size) + IntToStr(0xFFFFFFFF); socket.write(data); Debug("APF: Send ChannelOpenConfirmation"); } function SendChannelWindowAdjust(socket, chan, size) { var data = String.fromCharCode(APFProtocol.CHANNEL_WINDOW_ADJUST) + IntToStr(chan) + IntToStr(size); socket.write(data); Debug("APF: Send ChannelWindowAdjust: " + rstr2hex(data)); } function SendChannelData(socket, chan, len, data) { var buf = String.fromCharCode(APFProtocol.CHANNEL_DATA) + IntToStr(chan) + IntToStr(len) + data; socket.write(buf); Debug("APF: Send ChannelData: " + rstr2hex(buf)); } function SendChannelClose(socket, chan) { var buf = String.fromCharCode(APFProtocol.CHANNEL_CLOSE) + IntToStr(chan); socket.write(buf); Debug("APF: Send ChannelClose "); } obj.connect = function () { if (obj.forwardClient != null) { try { obj.forwardClient.ws.end(); } catch (e) { Debug(e); } //obj.forwardClient = null; } obj.cirastate = CIRASTATE.INITIAL; obj.pfwd_idx = 0; //obj.forwardClient = new obj.ws(obj.args.mpsurl, obj.tlsoptions); //obj.forwardClient.on("open", obj.onSecureConnect); var wsoptions = obj.http.parseUri(obj.args.mpsurl); wsoptions.rejectUnauthorized = 0; obj.forwardClient = obj.http.request(wsoptions); obj.forwardClient.upgrade = obj.onSecureConnect; obj.forwardClient.end(); // end request, trigger completion of HTTP request } obj.disconnect = function () { try { obj.forwardClient.ws.end(); } catch (e) { Debug(e); } } return obj; } module.exports = CreateAPFClient; (function() { var T, assert, createApiTree, createOptions, find, findDir; createApiTree = require('../lib/apitree').createApiTree; assert = require('assert'); find = function(tree, path) { var component, _i, _len, _ref; _ref = path.split('/'); for (_i = 0, _len = _ref.length; _i < _len; _i++) { component = _ref[_i]; if (!(component !== '.')) continue; tree = tree[component]; if (!tree) throw new Error("Path not found"); } return tree; }; findDir = function(tree, path) { var item; item = find(tree, path); if (item.length == null) return item; }; createOptions = function(tree, options) { if (options == null) options = {}; options.readdirSync = function(path) { var item; if (item = findDir(tree, path)) { return Object.keys(item).sort(); } else { throw new Error("Not a directory"); } }; options.isDirectory = function(path) { return !!findDir(tree, path); }; options.loadItem = function(path) { var index, name, result, _len, _ref; result = {}; _ref = find(tree, path); for (index = 0, _len = _ref.length; index < _len; index++) { name = _ref[index]; result[name] = "i" + index; } return result; }; return options; }; T = function(tree, options) { if (options == null) options = {}; return createApiTree('.', createOptions(tree, options)); }; describe("API tree", function() { describe("when given an empty folder", function() { var tree; tree = T({}); return it("should return an empty tree", function() { return assert.deepEqual(tree, {}); }); }); describe("when given a folder with a single file", function() { var tree; tree = T({ 'foo.js': ['bar', 'boz'] }); it("should put the file node under the tree root", function() { return assert.equal(Object.keys(tree).length, 1); }); it("should strip the extension when naming the tree node", function() { return assert.deepEqual(Object.keys(tree), ['foo']); }); return it("should put the file's contents under its node", function() { return assert.deepEqual(Object.keys(tree.foo).sort(), ['bar', 'boz']); }); }); describe("when given a file and a subfolder", function() { var tree; tree = T({ 'foo.js': ['bar', 'boz'], fold: { 'fil.js': ['fubar'] } }); return it("should put the file and subfolder nodes together under the tree root", function() { return assert.deepEqual(Object.keys(tree).sort(), ['fold', 'foo']); }); }); describe("when given a file and a subfolder which have the same name after stripping extensions", function() { var tree; tree = T({ 'foo.js': ['bar', 'boz'], foo: { 'fil.js': ['fubar'] } }); return it("should merge the file and the subfolder into a single node under the tree root", function() { assert.deepEqual(Object.keys(tree), ['foo']); return assert.deepEqual(Object.keys(tree.foo).sort(), ['bar', 'boz', 'fil']); }); }); describe("when given a folder hierarchy with nested subfolders", function() { var tree; tree = T({ foo: { bar: { 'boz.js': ['fubar'] } } }); return it("should reproduce the folder hierarachy inside the API tree", function() { assert.deepEqual(Object.keys(tree), ['foo']); assert.deepEqual(Object.keys(tree.foo), ['bar']); assert.deepEqual(Object.keys(tree.foo.bar), ['boz']); return assert.deepEqual(Object.keys(tree.foo.bar.boz), ['fubar']); }); }); describe("loadItem callback", function() { return it("should be used to obtain file contents", function() { var tree; tree = T({ 'foo.js': ['bar', 'boz'] }); assert.equal(tree.foo.bar, 'i0'); return assert.equal(tree.foo.boz, 'i1'); }); }); describe("nameToKey callback", function() { var args, nameToKey; args = null; nameToKey = function(name) { args = arguments; return "A" + (name.split('.')[0]) + "Z"; }; it("should accept file name as the only argument", function() { var tree; tree = T({ 'foo.js': ['bar', 'boz'] }, { nameToKey: nameToKey }); assert.equal(args.length, 1); return assert.equal(args[0], 'foo.js'); }); it("should be used to translate file names into tree keys", function() { var tree; tree = T({ 'foo.js': ['bar', 'boz'] }, { nameToKey: nameToKey }); return assert.deepEqual(Object.keys(tree), ['AfooZ']); }); it("should be used to translate subfolder names into tree keys", function() { var tree; tree = T({ foo: { 'bar.js': ['bar', 'boz'] } }, { nameToKey: nameToKey }); return assert.deepEqual(Object.keys(tree), ['AfooZ']); }); return it("should not be used to modify keys returned by loadItem", function() { var tree; tree = T({ 'foo.js': ['bar', 'boz'] }, { nameToKey: nameToKey }); return assert.deepEqual(Object.keys(tree.AfooZ).sort(), ['bar', 'boz']); }); }); describe("default nameToKey callback", function() { it("should strip file extension", function() { var tree; tree = T({ 'foo.js': ['bar'] }); return assert.deepEqual(Object.keys(tree), ['foo']); }); it("should replace any non-identifier characters with underscores", function() { var tree; tree = T({ 'foo-bar.js': ['bar'] }); return assert.deepEqual(Object.keys(tree), ['foo_bar']); }); return it("should replace runs of multiple non-identifier characters with a single underscore", function() { var tree; tree = T({ 'foo!!bar.js': ['bar'] }); return assert.deepEqual(Object.keys(tree), ['foo_bar']); }); }); describe("filter callback", function() { var args, filter; args = null; filter = function(name, names) { args = arguments; return name === 'foo.js'; }; it("should accept file name as the first argument", function() { var tree; tree = T({ 'foo.js': ['fu'] }, { filter: filter }); return assert.equal(args[0], 'foo.js'); }); it("should accept the list of all file names in the same folder as the second argument", function() { var tree; tree = T({ 'foo.js': ['fu'], 'bar.js': ['ba'] }, { filter: filter }); assert.deepEqual(args[1].sort(), ['bar.js', 'foo.js']); return assert.equal(args.length, 2); }); it("should be used to choose which files to process", function() { var tree; tree = T({ 'foo.js': ['fu'], 'bar.js': ['ba'] }, { filter: filter }); return assert.deepEqual(Object.keys(tree), ['foo']); }); return it("should have no effect on which folders are processed", function() { var tree; tree = T({ 'foo.js': ['fu'], 'fold': { 'foo.js': ['uf'], 'bar.js': ['ba'] } }, { filter: filter }); assert.deepEqual(Object.keys(tree).sort(), ['fold', 'foo']); return assert.deepEqual(Object.keys(tree.fold), ['foo']); }); }); return describe("default filter callback", function() { var tree; tree = T({ 'foo.js': ['xx'], 'bar.js': ['yy'], 'foo.txt': ['zz'], 'Rakefile': ['rr'], 'boz.coffee': ['cc'], 'both.js': ['bb'], 'both.coffee': ['BB'] }, { nameToKey: function(name) { return name; } }); it("should include .js files", function() { assert.ok('foo.js' in tree); return assert.ok('bar.js' in tree); }); it("should include .coffee files that don't have corresponding .js files", function() { return assert.ok('boz.coffee' in tree); }); it("should only include .js file when both .js and .coffee files exist", function() { assert.ok('both.js' in tree); return assert.ok(!('both.coffee' in tree)); }); return it("should not include any other files", function() { assert.ok(!('Rakefile' in tree)); return assert.ok(!('foo.txt' in tree)); }); }); }); }).call(this); <gh_stars>0 import React from "react"; import { mount } from "enzyme"; import CommentList from "components/CommentList"; import Root from "root"; let wrapped; beforeEach(() => { const initialState = { comments: ["Comment 1", "Comment 2"] }; wrapped = mount( <Root initialState={initialState}> <CommentList /> </Root> ); }); it("creates one LI per Comment", () => { expect(wrapped.find("li").length).toEqual(2); }); it("Shows the Text in each Comment", () => { console.log(wrapped.render().text()); // expect(wrapped.render().text()).toEqual( // "Add A CommentSubmit CommentComment 1Comment 2" // ); // expect(wrapped.render().text()).toEqual("Comment 2"); }); <reponame>webnator/auraworkout-scrapper 'use strict'; var responses = require('../../../components/responses'); module.exports = { internal_ddbb_error: { statusCode: 500, code: responses.auraworkout500.code, message: 'Internal DDBB Error' }, registration_ok: { statusCode: 200, code: responses.auraworkout200.code, message: 'User has been successfully registered' }, error_in_params: { statusCode: 403, code: responses.auraworkout403.code, message: 'Email already registered' }, register_error: { statusCode: 400, code: responses.auraworkout400.code, message: 'Error while registering into zingfit' } }; var NAVTREEINDEX44 = { "group___p_e___types__module.html#ga6d7fd7a4623f2bbe5a2d985cf397a578":[3,0,0,2,1017], "group___p_e___types__module.html#ga6d7fd7a4623f2bbe5a2d985cf397a578":[1,2,902], "group___p_e___types__module.html#ga6d83effc591bd5a124c0538354e04673":[1,2,187], "group___p_e___types__module.html#ga6d83effc591bd5a124c0538354e04673":[3,0,0,2,150], "group___p_e___types__module.html#ga6efa69e8410c697eaf6990a2f48a1b7c":[3,0,0,2,113], "group___p_e___types__module.html#ga6efa69e8410c697eaf6990a2f48a1b7c":[1,2,151], "group___p_e___types__module.html#ga6f417aaad3475857e9ae7b5b02376995":[1,2,342], "group___p_e___types__module.html#ga6f417aaad3475857e9ae7b5b02376995":[3,0,0,2,305], "group___p_e___types__module.html#ga6fd15fab6696c262310ccd154ae154d8":[1,2,353], "group___p_e___types__module.html#ga6fd15fab6696c262310ccd154ae154d8":[3,0,0,2,317], "group___p_e___types__module.html#ga6fe797d4215b852a1f7407f2393e667d":[1,2,394], "group___p_e___types__module.html#ga6fe797d4215b852a1f7407f2393e667d":[3,0,0,2,358], "group___p_e___types__module.html#ga702edd1626e2da939f72fe50dd7c5de4":[3,0,0,2,914], "group___p_e___types__module.html#ga7038232a628d9290ef0e081e3c18e8ae":[1,2,233], "group___p_e___types__module.html#ga7038232a628d9290ef0e081e3c18e8ae":[3,0,0,2,196], "group___p_e___types__module.html#ga7099a2311c895317142b3d88e6bce9c6":[1,2,711], "group___p_e___types__module.html#ga7099a2311c895317142b3d88e6bce9c6":[3,0,0,2,799], "group___p_e___types__module.html#ga70d44420af599732b3bd165642113193":[1,2,685], "group___p_e___types__module.html#ga70d44420af599732b3bd165642113193":[3,0,0,2,773], "group___p_e___types__module.html#ga7143333fc211cd8c5351aa555809ac90":[3,0,0,2,830], "group___p_e___types__module.html#ga7143333fc211cd8c5351aa555809ac90":[1,2,742], "group___p_e___types__module.html#ga715b450241071704dd8ca9460080517b":[3,0,0,2,488], "group___p_e___types__module.html#ga7283ef9d68feb16248949a1e705aff91":[3,0,0,2,962], "group___p_e___types__module.html#ga7283ef9d68feb16248949a1e705aff91":[1,2,853], "group___p_e___types__module.html#ga7283fa5ee273030d85a48a76fdd33f2c":[1,2,461], "group___p_e___types__module.html#ga7283fa5ee273030d85a48a76fdd33f2c":[3,0,0,2,547], "group___p_e___types__module.html#ga72a043be7a634b3691375beeda3a2dd7":[3,0,0,2,964], "group___p_e___types__module.html#ga72a043be7a634b3691375beeda3a2dd7":[1,2,855], "group___p_e___types__module.html#ga7349633cc40e88429442cfa012d8a5c8":[3,0,0,2,982], "group___p_e___types__module.html#ga7349633cc40e88429442cfa012d8a5c8":[1,2,867], "group___p_e___types__module.html#ga73578a8c0beb2cb4da6744e9ae188414":[3,0,0,2,22], "group___p_e___types__module.html#ga73578a8c0beb2cb4da6744e9ae188414":[1,2,62], "group___p_e___types__module.html#ga73a162b52f9d67652543863af8ebdae6":[3,0,0,2,927], "group___p_e___types__module.html#ga73a162b52f9d67652543863af8ebdae6":[1,2,818], "group___p_e___types__module.html#ga73cab4c81fd14cdad655433a561b5e1f":[3,0,0,2,961], "group___p_e___types__module.html#ga73cab4c81fd14cdad655433a561b5e1f":[1,2,852], "group___p_e___types__module.html#ga73e13d503d6bef8877b2d220ef62b553":[3,0,0,2,9], "group___p_e___types__module.html#ga73e13d503d6bef8877b2d220ef62b553":[1,2,49], "group___p_e___types__module.html#ga743a9400e98618bba0b00e5b87a93aee":[1,2,188], "group___p_e___types__module.html#ga743a9400e98618bba0b00e5b87a93aee":[3,0,0,2,151], "group___p_e___types__module.html#ga7473373e32d9bf69dcc712ea17188752":[1,2,452], "group___p_e___types__module.html#ga7473373e32d9bf69dcc712ea17188752":[3,0,0,2,538], "group___p_e___types__module.html#ga748098655584a18a359533f56d5af08e":[1,2,457], "group___p_e___types__module.html#ga748098655584a18a359533f56d5af08e":[3,0,0,2,543], "group___p_e___types__module.html#ga74cb93d430006e784da73b8ca406ee6e":[3,0,0,2,881], "group___p_e___types__module.html#ga74e89d4420d65faffdb0dfcbf2ca6d93":[1,2,288], "group___p_e___types__module.html#ga74e89d4420d65faffdb0dfcbf2ca6d93":[3,0,0,2,251], "group___p_e___types__module.html#ga7573870e437f8a6cf885f6675d4ab22b":[3,0,0,2,637], "group___p_e___types__module.html#ga7573870e437f8a6cf885f6675d4ab22b":[1,2,551], "group___p_e___types__module.html#ga75ec5528b4260f1f044b2a33e0a2f859":[1,2,286], "group___p_e___types__module.html#ga75ec5528b4260f1f044b2a33e0a2f859":[3,0,0,2,249], "group___p_e___types__module.html#ga75f3688e1a9634b9cd55065a5189b99b":[1,2,381], "group___p_e___types__module.html#ga75f3688e1a9634b9cd55065a5189b99b":[3,0,0,2,345], "group___p_e___types__module.html#ga762b97d64cdff19fffde4bf60cc646c8":[1,2,253], "group___p_e___types__module.html#ga762b97d64cdff19fffde4bf60cc646c8":[3,0,0,2,216], "group___p_e___types__module.html#ga76328e8cbfee1cf4f59c6139fc67a64b":[1,2,280], "group___p_e___types__module.html#ga76328e8cbfee1cf4f59c6139fc67a64b":[3,0,0,2,243], "group___p_e___types__module.html#ga76699addf890e383d17edf5d1d6c157c":[1,2,195], "group___p_e___types__module.html#ga76699addf890e383d17edf5d1d6c157c":[3,0,0,2,158], "group___p_e___types__module.html#ga76a64632dc55a977bd2c3bbe05d653a0":[3,0,0,2,1035], "group___p_e___types__module.html#ga76a64632dc55a977bd2c3bbe05d653a0":[1,2,920], "group___p_e___types__module.html#ga773bc57b83dd7c3d89592ff575d95543":[3,0,0,2,372], "group___p_e___types__module.html#ga77427a663364eb0fbf568c2acade8c46":[3,0,0,2,647], "group___p_e___types__module.html#ga77427a663364eb0fbf568c2acade8c46":[1,2,561], "group___p_e___types__module.html#ga77790c62540512f0584b776c6eb4419d":[3,0,0,2,616], "group___p_e___types__module.html#ga77790c62540512f0584b776c6eb4419d":[1,2,530], "group___p_e___types__module.html#ga7852684a913d461206eda36e12c3f0a6":[1,2,833], "group___p_e___types__module.html#ga7852684a913d461206eda36e12c3f0a6":[3,0,0,2,942], "group___p_e___types__module.html#ga7889c70883f2dae130cdff4b02cace21":[1,2,301], "group___p_e___types__module.html#ga7889c70883f2dae130cdff4b02cace21":[3,0,0,2,264], "group___p_e___types__module.html#ga7897caa7edd4b95c69aa369f7e176c08":[3,0,0,2,756], "group___p_e___types__module.html#ga7897caa7edd4b95c69aa369f7e176c08":[1,2,668], "group___p_e___types__module.html#ga78a5cdfe6cca1b3e9a288b5244401c0f":[3,0,0,2,668], "group___p_e___types__module.html#ga78a5cdfe6cca1b3e9a288b5244401c0f":[1,2,582], "group___p_e___types__module.html#ga7919cf66cff1c7e7938028f0dbfaf897":[3,0,0,2,69], "group___p_e___types__module.html#ga7919cf66cff1c7e7938028f0dbfaf897":[1,2,107], "group___p_e___types__module.html#ga7940d16a06bc6c645272c3070290be02":[3,0,0,2,655], "group___p_e___types__module.html#ga7940d16a06bc6c645272c3070290be02":[1,2,569], "group___p_e___types__module.html#ga79539dc54be4bb93abc77db3478c3aef":[3,0,0,2,610], "group___p_e___types__module.html#ga79539dc54be4bb93abc77db3478c3aef":[1,2,524], "group___p_e___types__module.html#ga797cb0f8493c555efe313e4ffa1531cf":[1,2,359], "group___p_e___types__module.html#ga797cb0f8493c555efe313e4ffa1531cf":[3,0,0,2,323], "group___p_e___types__module.html#ga7992830a5c2c2f3b2b6e733535d66584":[1,2,192], "group___p_e___types__module.html#ga7992830a5c2c2f3b2b6e733535d66584":[3,0,0,2,155], "group___p_e___types__module.html#ga79dc31db73d02321488a6cfce2854ef9":[1,2,489], "group___p_e___types__module.html#ga79dc31db73d02321488a6cfce2854ef9":[3,0,0,2,575], "group___p_e___types__module.html#ga79f99b0d51bed34d655b310171836ec4":[3,0,0,2,90], "group___p_e___types__module.html#ga79f99b0d51bed34d655b310171836ec4":[1,2,128], "group___p_e___types__module.html#ga7a568ed596db3cfb7b5b6fd86c4274e4":[3,0,0,2,117], "group___p_e___types__module.html#ga7a568ed596db3cfb7b5b6fd86c4274e4":[1,2,155], "group___p_e___types__module.html#ga7afc6249e5526bf839ef4e137e6a65ab":[1,2,707], "group___p_e___types__module.html#ga7afc6249e5526bf839ef4e137e6a65ab":[3,0,0,2,795], "group___p_e___types__module.html#ga7b46cade0cd773552e0628832605e58c":[3,0,0,2,479], "group___p_e___types__module.html#ga7b5684169ad678f21ed74d05367e6ac7":[1,2,446], "group___p_e___types__module.html#ga7b5684169ad678f21ed74d05367e6ac7":[3,0,0,2,532], "group___p_e___types__module.html#ga7b69852ff3c5cc14920a6a9311f50a5f":[3,0,0,2,719], "group___p_e___types__module.html#ga7b69852ff3c5cc14920a6a9311f50a5f":[1,2,631], "group___p_e___types__module.html#ga7c3ed191deb873ebaeab34279f12890d":[3,0,0,2,112], "group___p_e___types__module.html#ga7c3ed191deb873ebaeab34279f12890d":[1,2,150], "group___p_e___types__module.html#ga7c8b4fd73a09f8d717296751322a3b4a":[3,0,0,2,44], "group___p_e___types__module.html#ga7c8b4fd73a09f8d717296751322a3b4a":[1,2,82], "group___p_e___types__module.html#ga7ceec0d1213b03cab5f5059ad79d6f9c":[3,0,0,2,376], "group___p_e___types__module.html#ga7cf4950dd3ffdf321903de20719bdd60":[3,0,0,2,636], "group___p_e___types__module.html#ga7cf4950dd3ffdf321903de20719bdd60":[1,2,550], "group___p_e___types__module.html#ga7d09ab5bda47a1e236ac0a0b312dcfc5":[3,0,0,2,823], "group___p_e___types__module.html#ga7d09ab5bda47a1e236ac0a0b312dcfc5":[1,2,735], "group___p_e___types__module.html#ga7d5fc01faf3ed6751e122d7b3ff9e8a3":[3,0,0,2,487], "group___p_e___types__module.html#ga7def7f904f6594feabf296b02b5c88ed":[1,2,276], "group___p_e___types__module.html#ga7def7f904f6594feabf296b02b5c88ed":[3,0,0,2,239], "group___p_e___types__module.html#ga7dffaa3a86c62aa8550e6a2f75d0aedd":[3,0,0,2,469], "group___p_e___types__module.html#ga7e8983072ae98be828082983ea7b4442":[3,0,0,2,78], "group___p_e___types__module.html#ga7e8983072ae98be828082983ea7b4442":[1,2,116], "group___p_e___types__module.html#ga7ef8a3ccd618f5965f436dc0e02e8a13":[1,2,379], "group___p_e___types__module.html#ga7ef8a3ccd618f5965f436dc0e02e8a13":[3,0,0,2,343], "group___p_e___types__module.html#ga7f1c0053db9885c3b4c5c8ebfad9f78b":[3,0,0,2,968], "group___p_e___types__module.html#ga7f1c0053db9885c3b4c5c8ebfad9f78b":[1,2,859], "group___p_e___types__module.html#ga7f1f6eede63c14a1199e65543229f589":[3,0,0,2,673], "group___p_e___types__module.html#ga7f1f6eede63c14a1199e65543229f589":[1,2,587], "group___p_e___types__module.html#ga7f54557765be06b9c903dca8093d8c1d":[1,2,401], "group___p_e___types__module.html#ga7f54557765be06b9c903dca8093d8c1d":[3,0,0,2,365], "group___p_e___types__module.html#ga7f79d3e80ad542c3a135621c5ccfb34e":[3,0,0,2,943], "group___p_e___types__module.html#ga7f79d3e80ad542c3a135621c5ccfb34e":[1,2,834], "group___p_e___types__module.html#ga80392e7d0a7f48b031a3ab44e51b6300":[3,0,0,2,474], "group___p_e___types__module.html#ga805bfab956cb00a43f5f8565a2d4362f":[3,0,0,2,76], "group___p_e___types__module.html#ga805bfab956cb00a43f5f8565a2d4362f":[1,2,114], "group___p_e___types__module.html#ga80f4549eda0136cba3333947b8acd551":[3,0,0,2,65], "group___p_e___types__module.html#ga80f4549eda0136cba3333947b8acd551":[1,2,103], "group___p_e___types__module.html#ga811572473894aae0528ed943b8e84b53":[3,0,0,2,397], "group___p_e___types__module.html#ga8124607c5058435586c5944f9665db71":[1,2,64], "group___p_e___types__module.html#ga8124607c5058435586c5944f9665db71":[3,0,0,2,24], "group___p_e___types__module.html#ga814a2975cc70816df1d95a426a40afdf":[1,2,44], "group___p_e___types__module.html#ga814a2975cc70816df1d95a426a40afdf":[3,0,0,2,4], "group___p_e___types__module.html#ga8213455c190f80958af4e4b68b4dee14":[3,0,0,2,1012], "group___p_e___types__module.html#ga8213455c190f80958af4e4b68b4dee14":[1,2,897], "group___p_e___types__module.html#ga82627ad0f6e435bb61e9d8a7586ce1ff":[3,0,0,2,50], "group___p_e___types__module.html#ga82627ad0f6e435bb61e9d8a7586ce1ff":[1,2,88], "group___p_e___types__module.html#ga8330eca54134cfe204ce0309a1953349":[1,2,57], "group___p_e___types__module.html#ga8330eca54134cfe204ce0309a1953349":[3,0,0,2,17], "group___p_e___types__module.html#ga8338060276ecbc3d9e69b601ac946108":[3,0,0,2,609], "group___p_e___types__module.html#ga8338060276ecbc3d9e69b601ac946108":[1,2,523], "group___p_e___types__module.html#ga8371678ceacf49282bfc8dda73e5d9da":[3,0,0,2,635], "group___p_e___types__module.html#ga8371678ceacf49282bfc8dda73e5d9da":[1,2,549], "group___p_e___types__module.html#ga838413fa1e73793bf97190b27d389f91":[3,0,0,2,443], "group___p_e___types__module.html#ga83d151c11162bd485448e8f680003f01":[1,2,508], "group___p_e___types__module.html#ga83d151c11162bd485448e8f680003f01":[3,0,0,2,594], "group___p_e___types__module.html#ga83ee339d8cd1861a23a9232dbf6395a1":[3,0,0,2,687], "group___p_e___types__module.html#ga83ee339d8cd1861a23a9232dbf6395a1":[1,2,601], "group___p_e___types__module.html#ga8402bfd3b1c5bf0d046e21fadbfc6514":[1,2,321], "group___p_e___types__module.html#ga8402bfd3b1c5bf0d046e21fadbfc6514":[3,0,0,2,284], "group___p_e___types__module.html#ga841810a9231c80571561fe7f438f6d2f":[3,0,0,2,670], "group___p_e___types__module.html#ga841810a9231c80571561fe7f438f6d2f":[1,2,584], "group___p_e___types__module.html#ga8474b4efd6d7adbb6372f4d903483ddd":[3,0,0,2,874], "group___p_e___types__module.html#ga84b7bcde396e7dc48336d2bf59001855":[1,2,368], "group___p_e___types__module.html#ga84b7bcde396e7dc48336d2bf59001855":[3,0,0,2,332], "group___p_e___types__module.html#ga84f1e554b1b98a5e85e4fa90c45d5dad":[1,2,704], "group___p_e___types__module.html#ga84f1e554b1b98a5e85e4fa90c45d5dad":[3,0,0,2,792], "group___p_e___types__module.html#ga851e21a07e861a993326312f95813324":[3,0,0,2,472], "group___p_e___types__module.html#ga852326a98cd4d15b79f33164bc1ed086":[1,2,509], "group___p_e___types__module.html#ga852326a98cd4d15b79f33164bc1ed086":[3,0,0,2,595], "group___p_e___types__module.html#ga854bd2cd241f3a01f7f370e31ce331a9":[3,0,0,2,992], "group___p_e___types__module.html#ga854bd2cd241f3a01f7f370e31ce331a9":[1,2,877], "group___p_e___types__module.html#ga8576a9209d4809bf2eaef43551486ceb":[3,0,0,2,643], "group___p_e___types__module.html#ga8576a9209d4809bf2eaef43551486ceb":[1,2,557], "group___p_e___types__module.html#ga865cc3eb1db08087aef5c8432e442eae":[3,0,0,2,763], "group___p_e___types__module.html#ga865cc3eb1db08087aef5c8432e442eae":[1,2,675], "group___p_e___types__module.html#ga868f08f9448e5df27a38314f0893d84a":[3,0,0,2,916], "group___p_e___types__module.html#ga868f08f9448e5df27a38314f0893d84a":[1,2,807], "group___p_e___types__module.html#ga86acbb58883ee4b3c59516dd9e512cd6":[3,0,0,2,623], "group___p_e___types__module.html#ga86acbb58883ee4b3c59516dd9e512cd6":[1,2,537], "group___p_e___types__module.html#ga86ad7e81677bc5d1eb588be9b08d445e":[3,0,0,2,723], "group___p_e___types__module.html#ga86ad7e81677bc5d1eb588be9b08d445e":[1,2,635], "group___p_e___types__module.html#ga86f58a4d233e59d628da7ae081ba4c63":[3,0,0,2,686], "group___p_e___types__module.html#ga86f58a4d233e59d628da7ae081ba4c63":[1,2,600], "group___p_e___types__module.html#ga86f8905721105e80fd49eba95b1c9570":[3,0,0,2,672], "group___p_e___types__module.html#ga86f8905721105e80fd49eba95b1c9570":[1,2,586], "group___p_e___types__module.html#ga8718a0d79609d46a87432cb291b0691e":[3,0,0,2,751], "group___p_e___types__module.html#ga8718a0d79609d46a87432cb291b0691e":[1,2,663], "group___p_e___types__module.html#ga873f42453c21275b0c514fbec25e9a00":[1,2,396], "group___p_e___types__module.html#ga873f42453c21275b0c514fbec25e9a00":[3,0,0,2,360], "group___p_e___types__module.html#ga87416b9c0de9dd1a7be29447588e780d":[3,0,0,2,825], "group___p_e___types__module.html#ga87416b9c0de9dd1a7be29447588e780d":[1,2,737], "group___p_e___types__module.html#ga87a5cc47e3534dd97d030545c54881cf":[3,0,0,2,828], "group___p_e___types__module.html#ga87a5cc47e3534dd97d030545c54881cf":[1,2,740], "group___p_e___types__module.html#ga87b6c55009d3b57b9fed7a447b4789bf":[1,2,488], "group___p_e___types__module.html#ga87b6c55009d3b57b9fed7a447b4789bf":[3,0,0,2,574], "group___p_e___types__module.html#ga87b873c48fa7ae4dfc30c1096a6cbf83":[1,2,332], "group___p_e___types__module.html#ga87b873c48fa7ae4dfc30c1096a6cbf83":[3,0,0,2,295], "group___p_e___types__module.html#ga87d47e1a6591d9a9f4bac4cd9212d85d":[3,0,0,2,374], "group___p_e___types__module.html#ga87d602ee7c3f0019ada3ccc1c34b0c34":[1,2,679], "group___p_e___types__module.html#ga87d602ee7c3f0019ada3ccc1c34b0c34":[3,0,0,2,767], "group___p_e___types__module.html#ga885cc07ce998afe798cd777ddf3f20e0":[1,2,403], "group___p_e___types__module.html#ga885cc07ce998afe798cd777ddf3f20e0":[3,0,0,2,367], "group___p_e___types__module.html#ga88a18010a6279762dc4f9ab58a5cf715":[1,2,334], "group___p_e___types__module.html#ga88a18010a6279762dc4f9ab58a5cf715":[3,0,0,2,297], "group___p_e___types__module.html#ga89181fe4df1c4701239176768b4a9ce5":[3,0,0,2,1025], "group___p_e___types__module.html#ga89181fe4df1c4701239176768b4a9ce5":[1,2,910], "group___p_e___types__module.html#ga894f0d12a49afa98820d693a9a57ad8b":[3,0,0,2,468], "group___p_e___types__module.html#ga89543518340be86d18c7bf585cf2662d":[3,0,0,2,984], "group___p_e___types__module.html#ga89543518340be86d18c7bf585cf2662d":[1,2,869], "group___p_e___types__module.html#ga8957d0a2639d4ecc39466ef0a42c8738":[3,0,0,2,615], "group___p_e___types__module.html#ga8957d0a2639d4ecc39466ef0a42c8738":[1,2,529], "group___p_e___types__module.html#ga89eeb36d5753c21fb55207284dcb208d":[3,0,0,2,936], "group___p_e___types__module.html#ga89eeb36d5753c21fb55207284dcb208d":[1,2,827], "group___p_e___types__module.html#ga8a880419bd7974030cf48279f4ffe0cc":[3,0,0,2,618], "group___p_e___types__module.html#ga8a880419bd7974030cf48279f4ffe0cc":[1,2,532], "group___p_e___types__module.html#ga8af21cbad27c8d061a98924a11fc5a9b":[3,0,0,2,917], "group___p_e___types__module.html#ga8af21cbad27c8d061a98924a11fc5a9b":[1,2,808], "group___p_e___types__module.html#ga8b64bf8fe9946781e3c6740837f08c4c":[1,2,393], "group___p_e___types__module.html#ga8b64bf8fe9946781e3c6740837f08c4c":[3,0,0,2,357], "group___p_e___types__module.html#ga8b8767b3d11f9d621f3d9cadef01f3d3":[1,2,510], "group___p_e___types__module.html#ga8b8767b3d11f9d621f3d9cadef01f3d3":[3,0,0,2,596], "group___p_e___types__module.html#ga8ba907bd69efd3a9ee90fd214f9b8bff":[3,0,0,2,12], "group___p_e___types__module.html#ga8ba907bd69efd3a9ee90fd214f9b8bff":[1,2,52], "group___p_e___types__module.html#ga8bad2911b38dffd91924ee17316b5ebb":[1,2,47], "group___p_e___types__module.html#ga8bad2911b38dffd91924ee17316b5ebb":[3,0,0,2,7], "group___p_e___types__module.html#ga8bd7d99dc1a847cd84fbd377c4dfbd32":[1,2,216], "group___p_e___types__module.html#ga8bd7d99dc1a847cd84fbd377c4dfbd32":[3,0,0,2,179], "group___p_e___types__module.html#ga8bdb11099279dc6b336eba82862773c3":[1,2,716], "group___p_e___types__module.html#ga8bdb11099279dc6b336eba82862773c3":[3,0,0,2,804], "group___p_e___types__module.html#ga8be2fc8922a9d87e948deda961e07b8c":[3,0,0,2,115], "group___p_e___types__module.html#ga8be2fc8922a9d87e948deda961e07b8c":[1,2,153], "group___p_e___types__module.html#ga8c91be8bb0ed8a19088e181d70b91462":[3,0,0,2,844], "group___p_e___types__module.html#ga8c91be8bb0ed8a19088e181d70b91462":[1,2,754], "group___p_e___types__module.html#ga8d6bda73b6c4b43b3d4685cfebeca938":[3,0,0,2,922], "group___p_e___types__module.html#ga8d6bda73b6c4b43b3d4685cfebeca938":[1,2,813], "group___p_e___types__module.html#ga8dfda48d5d12731c35fe1d7e880af946":[1,2,166], "group___p_e___types__module.html#ga8dfda48d5d12731c35fe1d7e880af946":[3,0,0,2,128], "group___p_e___types__module.html#ga8e95f438242726488ade97f41eb2b239":[3,0,0,2,697], "group___p_e___types__module.html#ga8e95f438242726488ade97f41eb2b239":[1,2,611], "group___p_e___types__module.html#ga8edb5d183c47661065a5a7272e4cc3d4":[3,0,0,2,45], "group___p_e___types__module.html#ga8edb5d183c47661065a5a7272e4cc3d4":[1,2,83], "group___p_e___types__module.html#ga8ef4006ea27e84f96ed48ddb2996e422":[3,0,0,2,126], "group___p_e___types__module.html#ga8ef4006ea27e84f96ed48ddb2996e422":[1,2,164], "group___p_e___types__module.html#ga8f2318d5792f691d7d099665714ff692":[3,0,0,2,402], "group___p_e___types__module.html#ga8f61ba5898833d0fec83643643c1c0a4":[3,0,0,2,918], "group___p_e___types__module.html#ga8f61ba5898833d0fec83643643c1c0a4":[1,2,809], "group___p_e___types__module.html#ga8f77774e4af6f729641d53f049da9f22":[3,0,0,2,630], "group___p_e___types__module.html#ga8f77774e4af6f729641d53f049da9f22":[1,2,544], "group___p_e___types__module.html#ga8f8b6fdef1a36893387ee7ecc67ced29":[1,2,421], "group___p_e___types__module.html#ga8f8b6fdef1a36893387ee7ecc67ced29":[3,0,0,2,507], "group___p_e___types__module.html#ga8fade04748cdba6eb9d66171f711851b":[1,2,314], "group___p_e___types__module.html#ga8fade04748cdba6eb9d66171f711851b":[3,0,0,2,277], "group___p_e___types__module.html#ga8fe58c7c2f0e6aed916c1962eaf853ae":[1,2,317], "group___p_e___types__module.html#ga8fe58c7c2f0e6aed916c1962eaf853ae":[3,0,0,2,280], "group___p_e___types__module.html#ga8fec277ddd669fd3da2b0cc9c01e2484":[1,2,310], "group___p_e___types__module.html#ga8fec277ddd669fd3da2b0cc9c01e2484":[3,0,0,2,273], "group___p_e___types__module.html#ga909e62a6d8b7dbb16be18633bb76521f":[3,0,0,2,434], "group___p_e___types__module.html#ga90aa3ff7e416af377dbc09049168971a":[1,2,862], "group___p_e___types__module.html#ga90aa3ff7e416af377dbc09049168971a":[3,0,0,2,971], "group___p_e___types__module.html#ga917a63e22e5d492cd4d4a355678b29b2":[3,0,0,2,87] }; <reponame>mvlopri/seacas-docs var structIogn_1_1ExodusData = [ [ "ExodusData", "structIogn_1_1ExodusData.html#a1830e83d6457045389d0f2d5fdd743cb", null ], [ "ExodusData", "structIogn_1_1ExodusData.html#a9eb135cd393bdb07c0180bab5b8b3b6b", null ], [ "blockTopologicalData", "structIogn_1_1ExodusData.html#aaf968ac6e36fdc550236c07d6954568d", null ], [ "coordinates", "structIogn_1_1ExodusData.html#a59727f4c77c5359b3a0a302fd73079a8", null ], [ "elementBlockConnectivity", "structIogn_1_1ExodusData.html#aff6f330a40242d78ddf3d27a2a219a41", null ], [ "globalIdsOfLocalElements", "structIogn_1_1ExodusData.html#a309c91ca233928b28507003b5a1366ac", null ], [ "globalIdsOfLocalNodes", "structIogn_1_1ExodusData.html#aebbcb559c40a2279792bf5aaf26dcef6", null ], [ "globalNumberOfElementsInBlock", "structIogn_1_1ExodusData.html#a458959d60476ca5133a0887776fa04d6", null ], [ "globalNumberOfNodes", "structIogn_1_1ExodusData.html#a5e04e4d8f74f9b229523f87f74a5000a", null ], [ "localNumberOfElementsInBlock", "structIogn_1_1ExodusData.html#acc2dc76db9789a95095faf7d0d66fb7b", null ], [ "sharedNodes", "structIogn_1_1ExodusData.html#a1e00c93b859a22e52f51b50e586bcdff", null ], [ "sidesetConnectivity", "structIogn_1_1ExodusData.html#a3d3302a917d5acf85777004d12189ff2", null ], [ "sidesetTouchingBlocks", "structIogn_1_1ExodusData.html#ac9250d64d6f7a36ba00e39374ea33c5b", null ] ];(function() { ($('#cancel_link')).click(function(event) { event.preventDefault(); ($('.no-objects-found')).show(); ($('#new_image_link')).show(); return ($('#images')).html(''); }); }).call(this); var remote = new PouchDB('http://localhost:5984/blah'); var db = new PouchDB('can-events'); function doSync() { console.log('syncing now... '); db.sync(remote, {live: true}) .on('error', function(err) { console.log(err); // Retry connection every 5 seconds setTimeout(doSync, 5000); }); } doSync(); export default EmberPouch.Adapter.extend({ db: db }); import getCategoriesFromAPI from '../utils/getCategories' import getPostsFromAPI from '../utils/getPosts' import deletePostFromAPI from '../utils/deletePost' import changeVoteFromAPI from '../utils/changeVote' import changeCommentVoteFromAPI from '../utils/changeCommentVote' import saveEditFromAPI from '../utils/saveEdit' import getCommentsFromAPI from '../utils/getComments' import saveNewCommentAPI from '../utils/saveNewComment' import saveNewPostAPI from '../utils/saveNewPost' import deleteCommentFromAPI from '../utils/deleteComment' import saveEditCommentFromAPI from '../utils/saveEditComment' import { ADD_ALL_POSTS , REMOVE_POST , ADD_CATEGORIES , CHANGE_VOTE , UPDATE_POST , START_EDIT , UPDATE_EDIT , CANCEL_EDIT , SAVE_EDIT , SET_CATEGORY , ADD_COMMENTS , ADD_NEW_COMMENT , REMOVE_COMMENT , CHANGE_COMMENT_VOTE , CLEAR_COMMENTS , UPDATE_POST_COMMENT_COUNT , MODAL_OPEN , MODAL_CLOSE , UPDATE_NEW_COMMENT , CANCEL_NEW_COMMENT , CANCEL_NEW_POST, CHANGE_SORT, UPDATE_NEW_POST , START_EDIT_COMMENT , CANCEL_EDIT_COMMENT , UPDATE_EDIT_COMMENT , ADD_NEW_POST, UPDATE_COMMENT, } from './types'; export function cancelEdit (id) { console.log("in canceled it") console.log(id) return { type: CANCEL_EDIT, id } } //TODO: this needs to update the server and the reducer needs fixing export function saveEditReducer ({id}) { return { type: SAVE_EDIT, id } } export function changeSort({sortMethod}){ return { type:CHANGE_SORT, sortMethod, } } export function openModal({modal}){ return { type:MODAL_OPEN, modal, } } export function closeModal({modal}){ return { type:MODAL_CLOSE, } } export function updateEditField (id, title, body,category,author) { console.log("in updateditfield") console.log(id + " " + title + " " + body) return { type: UPDATE_EDIT, id, title, body, category, author } } export function updateWritingCommentField (body,author) { console.log("in updateditfield") console.log(body + " " + author) return { type: UPDATE_NEW_COMMENT, body, author } } export function cancelWritingCommentField (body,author) { return { type: CANCEL_NEW_COMMENT, body, author } } export function cancelNewPost () { return { type: CANCEL_NEW_POST, } } export function setEditComment (id,parentId,body,author) { return { type: START_EDIT_COMMENT, id, parentId, body, author, } } export function cancelEditComment (id,parentId,body,author) { return { type: CANCEL_EDIT_COMMENT, id, parentId, body, author, } } export function updateEditComment (id,parentId,body,author) { return { type: UPDATE_COMMENT, id, parentId, body, author, } } export function setEditPost (id,title,body,category,author) { return { type: START_EDIT, id, title, body, category, author } } export function endEditPost ({id,saveCancel}) { return { type: START_EDIT, id, saveCancel } } export function updatePost (data) { const {author, body, title, id,category,deleted, voteScore} = data return { type: UPDATE_POST, author, body, title, id, category, deleted, voteScore, } } export function updateNewPost (data) { const {author, body, title, id,category,deleted, voteScore} = data return { type: UPDATE_NEW_POST, author, body, title, id, category, deleted, voteScore, } } export function addPost ({ id, timestamp,title,body,author,category,voteScore,deleted,comments,totalComments }) { console.log("in add post function") // console.log(id) return { type: ADD_NEW_POST, id, timestamp, title, body, author, category, voteScore, deleted, comments, totalComments } } export function removeComment (comment ) { // console.log("Remove_Post " + id) return { type: REMOVE_COMMENT, comment, parentId:comment.parentId, id:comment.id } } export function removePost (id ) { // console.log("Remove_Post " + id) return { type: REMOVE_POST, id, } } export function addCommentCountToPost(id,count) { return { type: UPDATE_POST_COMMENT_COUNT, id, count } } export function categoriesReturned(categories) { //console.log("in categories returned") //console.log(categories) return { type: ADD_CATEGORIES, categories } } export function updateEditingCommentField(comments){ return { type: UPDATE_EDIT_COMMENT, comments } } export function commentsReturned(comments) { return { type: ADD_COMMENTS, comments } } export function addNewComment(comments) { return { type: ADD_NEW_COMMENT, comments } } export function clearComments(comments) { return { type: CLEAR_COMMENTS, comments } } export function postsReturned(posts) { //console.log("in postsreturned posts are next"); //console.log(posts) return { type: ADD_ALL_POSTS, posts } } export function changeCommentVotePost(comments) { //const [ id, vote ] = data console.log("in changecomment vote") console.log(comments.comments) return { type: CHANGE_COMMENT_VOTE, comments:comments.comments, } } export function changeVotePost (data) { const [ id, vote ] = data return { type: CHANGE_VOTE, id, vote, } } export const editComment = (comment) => { const {id,parentId,author,body} = comment return setEditComment(id,parentId,author,body) } export const editPost = (id,title,body,category) => { return setEditPost(id,title,body,category) } export function setDisplayCategory (category) { return { type: SET_CATEGORY, category } } export const setCategory = (category) => { return setDisplayCategory(category) } export const addPostToServer = (post) => dispatch =>( saveNewPostAPI(post) .then(post => dispatch(addPost(post) ) ) ) export const changeVote = (id) => dispatch =>( changeVoteFromAPI(id) //need to finish update post in state .then(posts => dispatch(changeVotePost( id ) ) ) ) export const changeCommentVote = (id) => dispatch =>( changeCommentVoteFromAPI(id) //need to finish update post in state .then(comments => { console.log("about to return") console.log(comments) dispatch(changeCommentVotePost( comments ) )} ) ) export const saveEditComment = (state) => dispatch =>( saveEditCommentFromAPI(state) .then(posts => dispatch(updateEditComment(state))) .then(posts => dispatch(cancelEditComment({id: "dd"}))) ) export const saveEdit = (state) => dispatch =>( saveEditFromAPI(state) .then(posts => dispatch(updatePost(state))) .then(posts => dispatch(cancelEdit({id: "dd"}))) ) export const deletePost = (id) => dispatch =>( deletePostFromAPI(id) .then(posts => dispatch(removePost( id ) ) ) ) export const deleteComment = (id) => dispatch =>( deleteCommentFromAPI(id) .then(comment => dispatch(removeComment( comment ) ) ) ) export const saveNewComment = (comment) => dispatch =>( saveNewCommentAPI(comment) .then(comment => dispatch(addNewComment(comment) ) ) ) export const getPosts = (posts) => dispatch =>( getPostsFromAPI(posts) .then(posts => dispatch(postsReturned(posts) ) ) ) export const getComments = (comments) => dispatch =>( getCommentsFromAPI(comments) .then(comments => { console.log("in getcomments") dispatch(commentsReturned( comments //posts.reduce((ret,cur,index, array) => {return ret.concat(cur)},[]) ) )} ) ) export const getPostsAndComments = (posts) => dispatch => dispatch(getPosts(posts)) //export const getCategories = () => getCategoriesFromAPI() export const getCategories = () => dispatch =>( getCategoriesFromAPI() //.getCategories() //.then(categories => (console.log(categories))) .then(categories => dispatch(categoriesReturned( categories //categories.reduce((ret,cur,index, array) => {return ret.concat(cur)},[]) ) ) ) ) <filename>public/src/gui/tr/korean.js define(function (require, exports, module) { 'use strict'; var TR = { // background backgroundTitle: '배경', backgroundReset: '초기화', backgroundImport: '배경 (jpg, png...)', backgroundFill: '채우기', // camera cameraTitle: '카메라', cameraReset: '뷰', cameraCenter: '초기화 (bar)', cameraFront: '앞쪽 (F)', cameraLeft: '왼쪽 (L)', cameraTop: '위쪽 (T)', cameraMode: '모드', cameraOrbit: '궤도 (Turntable)', cameraSpherical: '구 (Trackball)', cameraPlane: '평면 (Trackball)', cameraProjection: '투사', cameraPerspective: '원근법', cameraOrthographic: '정사영법', cameraFov: '시야각', cameraPivot: '피봇 고르기', // file fileTitle: '파일 (가져오기/내보내기)', fileImportTitle: '가져오기', fileAdd: '파일 (obj, sgl, ply, stl)', fileAutoMatrix: null, fileVertexSRGB: null, fileExportMeshTitle: '메쉬 내보내기', fileExportSceneTitle: '장면 내보내기', fileExportSGL: 'sgl로 저장하기', fileExportOBJ: 'obj로 저장하기', fileExportPLY: 'ply로 저장하기', fileExportSTL: 'stl로 저장하기', // scene sceneTitle: '장면', sceneReset: '장면 초기화', sceneAddSphere: '구 추가하기 ', sceneAddCube: null, sceneAddCylinder: null, sceneAddTorus: null, sceneSelection: null, sceneMerge: null, // mesh meshTitle: '메쉬', meshNbVertices: '점들 : ', meshNbFaces: '면들 : ', // topology topologyTitle: '토폴로지', //multires multiresTitle: '다중 해상도', multiresSubdivide: '세분화', multiresReverse: '리버스', multiresResolution: '해상도', multiresNoLower: '더 낮은 해상도가 존재하지 않습니다.', multiresNoHigher: '더 높은 해상도가 존재하지 않습니다.', multiresDelHigher: '더 높은 것을 삭제', multiresDelLower: '더 낮은 것을 삭제', multiresSelectLowest: '리버싱 하기 전에 더 낮은 해상도를 고르세요.', multiresSelectHighest: '세분화 하기 전에 더 높은 해상도를 고르세요', multiresWarnBigMesh: function (nbFacesNext) { return '다음 세분화 레벨은 ' + nbFacesNext + ' 면만큼 도달할 것입니다.\n' + '만약 당신이 무엇을 하는지 안다면 "세분화"를 다시 클릭하세요.'; }, multiresNotReversible: '이 메쉬는 리버싱할 수 없습니다.\n' + '이 메쉬는 여러가지 메쉬의 표면의 세분화를 product한 것이 아닙니다.(loop-catmull)', // remesh remeshTitle: null, remeshRemesh: null, remeshResolution: null, remeshBlock: null, // dynamic dynamicTitle: null, dynamicActivated: null, dynamicSubdivision: null, dynamicDecimation: null, dynamicLinear: null, // sculpt sculptTitle: null, sculptBrush: '브러쉬', sculptInflate: null, sculptTwist: null, sculptSmooth: null, sculptFlatten: null, sculptPinch: null, sculptCrease: null, sculptDrag: null, sculptPaint: null, sculptMasking: null, sculptMove: null, sculptLocalScale: null, sculptTransform: null, sculptCommon: null, sculptTool: null, sculptSymmetry: null, sculptContinuous: null, sculptRadius: null, sculptIntensity: null, sculptHardness: null, sculptCulling: null, sculptAlphaTitle: null, sculptLockPositon: null, sculptAlphaTex: null, sculptImportAlpha: null, sculptNegative: null, sculptColor: null, sculptRoughness: null, sculptMetallic: null, sculptClay: null, sculptAccumulate: null, sculptColorGlobal: null, sculptPickColor: null, sculptTangentialSmoothing: null, sculptTopologicalCheck: null, sculptMoveAlongNormal: null, sculptMaskingClear: null, sculptMaskingInvert: null, sculptMaskingBlur: null, sculptMaskingSharpen: null, sculptPBRTitle: null, sculptPaintAll: null, sculptExtractTitle: null, sculptExtractThickness: null, sculptExtractAction: null, // states stateTitle: '역사', stateUndo: '되돌리기', stateRedo: '다시하기', stateMaxStack: '최대 스택', // wacom wacomTitle: '와콤 테블릿', wacomRadius: '압력 반지름', wacomIntensity: '압력 강도', // rendering renderingTitle: '렌더링', renderingGrid: '그리드 보이기', renderingSymmetryLine: '대칭선 보이기', renderingMatcap: null, renderingCurvature: null, renderingPBR: null, renderingTransparency: '투명도', renderingNormal: '노말 쉐이더', renderingUV: 'UV 쉐이더', renderingShader: '쉐이더', renderingMaterial: '질', renderingImportUV: '가져오기 (jpg, png...)', renderingImportMatcap: '가져오기 (jpg, png...)', renderingExtra: '추가', renderingFlat: '편평한 (느리게)', renderingWireframe: '와이어프레임 (느리게) (W)', renderingExposure: null, renderingEnvironment: null, renderingIsolate: null, renderingFilmic: null, // contour contour: null, contourShow: null, contourColor: null, darkenUnselected: null, // pixel ratio resolution: null, // matcaps matcapPearl: null, matcapClay: null, matcapSkin: null, matcapGreen: null, matcapWhite: null, // sketchfab sketchfabTitle: 'Sketchfab으로 가기 !', sketchfabUpload: '올리기', sketchfabUploadMessage: null, // sketchfabUploadError: null, // sketchfabUploadSuccess: null, sketchfabAbort: null, sketchfabUploadProcessing: null, about: null, alphaNone: null, alphaSquare: null, alphaSkin: null, envFootPrint: null, envGlazedPatio: null, envNicolausChurch: null, envTerrace: null, envBryantPark: null }; module.exports = TR; });<reponame>agnezi/pig-bank_web import { ExpensesTypes } from "./types"; import { action } from "typesafe-actions"; export const loadRequest = (page, pageSize) => action(ExpensesTypes.LOAD_REQUEST, { page, pageSize }); export const loadSuccess = data => action(ExpensesTypes.LOAD_SUCCESS, { data }); export const loadFailure = () => action(ExpensesTypes.LOAD_FAILURE); export const createRequest = data => action(ExpensesTypes.CREATE_REQUEST, { data }); export const createSuccess = data => action(ExpensesTypes.CREATE_SUCCESS, { data }); export const createFailure = () => action(ExpensesTypes.CREATE_FAILURE); export const deleteRequest = data => action(ExpensesTypes.DELETE_REQUEST, { data }); export const deleteSuccess = data => action(ExpensesTypes.DELETE_SUCCESS, { data }); <reponame>paularrea/earlyKolyerLanding import React, { useEffect, useState } from "react"; import { graphql, Link } from "gatsby"; import SubscribeComponent from "../components/blogComponents/subscribeComponent"; import Layout from "../components/layout/layout"; import { Grid, Row, Col } from "react-flexbox-grid"; import Seo from "../components/seo"; import Img from "gatsby-image"; import { span, container, bg_img, content, post_flex, search_container, search_absolute, post, } from "../styles/blog.module.scss"; import AllPosts from "../components/blogComponents/allPosts"; import BlogImg from "../components/blogComponents/blogBackgroundImg"; import searchIcon from "../images/icons/search.png"; const Blog = ({ data }) => { const [state, setState] = useState({ filteredPosts: [], query: "", }); const allPosts = data.allMarkdownRemark.edges; useEffect(() => { window.scrollTo(0, 0); }, []); const handleInputChange = (event) => { const query = event.target.value; const filteredPosts = allPosts.filter((post) => { const { title } = post.node.frontmatter; return title.toLowerCase().includes(query.toLowerCase()); }); setState({ query, filteredPosts, }); }; const posts = state.query ? state.filteredPosts : allPosts; useEffect(() => { window.scrollTo(0, 0); }, []); return ( <Layout> <Seo title="Blog" /> <BlogImg> <div className={bg_img}> <div data-sal="fade" data-sal-delay="100" data-sal-duration="1000" className={content} > <h2> Descubre y aprende <br /> todo sobre nuestros perros </h2> <p style={{ color: "white" }}> Un contenido quincenal para convertirte en un experto. </p> <SubscribeComponent /> </div> </div> </BlogImg> <div className={container} style={{ paddingTop: "6rem" }}> <div className={search_absolute}> <div className={search_container}> <input type="text" aria-label="Buscar" placeholder="Buscar" value={state.query} onChange={handleInputChange} /> <img src={searchIcon} alt="search" /> </div> </div> <span className={span}>Un mundo por descubrir.</span> <h2>Últimos artículos</h2> <div className={post_flex}> <Grid> <Row> {posts.slice(0, 3).map((edge) => { const { fields, frontmatter } = edge.node ; return ( <Col md={4} sm={12} xs={12}> <div className={post} key={fields.slug}> <Link to={fields.slug}> <Img fluid={ frontmatter.featuredImage.childImageSharp.fluid } /> <h5>{frontmatter.title}</h5> </Link> <Link to={fields.slug}> <button>Leer más</button> </Link> </div> </Col> ); })} </Row> </Grid> </div> <AllPosts /> </div> </Layout> ); }; // export const query = graphql` // query blogQuery { // allMarkdownRemark( // sort: { fields: [frontmatter___date], order: DESC } // filter: { frontmatter: { type: { eq: "blog" } } } // ) { // edges { // node { // frontmatter { // title // path // date(formatString: "YYYY MMMM Do") // featuredImage { // childImageSharp { // fluid(maxWidth: 800) { // ...GatsbyImageSharpFluid // } // } // } // } // } // } // } // } // `; export const query = graphql` query { site { siteMetadata { title } } allMarkdownRemark( sort: { fields: [frontmatter___date], order: DESC } filter: { frontmatter: { type: { eq: "blog" } } } ) { edges { node { excerpt fields { slug } frontmatter { title path date(formatString: "YYYY MMMM Do") featuredImage { childImageSharp { fluid(maxWidth: 800) { ...GatsbyImageSharpFluid } } } } } } } } `; export default Blog; var page = require('webpage').create(); page.onInitialized = function() { page.evaluate(function(domContentLoadedMsg) { document.addEventListener('DOMContentLoaded', function() { window.callPhantom('DOMContentLoaded'); }, false); }); }; page.onCallback = function(data) { // your code here console.log('DOMContentLoaded'); phantom.exit(0); }; page.open('http://phantomjs.org/'); <reponame>stanleychen96/js_17.09.14 /** * 2017-09-14 <NAME> */ var afternoon = { question: 'property', answer: 'folder', number: 9, _1: true, }; for (var key in afternoon) { console.log(key); console.log(afternoon, afternoon[key]) } <gh_stars>0 (function() { let currentPageIndex = 0; let pageMode = 1; let cursorIndex = Math.floor(currentPageIndex / pageMode); let pdfInstance = null; let totalPagesCount = 0; const viewport = document.querySelector("#viewport"); window.initPDFViewer = function(pdfURL) { pdfjsLib.getDocument(pdfURL).then(pdf => { pdfInstance = pdf; totalPagesCount = pdf.numPages; initPager(); initPageMode(); render(); }); }; function onPagerButtonsClick(event) { const action = event.target.getAttribute("data-pager"); if (action === "prev") { if (currentPageIndex === 0) { return; } currentPageIndex -= pageMode; if (currentPageIndex < 0) { currentPageIndex = 0; } render(); } if (action === "next") { if (currentPageIndex === totalPagesCount - 1) { return; } currentPageIndex += pageMode; if (currentPageIndex > totalPagesCount - 1) { currentPageIndex = totalPagesCount - 1; } render(); } } function initPager() { const pager = document.querySelector("#pager"); pager.addEventListener("click", onPagerButtonsClick); return () => { pager.removeEventListener("click", onPagerButtonsClick); }; } function onPageModeChange(event) { pageMode = Number(event.target.value); render(); } function initPageMode() { const input = document.querySelector("#page-mode input"); input.setAttribute("max", totalPagesCount); input.addEventListener("change", onPageModeChange); return () => { input.removeEventListener("change", onPageModeChange); }; } function render() { cursorIndex = Math.floor(currentPageIndex / pageMode); const startPageIndex = cursorIndex * pageMode; const endPageIndex = startPageIndex + pageMode < totalPagesCount ? startPageIndex + pageMode - 1 : totalPagesCount - 1; const renderPagesPromises = []; for (let i = startPageIndex; i <= endPageIndex; i++) { renderPagesPromises.push(pdfInstance.getPage(i + 1)); } Promise.all(renderPagesPromises).then(pages => { const pagesHTML = `<div style="width: ${ pageMode > 1 ? "50%" : "100%" }"><canvas></canvas></div>`.repeat(pages.length); viewport.innerHTML = pagesHTML; pages.forEach(renderPage); }); } function renderPage(page) { let pdfViewport = page.getViewport(0.75); const container = viewport.children[page.pageIndex - cursorIndex * pageMode]; pdfViewport = page.getViewport(container.offsetWidth / pdfViewport.width); const canvas = container.children[0]; const context = canvas.getContext("2d"); canvas.height = pdfViewport.height; canvas.width = pdfViewport.width; page.render({ canvasContext: context, viewport: pdfViewport }); } })();<gh_stars>0 import { FETCH_SITES } from '../actions/fetchSites'; import { CLEAR } from '../actions/clear'; export const initialState = []; const fetchSites = (state = initialState, action) => { switch(action.type) { case FETCH_SITES: if (action.skip > 0) return [...state, ...action.jsonObjects]; else return action.jsonObjects; case CLEAR: return []; default: return state; } }; export default fetchSites;const { compose } = require('compose-middleware') const { sse } = require("@toverux/expresse") module.exports = function(getHub) { function middleware(req, res, next) { const hub = getHub(req, res) if (!hub) { return res.status(404).end() } //=> Register the SSE functions of that client on the hub hub.register(res.sse); //=> Unregister the user from the hub when its connection gets closed (close=client, finish=server) res.once('close', () => hub.unregister(res.sse)); res.once('finish', () => hub.unregister(res.sse)); //=> Make hub's functions available on the response res.sse.broadcast = { data: hub.data.bind(hub), event: hub.event.bind(hub), comment: hub.comment.bind(hub), }; //=> Done next(); } return compose(sse(), middleware); }<filename>debug-db/src/main/assets/app.js $( document ).ready(function() { getDBList(); $("#query").keypress(function(e){ if(e.which == 13) { queryFunction(); } }); }); function getData(tableName) { $.ajax({url: "getAllDataFromTheTable?tableName="+tableName, success: function(result){ result = JSON.parse(result); inflateData(result); }}); } function queryFunction() { var query = $('#query').val(); $.ajax({url: "query?query="+escape(query), success: function(result){ result = JSON.parse(result); inflateData(result); }}); } function getDBList() { $.ajax({url: "getDbList", success: function(result){ result = JSON.parse(result); var dbList = result.rows; $('#db-list').empty(); var isSelectionDone = false; for(var count = 0; count < dbList.length; count++){ if(dbList[count].indexOf("journal") == -1){ $("#db-list").append("<a href='#' id=" +dbList[count] + " class='list-group-item' onClick='openDatabaseAndGetTableList(\""+ dbList[count] + "\");'>" +dbList[count] + "</a>"); if(!isSelectionDone){ isSelectionDone = true; $('#db-list').find('a').trigger('click'); } } } }}); } function openDatabaseAndGetTableList(db) { if("APP_SHARED_PREFERENCES" == db) { $('#run-query').removeClass('active'); $('#run-query').addClass('disabled'); } else { $('#run-query').removeClass('disabled'); $('#run-query').addClass('active'); } $("#selected-db-info").text("Selected Database : "+db); $.ajax({url: "getTableList?database="+db, success: function(result){ result = JSON.parse(result); var tableList = result.rows; $('#table-list').empty() for(var count = 0; count < tableList.length; count++){ $("#table-list").append("<a href='#' class='list-group-item' onClick='getData(\""+ tableList[count] + "\");'>" +tableList[count] + "</a>"); } }}); } function inflateData(result){ if(result.isSuccessful){ showSuccessInfo(); var columnHeader = result.columns.map(function(columnName) { return {"title": columnName}; }); var columnData = result.rows; var tableId = "#db-data"; if ($.fn.DataTable.isDataTable(tableId) ) { $(tableId).DataTable().destroy(); } $("#db-data-div").remove(); $("#parent-data-div").append('<div id="db-data-div"><table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered display" id="db-data"></table></div>'); $(tableId).dataTable({ "data": columnData, "columns": columnHeader, 'bPaginate': true, 'searching': true, 'bFilter': true, 'bInfo': true, "bSort" : true, "scrollX": true, "iDisplayLength": 10 }); // hack to fix alignment issue when scrollX is enabled $(".dataTables_scrollHeadInner").css({"width":"100%"}); $(".table ").css({"width":"100%"}); }else{ showErrorInfo(); } } function showSuccessInfo(){ $("#success-info").show(); $("#error-info").hide(); } function showErrorInfo(){ $("#success-info").hide(); $("#error-info").show(); } function hideBothInfo(){ $("#success-info").hide(); $("#error-info").hide(); }<reponame>donaldnevermore/javascript-exercises /** * 解析查询字符串 */ function getQueryStringArgs() { let qs = location.search.length > 0 ? loction.search.substring(1) : "" let args = {} let items = qs.length ? qs.split("&") : [] let item = null let name = null let value = null let i = 0 let len = items.length for (let i = 0; i < len; i++) { item = items[i].split("=") name = decodeURIComponent(item[0]) value = decodeURIComponent(item[1]) if (name.length) { args[name] = value } } return args } /** * 拼接查询字符串 * @param {Object} obj */ function setQueryStringArgs(obj) { let value = null let name = null let query = "" for (let name of Object.keys(obj)) { value = obj[name] query += encodeURIComponent(name) + "=" + encodeURIComponent(value) + "&" } return query.length ? query.substring(0, query.length - 1) : "" } // fetch("./modules/read_directories.php?file") // .then(function (response) { // return response.json(); // }) // .then(function (json) { // console.log(json); // }) // .catch(function (err) { // console.log("Fetch problem: " + err.message); // }); // $("i[data-file]").click(function () { // // console.log("Holaaa"); // }); <filename>src/components/header/styles.js import { StyleSheet } from 'react-native' import { fonts, colors } from '../../styles' export default StyleSheet.create({ base: { width: '100%', flexDirection: 'row', alignItems: 'center', paddingRight: 30 }, leftButton: { height: 67, paddingHorizontal: 30, paddingVertical: 15, justifyContent: 'center', alignItems: 'center' }, img: { height: 48, width: 32 }, titleContainer: { flex: 1, justifyContent: 'center' }, title: { ...fonts.default, fontSize: 20, fontWeight: 'bold', color: colors.white } }) /*global describe, it, assert */ define('first-element', function(require) { 'use strict'; var proto = Object.create(HTMLElement.prototype); proto.createdCallback = require('htemplate')(function(html) { html`<h1 class="first-element">first-element</h1>`; }); document.registerElement('first-element', { prototype: proto }); }); define(function(require) { 'use strict'; require('first-element'); document.getElementById('htemplate-out').innerHTML = ` <first-element></first-element> `; describe('Basic custom element', function() { it('innerHTML generated by htemplate', function() { assert.equal(true, document.querySelector('first-element > h1') .classList.contains('first-element')); }); }); }); <gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Option_1 = require("./Option"); var Option_2 = require("./Option"); exports.Option = Option_2.default; var OptionContext_1 = require("./OptionContext"); exports.OptionContext = OptionContext_1.default; var Selector_1 = require("./Selector"); exports.Selector = Selector_1.default; exports.TopOption = new Option_1.default({ key: 'topType', label: 'Top', }); exports.AccessoriesOption = new Option_1.default({ key: 'accessoriesType', label: '↳ 👓 Accessories', }); exports.HatColorOption = new Option_1.default({ key: 'hatColor', label: '🎨 HatColor', }); exports.HairColorOption = new Option_1.default({ key: 'hairColor', label: '↳ 💈 Hair Color', }); exports.FacialHairOption = new Option_1.default({ key: 'facialHairType', label: 'Facial Hair', }); exports.FacialHairColor = new Option_1.default({ key: 'facialHairColor', label: '↳ ✂️ Facial Hair Color', }); exports.ClotheOption = new Option_1.default({ key: 'clotheType', label: '👔 Clothes', }); exports.ClotheColorOption = new Option_1.default({ key: 'clotheColor', label: '↳ Color Fabric', }); exports.GraphicOption = new Option_1.default({ key: 'graphicType', label: '↳ Graphic', }); exports.EyesOption = new Option_1.default({ key: 'eyeType', label: '👁 Eyes', }); exports.EyebrowOption = new Option_1.default({ key: 'eyebrowType', label: '✏️ Eyebrow', }); exports.MouthOption = new Option_1.default({ key: 'mouthType', label: '👄 Mouth', }); exports.SkinOption = new Option_1.default({ key: 'skinColor', label: '🎨 Skin', }); exports.allOptions = [ exports.TopOption, exports.AccessoriesOption, exports.HatColorOption, exports.HairColorOption, exports.FacialHairOption, exports.FacialHairColor, exports.ClotheOption, exports.ClotheColorOption, exports.GraphicOption, exports.EyesOption, exports.EyebrowOption, exports.MouthOption, exports.SkinOption, ]; <gh_stars>0 // Components============== import { motion } from "framer-motion"; import { useMediaQ } from "hooks-lib"; import React from "react"; import styled from "styled-components"; // ========================= const Wrapper = styled(motion.div)` cursor: pointer; position: absolute; position: ${({ sticky }) => sticky && "fixed"}; right: 20px; top: 13px; height: 40px; width: 40px; z-index: 153; display: flex; justify-content: center; align-items: center; flex-direction: column; `; const Bar = styled(motion.div)` background: ${({ theme: { gray } }) => gray[14]}; height: 8%; width: 70%; margin-bottom: 4px; border-radius: ${({ theme: { borderRadius } }) => borderRadius}; `; const Top = styled(Bar)``; const Center = styled(Bar)` width: 55%; `; const Bottom = styled(Bar)` margin-bottom: 0; `; export default function Burger({ isToggled, toggle, sticky }) { const burgerQuerySmall = useMediaQ("max", 320); const burgerQuery = useMediaQ("max", 380); return ( <Wrapper onClick={toggle} sticky={sticky} animate={ isToggled ? { x: burgerQuerySmall ? "0" : burgerQuery ? "-75px" : "-40vw" } : { x: "0" } } > <Top animate={!isToggled ? `menuOpen` : `menuClosed`} variants={{ menuClosed: { rotate: 45, y: 8, }, menuOpen: { rotate: 0, y: 0, }, }} initial={false} /> <Center animate={!isToggled ? `menuOpen` : `menuClosed`} variants={{ menuClosed: { x: "60vw", }, menuOpen: { x: 0, }, }} initial={false} ter /> <Bottom animate={!isToggled ? `menuOpen` : `menuClosed`} variants={{ menuClosed: { rotate: 320, y: -8, }, menuOpen: { rotate: 0, y: 0, }, }} initial={false} /> </Wrapper> ); } <filename>src/App.js<gh_stars>1-10 import React, { Component } from "react"; import "bootstrap/dist/css/bootstrap.min.css"; import "./App.css"; import { connect } from "react-redux"; import { getCurrentUser } from "./actions/currentUser"; import TasksContainer from "./components/TasksContainer.js"; import NavBar from "./components/NavBar.js"; import { fetchDepartments } from "./actions/departments"; import { fetchComments } from "./actions/comments"; import { withRouter } from "react-router-dom"; import AuthContainer from "./components/AuthContainer"; class App extends Component { componentDidMount() { this.props.getCurrentUser(); this.props.fetchDepartments(); this.props.fetchComments(); } render() { return ( <div className="App"> <NavBar loggedIn={this.props.loggedIn} history={this.props.history} /> <br /> {this.props.loggedIn ? ( <TasksContainer history={this.props.history} /> ) : ( <AuthContainer history={this.props.history} /> )} </div> ); } } const mapStateToProps = (state) => { return { loggedIn: !!state.currentUser, }; }; export default withRouter( connect(mapStateToProps, { getCurrentUser, fetchDepartments, fetchComments })( App ) ); import * as THREE from 'three'; import SpaceObject from './SpaceObject'; class Grid extends SpaceObject { // ############################################## // # Constructor ################################ // ############################################## constructor(scene, name, options) { super(); this.scene = scene; this.name = name; this.position = options.position || new THREE.Vector3(); this.width = options.width || 7500; this.height = options.height || 7500; this.segments = options.segments || 600; this.moveWithCamera = options.moveWithCamera || false; this.opacity = options.opacity || 0.1; this.color = options.color || 0xffffff; if (this.moveWithCamera) { this.cameraOffset = this.position.clone().add(this.scene.camera.camera.position); } this.createMesh(); this.scene.add(this.mesh); } // ############################################## // # Private functions ########################## // ############################################## createMesh() { const geometry = new THREE.Geometry(); // Loop end condition has to accomodate for even/odd number of segments let condition = (this.segments % 2 === 0) ? this.width / 2 + 1 : this.width / 2; for (let x = -this.width / 2; x <= condition; x += this.width / this.segments) { geometry.vertices.push( new THREE.Vector3(x, 0, -this.height / 2), new THREE.Vector3(x, 0, this.height / 2), ); } condition = (this.segments % 2 === 0) ? this.height / 2 + 1 : this.height / 2; for (let z = -this.height / 2; z <= condition; z += this.height / this.segments) { geometry.vertices.push( new THREE.Vector3(-this.width / 2, 0, z), new THREE.Vector3(this.width / 2, 0, z), ); } const material = new THREE.LineBasicMaterial({ color: this.color, transparent: true }); material.opacity = this.opacity; this.mesh = new THREE.LineSegments(geometry, material); this.mesh.position.set(this.position.x, this.position.y, this.position.z); } // ############################################## // # Public functions ########################### // ############################################## update(deltaT) { super.update(deltaT); const { camera } = this.scene.camera; if (this.moveWithCamera) { const roundedOffset = new THREE.Vector3( (camera.position.x - this.cameraOffset.x) % (this.width / this.segments), camera.position.y - this.cameraOffset.y, (camera.position.z - this.cameraOffset.z) % (this.height / this.segments), ); const newPosition = camera.position .clone() .sub(this.cameraOffset) .sub(roundedOffset); this.position.set( newPosition.x, newPosition.y, newPosition.z, ); this.mesh.position.set(this.position.x, this.position.y, this.position.z); } } } // class export default Grid; <reponame>Devyani606/chatwoot import types from '../../../mutation-types'; import { mutations } from '../../conversationStats'; describe('#mutations', () => { describe('#SET_CONV_TAB_META', () => { it('set conversation stats correctly', () => { const state = {}; mutations[types.SET_CONV_TAB_META](state, { mine_count: 1, unassigned_count: 1, all_count: 2, }); expect(state).toEqual({ mineCount: 1, unAssignedCount: 1, allCount: 2, }); }); }); }); <filename>test/variables/ancient-20th-century-browser.spec.js const setupEnv = require('./setupEnv'); const getVariables = require('../../src/variables'); const defaultOptions = require('../../src/api/defaultOptions'); const testingEnvMissingData = setupEnv({ data: 'missing', }); describe('returns on client-side', () => { describe('null', () => { describe('with missing window properties', () => { it('with default options', () => { expect(getVariables({}, defaultOptions)).toEqual(testingEnvMissingData); }); }); }); }); alert ('Carregando...'); function escreveNome() { for (var x=0; x<=10; x++){} }<filename>chrome/background.js chrome.browserAction.onClicked.addListener(function () { chrome.tabs.getSelected(null, function (tab) { openBugShot(tab); }); }); chrome.commands.onCommand.addListener(function (command) { if(command == 'toggle-bugshot-on') { chrome.tabs.getSelected(null, function (tab) { openBugShot(tab); }); } }); function openBugShot(tab) { chrome.tabs.captureVisibleTab(null, { format: "png" }, function (data) { localStorage.setItem("screenshot", data); chrome.tabs.create({ index: tab.index + 1, url: "common/editor.html" }, function (tab) { // DOES NOTHING FOR NOW }); }); } var _ym_rule = null; function ruleClick(btn,jsonurl) { if (_ym_rule == null) _ym_rule = new Rule(); if(jsonurl){ _ym_rule.setting.defaultJsonUrl = jsonurl; if(jsonurl == '/json/userskill'){ _ym_rule.setting.maxSkillLevel = '2'; _ym_rule.setting.defaultValidate = 'integer,numberLimit!1!2'; _ym_rule.setting.defaultErrormsg = '输入1到2之间的整数'; } } _ym_rule.click(); } function Rule() {} Rule.prototype.setting = { 'tags': [], 'modalid': 'select-rule-modal', 'container': 'ruleContainer', 'confirm':'my-confirm-rule', 'tagsList':'rulesList', 'defaultJsonUrl':'/json/taskRule', 'defaultValue':'', 'maxSkillLevel':'2', 'defaultValidate':'integer,numberLimit!1!5', 'defaultErrormsg':'输入1到5之间的整数', 'skillShow':'together', //spread 'skillLevelOption':['爱好','达人','专业','专家','大神'] }; Rule.prototype.bind = function(sets) { for (x in sets) this.setting[x] = sets[x]; }; Rule.prototype.addExistTag = function() { var obj = this; var modalctrl = $("#" + obj.setting.modalid); var contentDiv = $("#" + obj.setting.modalid + "-content"); var jsonurl = obj.setting.defaultJsonUrl; if (contentDiv.html() == "") { $.getJSON(jsonurl,function(data){ obj.setting.tags = data; for(var i = 0;i<obj.setting.tags.length; i++) { var tag = obj.setting.tags[i]; var type = tag.type; switch(type){ case "userSkill": var show = obj.setting.skillShow; if(show == 'together'){ var html = '<div class="am-btn-group"><button class="am-btn am-btn-secondary">'+ tag.name +'</button>' +'<div class="am-dropdown am-dropdown-up" data-am-dropdown><button class="am-btn am-btn-secondary am-dropdown-toggle ym-skill-toggle" data-am-dropdown-toggle><span class="am-icon-caret-up"></span></button>' +' <ul class="am-dropdown-content" style="min-width:100px !important;padding: 0;overflow-y:auto;max-height:150px;">'; // contentDiv.append(html); //onclick="addSkill(this,'+j+',\''+tag.key[j]+'\')" for(var j in tag.key){ html += '<li id="tag_' + j + '_addBtn" onclick="addSkill(this,'+j+',\''+tag.key[j]+'\',\''+type+'\')" class="am-btn am-btn-primary" style="width:100%;">'+ tag.key[j] +'</li>'; } html += '</ul></div></div>'; contentDiv.append(html); $('.ym-skill-toggle').on('click',function(e){ if($(this).next('ul').css('display')=='none'){ $(this).next('ul').css('display','block'); }else{ $(this).next('ul').css('display','none'); } e.stopPropagation();//阻止冒泡 }); $(document).on('click',function(){ $('.ym-skill-toggle').next('ul').css('display','none'); }); continue; }else{ for(var j in tag.key) { contentDiv.append('<label id ="tag_' + j + '_addBtn" class="am-btn am-btn-warning am-radius" onclick="addSkill(this,'+j+',\''+tag.key[j]+'\',\''+type+'\')" style="margin:5px 5px;font-size: 1.2rem;padding: 0.5rem 0rem 0.5rem 0rem;width: 5.2rem;">' + tag.key[j] + '</label>'); } } } } var arr = obj.setting.defaultValue.split(';'); // console.log(arr); for(var i in arr){ if(arr[i].length > 0){ arr1 = arr[i].split('_'); $btn = $('#tag_' + arr1[1] + '_addBtn'); $btn.attr('disabled', 'disabled'); $btn.css('background-color', '#a5a5a5'); $btn.css('border-color', '#a5a5a5'); obj.addSkillTag(arr1[1],arr1[3],'userSkill',arr1[2]); } } }); } } Rule.prototype.addSkill = function() { var obj = this; var modalctrl = $("#" + obj.setting.modalid); var contentDiv = $("#" + obj.setting.modalid + "-content"); var jsonurl = obj.setting.defaultJsonUrl; modalctrl.modal(); if (contentDiv.html() == "") { $.getJSON(jsonurl,function(data){ obj.setting.tags = data; for(var i = 0;i<obj.setting.tags.length; i++) { var tag = obj.setting.tags[i]; var type = tag.type; switch(type){ case "onlyFriend": contentDiv.append('<label id ="tag_' + tag.key + '_addBtn" class="am-btn am-btn-primary am-radius" style="margin:2px 3px">' + tag.name + '</label>'); var btn = $('#tag_' + tag.key + '_addBtn'); btn.on('click', function() { var id = this.id.split('_')[1]; obj.addNewTag(id); $(this).attr('disabled', 'disabled'); modalctrl.modal('close'); }); continue; case "userSkill": var show = obj.setting.skillShow; if(show == 'together'){ var html = '<div class="am-btn-group"><button class="am-btn am-btn-secondary">'+ tag.name +'</button>' +'<div class="am-dropdown am-dropdown-up" data-am-dropdown><button class="am-btn am-btn-secondary am-dropdown-toggle ym-skill-toggle" onclick="toggleUp(this)" data-am-dropdown-toggle><span class="am-icon-caret-up"></span></button>' +' <ul class="am-dropdown-content" style="min-width:100px !important;padding: 0;overflow-y:auto;max-height:150px;">'; for(var j in tag.key){ html += '<li id="tag_' + j + '_addBtn" onclick="addSkill(this,'+j+',\''+tag.key[j]+'\')" class="am-btn am-btn-primary" style="width:100%;">'+ tag.key[j] +'</li>'; var btn = $('#tag_' + j + '_addBtn'); btn.on('click', function() { var id = this.id.split('_')[1]; obj.addNewTag(id); $(this).attr('disabled', 'disabled'); modalctrl.modal('close'); }); } html += '</ul></div></div>'; contentDiv.append(html); continue; }else{ } } } }); } } Rule.prototype.click = function() { var obj = this; var modalctrl = $("#" + obj.setting.modalid); var contentDiv = $("#" + obj.setting.modalid + "-content"); var jsonurl = obj.setting.defaultJsonUrl; modalctrl.modal(); if (contentDiv.html() == "") { $.getJSON(jsonurl,function(data){ obj.setting.tags = data; for(var i = 0;i<obj.setting.tags.length; i++) { var tag = obj.setting.tags[i]; var type = tag.type; switch(type){ case "onlyFriend": contentDiv.append('<label id ="tag_' + tag.key + '_addBtn" class="am-btn am-btn-primary am-radius" style="margin:2px 3px">' + tag.name + '</label>'); var btn = $('#tag_' + tag.key + '_addBtn'); btn.on('click', function() { var id = this.id.split('_')[1]; obj.addNewTag(id); $(this).attr('disabled', 'disabled'); modalctrl.modal('close'); }); continue; case "userSkill": var show = obj.setting.skillShow; if(show == 'together'){ var html = '<div class="am-btn-group"><button class="am-btn am-btn-secondary">'+ tag.name +'</button>' +'<div class="am-dropdown am-dropdown-up" data-am-dropdown><button class="am-btn am-btn-secondary am-dropdown-toggle ym-skill-toggle" data-am-dropdown-toggle><span class="am-icon-caret-up"></span></button>' +' <ul class="am-dropdown-content" style="min-width:100px !important;padding: 0;overflow-y:auto;max-height:150px;">'; // contentDiv.append(html); //onclick="addSkill(this,'+j+',\''+tag.key[j]+'\')" for(var j in tag.key){ html += '<li id="tag_' + j + '_addBtn" onclick="addSkill(this,'+j+',\''+tag.key[j]+'\',\''+type+'\')" class="am-btn am-btn-primary" style="width:100%;">'+ tag.key[j] +'</li>'; } html += '</ul></div></div>'; contentDiv.append(html); $('.ym-skill-toggle').on('click',function(e){ if($(this).next('ul').css('display')=='none'){ $(this).next('ul').css('display','block'); }else{ $(this).next('ul').css('display','none'); } e.stopPropagation();//阻止冒泡 }); $(document).on('click',function(){ $('.ym-skill-toggle').next('ul').css('display','none'); }); continue; }else{ for(var j in tag.key) { contentDiv.append('<label id ="tag_' + j + '_addBtn" class="am-btn am-btn-warning am-radius" onclick="addSkill(this,'+j+',\''+tag.key[j]+'\',\''+type+'\')" style="margin:5px 5px;font-size: 1.2rem;padding: 0.5rem 0rem 0.5rem 0rem;width: 5.2rem;">' + tag.key[j] + '</label>'); } var arr = obj.setting.defaultValue.split(';'); for(var i in arr){ if(arr[i].length > 0){ arr1 = arr[i].split('_'); $btn = $('#tag_' + arr1[1] + '_addBtn'); $btn.css('background-color', '#a5a5a5'); $btn.css('border-color', '#a5a5a5'); $btn.attr('disabled', 'disabled').addClass('am-disabled'); obj.addSkillTag(arr1[1],arr1[3],'userSkill',arr1[2]); } } } } } }); } } function addSkill(o,id,name,type){ _ym_rule.addSkillTag(id,name,type); $(o).css('background-color', '#a5a5a5'); $(o).css('border-color', '#a5a5a5'); $(o).attr('disabled', 'disabled').addClass('am-disabled'); $("#" + _ym_rule.setting.modalid).modal('close'); } Rule.prototype.addNewTag = function(id) { var set = this.findSet(id,id); var str = '<label class="am-btn am-btn-warning am-round" style = "font-size:1.1rem;padding:0.2rem 0.5rem; margin:0.5rem 0.2rem">' + set.name + '<input type="hidden" id="rule_' + id + '" name="rule_' + id + '" value = "'+set.key+'" />' + '</label>'; var obj = this; $("#"+this.setting.container).append(str); $("#rule_"+id).parent().on('click', obj.getDeleteConfirm(id,id)); var v = $("#"+this.setting.tagsList).val(); $("#"+this.setting.tagsList).val(v+";"+set.type+'_'+id); } Rule.prototype.addSkillTag = function(id,name,type,existLevel) { var set = this.findSet(id,type); if(!existLevel){ existLevel = 1; } var max = this.setting.maxSkillLevel*1; var skillLevelOption = this.setting.skillLevelOption; var select = '',option = ''; for(i=1;i<=max;i++){ if(existLevel == i){ select = "selected"; }else{ select = ''; } option +='<option value="'+i+'" '+select+'>'+skillLevelOption[i-1]+'</option>'; } var str = '<label style="display:inline-block;width:100%;"><label class="am-btn" style = "font-size:1.2rem;width: 6rem; margin-right: 1.5rem;color:#fff;background-color: #383838;border-radius: 2px;">' + name + '<input type="hidden" name="_skill_' + id + '" value = "'+id+'" id="_skill_' + id + '" />' + '</label>' + '<select class=" am-form-field ym-publish-field" style="display:inline-block;width:45%;padding:0 0.8rem;height:30px;font-size:1.2rem;color:#383838;border:#e2e2e2 0.1rem solid;border-radius: 2px;" id="rule_' + id + '" name="rule_' + id + '">' + option +'</select><label id="skill_'+id+'_del" class="am-btn am-btn-warning am-fr" style="font-size:1.2rem;padding-left: 1.5rem;padding-right: 1.5rem;border-radius: 0.2rem;"><span>移除</span></label></label>'; var obj = this; $("#"+this.setting.container).append(str); $("#skill_"+id+"_del span").parent().on('click', obj.getDeleteConfirm(id,type)); var v = $("#"+this.setting.tagsList).val(); $("#"+this.setting.tagsList).val(v+";"+type+'_'+id); } Rule.prototype.findSet = function(id) { for (var i = 0; i < this.setting.tags.length; i++) { if (this.setting.tags[i].type == id) return this.setting.tags[i]; } return null; } Rule.prototype.getDeleteConfirm = function(id,type) { var set = this.findSet(type); var obj = this; return function(){ $('#'+obj.setting.confirm+"-content").html('你确定要删除这个标签吗?'); $('#'+obj.setting.confirm+"-content").attr('tagId',id); $('#'+obj.setting.confirm).modal({'onConfirm':function(c){ var id = $('#'+obj.setting.confirm+"-content").attr('tagId'); $("#rule_"+id).parent().remove(); $("#tag_" + id + "_addBtn").removeAttr('disabled'); $("#tag_" + id + "_addBtn").removeClass('am-disabled'); $("#tag_" + id + "_addBtn").css('background-color', '#f37b1d'); $("#tag_" + id + "_addBtn").css('border-color', '#f37b1d'); var v = $("#"+obj.setting.tagsList).val(); $("#"+obj.setting.tagsList).val(v.replace(";"+type+'_'+id, "")); }}); }; } <reponame>donohutcheon/go-react<gh_stars>0 import { FETCHING, SUCCESS, ERROR } from "./actionTypes"; export const fetching = () => ({ type: FETCHING }); export const success = response => ({ type: SUCCESS, response }); export const error = response => ({ type: ERROR, response }); process.isTest = true; const assert = require('assert'); // Get config const {drive} = require('../configs/database'); require(`../models/${drive}/connect`); const Clients = require(`../models/${drive}/clients`); //Test data const dataTest = require('./data/clients'); describe('Test model clients', () => { before(async () => { await Clients.clear(); for(let client of dataTest.clients) await Clients.create(client); }); it('get All', async () => { let clients = await Clients.getAll(); assert.equal(clients.length, 3); }); it('get statsByWeekAgo', async () => { let result = await Clients.statsByWeekAgo(); assert.equal(result.stats[dataTest.oneDayAgo.byUtc().toStringByFormat('y-m-d')], 1); assert.equal(result.stats[dataTest.twoDayAgo.byUtc().toStringByFormat('y-m-d')], 2); }); }); import React from 'react'; import CanvasCore from '../../Components/CanvasCore' import {Stage,Layer,Rect} from 'react-konva'; import pubsub from 'pubsub-js' class BaseStage extends CanvasCore { static propTypes = { children: React.PropTypes.node, }; constructor(props) { super(props); this.state = { stageWidth: 0 } } //不用 componentWillMount() { } //组件加载完毕,如果是页面就是页面加载完毕 componentDidMount() { let stage = this.refs.compomentStage.getStage(); let currentContainer = stage.container(); //把当前页面dom节点大小传递过去 this.setState({ stageWidth: currentContainer.offsetWidth }) } //销毁 componentWillUnmount() { super.componentWillUnmount() } //不用 componentWillReceiveProps(nextProps) { } //drag事件 baseStageDrag(evt){ var shape = evt.target; let layer = shape.getLayer(); shape.stopDrag(); // 还原坐标的位置 let config = { x: 0, y: 0, } let originalX = shape.getAttr('originalX'); let originalY = shape.getAttr('originalY'); if(originalX && originalY){ config = { x: originalX, y: originalY, } } shape.setAttrs(config) layer.draw(); let shapeType = shape.getAttr('shapeType') pubsub.publish(`anchorGroup.${shapeType}`,evt) } render() { return ( <Stage ref='compomentStage' width={this.state.stageWidth} height={this.state.stageWidth} onDragstart={this.baseStageDrag}> <Layer ref='compomentLayer'> {React.cloneElement(this.props.children, {config: { stageWidth: this.state.stageWidth, }})} </Layer> </Stage> ) } } export default BaseStage; import propertyValueConverters from './property-value-converters' export * from './utils' export {propertyValueConverters} var express = require('express'); var router = express.Router(); const Firebase = require('firebase'); // GET - Register router.get('/register', function(req, res, next) { res.render('users/register'); }); // POST - Register router.post('/register', function(req, res, next) { var username = req.body.username; var email = req.body.email; var password = <PASSWORD>; var confirm_password = req.body.confirm_password; var favourite_game = req.body.favourite_game; // Validation req.checkBody('username', 'Username is required').notEmpty(); req.checkBody('email', 'Email is required').notEmpty(); req.checkBody('email', 'Email must be valid.').isEmail(); req.checkBody('password', '<PASSWORD>').notEmpty(); req.checkBody('confirm_password', 'Passwords must match.').equals(req.body.password); var errors = req.validationErrors(); if(errors){ res.render('users/register', {errors: errors}); }else{ Firebase.auth().createUserWithEmailAndPassword(email, password).then( function(data){ var user = { uid: data.uid, email: email, username: username, favourite_game: favourite_game } var userRef = Firebase.database().ref('users'); userRef.push().set(user); req.flash("success_msg", "You are now registered and may login."); res.redirect('/games'); }, function(error) { console.log("ERROR WHILE REGISTERING USER: " + error); } ); } }); // GET - Login router.get('/login', function(req, res, next) { if(Firebase.auth().currentUser){ res.redirect('/games'); }else{ res.render('users/login'); } }); // GET - Logout router.get('/logout', function(req, res, next){ Firebase.auth().signOut() .then( function(){ req.flash("success_msg", "You are now logged out."); res.redirect('/users/login'); }, function(error){ req.flash("error_msg", "Error logging out, please try again."); res.redirect("/users/login"); } ) }); // POST - Login router.post('/login', function(req, res, next) { var email = req.body.email; var password = req.body.password; req.checkBody("email", "Email or username is required.").notEmpty(); req.checkBody("email", "Email must be valid.").isEmail(); req.checkBody("password", "<PASSWORD>.").notEmpty(); var errors = req.validationErrors(); if(errors){ res.render("/user/login", {errors:errors}); }else{ Firebase.auth().signInWithEmailAndPassword(email, password) .then( function(data){ console.log("LOGGED IN WITH UID: " + data.uid); req.flash("success_msg", "You are now logged in."); res.redirect('/games'); }, function(error){ console.log("ERROR WHILE LOGGING IN! :" + error); req.flash("error_msg", "Login failed - wrong username or password."); res.redirect("/users/login"); } ) } }); module.exports = router; <reponame>lzd358194530/vue-fabric-drawing<filename>src/router/index.js import Vue from 'vue' import Router from 'vue-router' import Sketchpad from '@/components/Sketchpad.vue' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Sketchpad', component: Sketchpad } ] }) <filename>node_modules/react-query/es/react/setLogger.js import { setLogger } from '../core'; import { logger } from './logger'; if (logger) { setLogger(logger); }<reponame>KPO-2020-2021/zad5_2-AdamDomachowski var searchData= [ ['ymax_342',['Ymax',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#ac54e4e7448ce3bd324efdc94a999f535',1,'PzG::LaczeDoGNUPlota']]], ['ymin_343',['Ymin',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a9352c0382bfaeaaba9f65399a7383164',1,'PzG::LaczeDoGNUPlota']]] ]; import { Link, routes } from '@redwoodjs/router' const DefaultLayout = ({ children }) => { return ( <> <header> <h1>Code Playground</h1> <nav> <ul> <li> <Link to={routes.home()}>Home</Link> </li> <li> <Link to={routes.three()}>Three</Link> </li> <li> <Link to={routes.threeFiber()}>Three Fiber</Link> </li> </ul> </nav> </header> <main>{children}</main> </> ) } export default DefaultLayout /** * Animate function calls 60 moves in a second * @module Util/Animate * @param {number} options.from - Start value * @param {number} options.to - End value * @param {number} options.duration - Animate duration * @param {function} options.callback - Callback for each move */ export default function animate({from, to, duration, callback}) { const animate = () => { // Calcualte stop value const stop = from + step * currentFrame; // Draw a segment callback({from, to: stop}); // Auto play frame currentFrame += 1; currentFrame <= totalFrames && window.requestAnimationFrame(animate); }; const totalFrames = Math.floor(duration / 1000 * 60); // Must ensure 60fps const step = (to - from) / totalFrames; let currentFrame = 1; // start from 1 window.requestAnimationFrame(animate); } /** * Shows how the Slider control can be used in a form and participate like a form field. */ Ext.define('KitchenSink.view.form.SliderField', { extend: 'Ext.form.Panel', xtype: 'slider-field', controller: 'slider-field', requires: [ 'Ext.slider.Single' ], //<example> otherContent: [{ type: 'Controller', path: 'classic/samples/view/form/SliderFieldController.js' }], profiles: { classic: { labelWidth: 125 }, neptune: { labelWidth: 125 }, 'neptune-touch': { labelWidth: 150 } }, //</example> title: 'Sound Settings', width: 400, bodyPadding: 10, msgTpl: 'Sounds Effects: <b>{fx}%</b><br />' + 'Ambient Sounds: <b>{ambient}%</b><br />' + 'Interface Sounds: <b>{iface}%</b>', defaults: { labelWidth: '${labelWidth}', anchor: '95%', tipText: 'tipText' }, defaultType: 'slider', items: [{ fieldLabel: 'Sound Effects', value: 50, name: 'fx' }, { fieldLabel: 'Ambient Sounds', value: 80, name: 'ambient' }, { fieldLabel: 'Interface Sounds', value: 25, name: 'iface' }], bbar: [{ text: 'Max All', handler: 'onMaxAllClick' }, '->', { text: 'Save', handler: 'onSaveClick' }, { text: 'Reset', handler: 'onResetClick' }] }); import { route, meta } from '@/helpers/routes' import View from './form/form' import Search from './search/search' export default [ route('index', '/index', Search, meta('Lista de escolas', true, 'admin')), route('view', '/view', View, meta('Adicionar escola', true, 'admin')) ] <gh_stars>0 let hasnewgamestarted = 0; let startnewgamenumberanimationobject = { bignumberdigits: 0, bignumbertens: 0, bignumberhundreds: 0, bignumberkilos: 0, bignumberkilogain: 1, bignumbertkilos: 0, bignumbertkilogain: 1, bignumberhkilos: 0, bignumberhkilogain: 1, bignumbermils: 0, bignumbertmils: 0, bignumberhmils: 0, bignumberbils: 0, bignumbertbils: 0, bignumberhbils: 0, bignumbertrils: 0, timedelay: 500, finished: 0, } var savestate = { hasnewgamestarted: 0, texttutorialfinished: 0, } var tutorialspeech = [ 'See that button you just clicked? That is an orange button. Orange buttons are for dialogue and communication! When you want to talk to someone, you use the orange button! How about some practice? How are you?', 'Great! That is the power of the orange button. Now look at my text. See this font? It is my voice. Every character has a different font, or voice. It is just a heads up for when you meet someone new. Hey, how about we go into the game itself?', 'I am sorry to hear that. Anyway, that is the power of the orange button. Now look at my text. See this font? It is my voice. Every character has a different font, or voice. It is just a heads up for when you meet someone new. Hey, how about we go into the game itself?' ]; var typewriter = { speed: 100, i: 0, finished: 0, tutorial: 0, tutorialstage: 0, } function O (i) { return document.getElementById(i); } function S (i) { return O(i).style; } $(document).ready(function() { if (localStorage.getItem('hasnewgamestarted') == 1) { O('newgame').innerHTML = 'Resume game'; S('newgame').right = '55px'; if (localStorage.getItem('texttutorialfinished') == 1) { $("#newgame").attr("onclick", "drawthomasbedroommap()"); } else { $("#newgame").attr("onclick", "startnewgameimageanimation()"); } } }); var optionsmodal = document.getElementById('optionsmodal'); var optionsbutton = document.getElementById('optionsbutton'); optionsbutton.onclick = function () { optionsmodal.style.display = "block"; } window.onclick = function(event) { if (event.target == optionsmodal) { optionsmodal.style.display = "none"; O('optionslogtext').innerHTML = ''; } } var resetgame = document.getElementById('resetgame'); resetgame.onclick = function () { var resetgame1 = confirm("Are you sure you want to clear all you saves?"); if (resetgame1 == true) { localStorage.clear(); O('optionslogtext').innerHTML = 'Save cleared!' } else { O('optionslogtext').innerHTML = 'Save not cleared'} } function typeWriter(a, b) { if (undefined !== b && b.length) { b = b.toString(); if (b === 'escape') { document.getElementById(a).innerHTML = ''; typewriter.i = 0; return; } if (typewriter.i < b.length) { document.getElementById(a).innerHTML += b.charAt(typewriter.i); typewriter.i++; setTimeout(typeWriter, typewriter.speed, a, b); } if (typewriter.i >= b.length) { tutorialswitch(); } } } function tutorialswitch () { typewriter.finished = 1; if (typewriter.tutorial === 0) { if (typewriter.tutorialstage >= 2) { answer3buttonappear(); } if (typewriter.tutorialstage == 1) { answer1buttonappear(); } else { answer0buttonappear(); } } } function startnewgame () { if (hasnewgamestarted === 0) { hasnewgamestarted = 1; O('header').style.display = 'none'; O('titlescreen').style.display = 'none'; O('titlesetdateanimation').style.display = 'flex'; O('titlesetdateanimationbox').style.display = 'flex'; setTimeout(startnewgamenumberanimation, 1000); } } function startnewgamenumberanimation () { setTimeout(startnewgamenumberanimationloop, startnewgamenumberanimationobject.timedelay); } function startnewgamenumberanimationloop () { if (startnewgamenumberanimationobject.bignumberdigits != 9 && startnewgamenumberanimationobject.timedelay > 1) { startnewgamenumberanimationobject.bignumberdigits++; O('titlesetdateanimationsecond2').innerHTML = startnewgamenumberanimationobject.bignumberdigits; } else if (startnewgamenumberanimationobject.timedelay != 1) { if (startnewgamenumberanimationobject.bignumbertens != 9) { startnewgamenumberanimationobject.bignumberdigits = 0; startnewgamenumberanimationobject.bignumbertens++; O('titlesetdateanimationsecond2').innerHTML = startnewgamenumberanimationobject.bignumberdigits; O('titlesetdateanimationsecond1').innerHTML = startnewgamenumberanimationobject.bignumbertens; } else { if (startnewgamenumberanimationobject.bignumberhundreds != 9) { startnewgamenumberanimationobject.bignumberdigits = 0; startnewgamenumberanimationobject.bignumbertens = 0; startnewgamenumberanimationobject.bignumberhundreds++; O('titlesetdateanimationsecond2').innerHTML = startnewgamenumberanimationobject.bignumberdigits; O('titlesetdateanimationsecond1').innerHTML = startnewgamenumberanimationobject.bignumbertens; O('titlesetdateanimationminute2').innerHTML = startnewgamenumberanimationobject.bignumberhundreds; } else { O('titlesetdateanimationheader').innerHTML = 'Initializing other techy stuff'; if (startnewgamenumberanimationobject.bignumberkilos != 9) { startnewgamenumberanimationobject.bignumberdigits = 0; startnewgamenumberanimationobject.bignumbertens = 0; startnewgamenumberanimationobject.bignumberhundreds = 0; startnewgamenumberanimationobject.bignumberkilos += startnewgamenumberanimationobject.bignumberkilogain; O('titlesetdateanimationsecond2').innerHTML = startnewgamenumberanimationobject.bignumberdigits; O('titlesetdateanimationsecond1').innerHTML = startnewgamenumberanimationobject.bignumbertens; O('titlesetdateanimationminute2').innerHTML = startnewgamenumberanimationobject.bignumberhundreds; O('titlesetdateanimationminute1').innerHTML = startnewgamenumberanimationobject.bignumberkilos; } else { if (startnewgamenumberanimationobject.bignumbertrils < 9) { startnewgameanimationloopspeedup2(); } } } } } else { startnewgameanimationloopspeedup(); } if (startnewgamenumberanimationobject.timedelay > 1) { startnewgamenumberanimationobject.timedelay -= 10; } if (startnewgamenumberanimationobject.finished != 1) { startnewgamenumberanimation(); } } function startnewgameanimationloopspeedup () { startnewgamenumberanimationobject.bignumberdigits++; startnewgamenumberanimationobject.bignumbertens++; startnewgamenumberanimationobject.bignumberhundreds++; O('titlesetdateanimationsecond2').innerHTML = startnewgamenumberanimationobject.bignumberdigits; O('titlesetdateanimationsecond1').innerHTML = startnewgamenumberanimationobject.bignumbertens; O('titlesetdateanimationminute2').innerHTML = startnewgamenumberanimationobject.bignumberhundreds; O('titlesetdateanimationminute1').innerHTML = startnewgamenumberanimationobject.bignumberkilos; O('titlesetdateanimationhour1').innerHTML = startnewgamenumberanimationobject.bignumbertkilos; O('titlesetdateanimationyear4').innerHTML = startnewgamenumberanimationobject.bignumberhkilos; if (startnewgamenumberanimationobject.finished != 1) { setTimeout(startnewgameanimationloopspeedup, 1); } setTimeout(startnewgameanimationloopspeedup3, 100); } function startnewgameanimationloopspeedup2 () { O('titlesetdateanimationheader').innerHTML = 'Finishing game initialization' if (startnewgamenumberanimationobject.bignumbertrils < 9) { startnewgamenumberanimationobject.bignumberkilos++; startnewgamenumberanimationobject.bignumbertkilos++; O('titlesetdateanimationminute1').innerHTML = startnewgamenumberanimationobject.bignumberkilos; O('titlesetdateanimationhour1').innerHTML = startnewgamenumberanimationobject.bignumbertkilos; setTimeout(startnewgameanimationloopspeedup, 1); setTimeout(startnewgameanimationloopspeedup3, 10); } } function startnewgameanimationloopspeedup3 () { if (startnewgamenumberanimationobject.bignumbertrils < 9) { startnewgamenumberanimationobject.bignumberhkilos++; startnewgamenumberanimationobject.bignumbermils++; O('titlesetdateanimationyear4').innerHTML = startnewgamenumberanimationobject.bignumberhkilos; O('titlesetdateanimationyear3').innerHTML = startnewgamenumberanimationobject.bignumbermils; setTimeout(startnewgameanimationloopspeedup4, 10); } } function startnewgameanimationloopspeedup4 () { if (startnewgamenumberanimationobject.bignumbertrils < 9) { startnewgamenumberanimationobject.bignumbertmils++; startnewgamenumberanimationobject.bignumberhmils++; O('titlesetdateanimationyear2').innerHTML = startnewgamenumberanimationobject.bignumbertmils; O('titlesetdateanimationyear1').innerHTML = startnewgamenumberanimationobject.bignumberhmils; setTimeout(startnewgameanimationloopspeedup5, 10); } } function startnewgameanimationloopspeedup5 () { if (startnewgamenumberanimationobject.bignumbertrils < 9) { startnewgamenumberanimationobject.bignumberbils++; startnewgamenumberanimationobject.bignumbertbils++; O('titlesetdateanimationmonth2').innerHTML = startnewgamenumberanimationobject.bignumberbils; O('titlesetdateanimationmonth1').innerHTML = startnewgamenumberanimationobject.bignumbertbils; setTimeout(startnewgameanimationloopspeedup6, 10); } } function startnewgameanimationloopspeedup6 () { if (startnewgamenumberanimationobject.bignumbertrils < 9) { startnewgamenumberanimationobject.bignumberhbils++; startnewgamenumberanimationobject.bignumbertrils++; O('titlesetdateanimationday2').innerHTML = startnewgamenumberanimationobject.bignumberhbils; O('titlesetdateanimationday1').innerHTML = startnewgamenumberanimationobject.bignumbertrils; } if (startnewgamenumberanimationobject.bignumbertrils >= 9) { startnewgamenumberanimationobject.bignumberdigits = 9; startnewgamenumberanimationobject.bignumbertens = 9; startnewgamenumberanimationobject.bignumberhundreds = 9; startnewgamenumberanimationobject.bignumberkilos = 9; startnewgamenumberanimationobject.bignumbertkilos = 9; startnewgamenumberanimationobject.bignumberhkilos = 9; startnewgamenumberanimationobject.bignumbermils = 9; startnewgamenumberanimationobject.bignumbertmils = 9; startnewgamenumberanimationobject.bignumberhmils = 9; startnewgamenumberanimationobject.bignumberbils = 9; startnewgamenumberanimationobject.bignumbertbils = 9; startnewgamenumberanimationobject.bignumberhbils = 9; startnewgamenumberanimationobject.bignumbertrils = 9; O('titlesetdateanimationsecond2').innerHTML = startnewgamenumberanimationobject.bignumberdigits; O('titlesetdateanimationsecond1').innerHTML = startnewgamenumberanimationobject.bignumbertens; O('titlesetdateanimationminute2').innerHTML = startnewgamenumberanimationobject.bignumberhundreds; O('titlesetdateanimationminute1').innerHTML = startnewgamenumberanimationobject.bignumberkilos; O('titlesetdateanimationhour1').innerHTML = startnewgamenumberanimationobject.bignumbertkilos; O('titlesetdateanimationyear4').innerHTML = startnewgamenumberanimationobject.bignumberhkilos; O('titlesetdateanimationyear3').innerHTML = startnewgamenumberanimationobject.bignumbermils; O('titlesetdateanimationyear2').innerHTML = startnewgamenumberanimationobject.bignumbertmils; O('titlesetdateanimationyear1').innerHTML = startnewgamenumberanimationobject.bignumberhmils; O('titlesetdateanimationmonth2').innerHTML = startnewgamenumberanimationobject.bignumberbils; O('titlesetdateanimationmonth1').innerHTML = startnewgamenumberanimationobject.bignumbertbils; O('titlesetdateanimationday2').innerHTML = startnewgamenumberanimationobject.bignumberhbils; O('titlesetdateanimationday1').innerHTML = startnewgamenumberanimationobject.bignumbertrils; startnewgamenumberanimationobject.finished = 1; setTimeout(startnewgamenumberanimationdecrement, 1000); O('titlesetdateanimationheader').innerHTML = 'Setting date and time'; } } function startnewgamenumberanimationdecrement () { if (startnewgamenumberanimationobject.bignumbertrils != 2) { startnewgamenumberanimationobject.bignumbertrils--; O('titlesetdateanimationday1').innerHTML = startnewgamenumberanimationobject.bignumbertrils; } if (startnewgamenumberanimationobject.bignumberhbils != 1) { startnewgamenumberanimationobject.bignumberhbils--; O('titlesetdateanimationday2').innerHTML = startnewgamenumberanimationobject.bignumberhbils; } if (startnewgamenumberanimationobject.bignumbertrils != 2 || startnewgamenumberanimationobject.bignumberhbils != 1) { setTimeout(startnewgamenumberanimationdecrement, 100); } if (startnewgamenumberanimationobject.bignumbertrils === 2 && startnewgamenumberanimationobject.bignumberhbils === 1) { startnewgamenumberanimationdecrement2(); } } function startnewgamenumberanimationdecrement2 () { if (startnewgamenumberanimationobject.bignumbertbils != 0) { startnewgamenumberanimationobject.bignumbertbils--; O('titlesetdateanimationmonth1').innerHTML = startnewgamenumberanimationobject.bignumbertbils; } if (startnewgamenumberanimationobject.bignumberbils != 4) { startnewgamenumberanimationobject.bignumberbils--; O('titlesetdateanimationmonth2').innerHTML = startnewgamenumberanimationobject.bignumberbils; } if (startnewgamenumberanimationobject.bignumbertbils != 0 || startnewgamenumberanimationobject.bignumberbils != 4) { setTimeout(startnewgamenumberanimationdecrement2, 100); } if (startnewgamenumberanimationobject.bignumbertbils === 0 && startnewgamenumberanimationobject.bignumberbils === 4) { startnewgamenumberanimationdecrement3(); } } function startnewgamenumberanimationdecrement3 () { if (startnewgamenumberanimationobject.bignumberhmils != 2) { startnewgamenumberanimationobject.bignumberhmils--; O('titlesetdateanimationyear1').innerHTML = startnewgamenumberanimationobject.bignumberhmils; } if (startnewgamenumberanimationobject.bignumbertmils != 1) { startnewgamenumberanimationobject.bignumbertmils--; O('titlesetdateanimationyear2').innerHTML = startnewgamenumberanimationobject.bignumbertmils; } if (startnewgamenumberanimationobject.bignumberhmils != 2 || startnewgamenumberanimationobject.bignumbertmils != 1) { setTimeout(startnewgamenumberanimationdecrement3, 100); } if (startnewgamenumberanimationobject.bignumberhmils === 2 && startnewgamenumberanimationobject.bignumbertmils === 1) { startnewgamenumberanimationdecrement4(); } } function startnewgamenumberanimationdecrement4 () { if (startnewgamenumberanimationobject.bignumbermils != 0) { startnewgamenumberanimationobject.bignumbermils--; O('titlesetdateanimationyear3').innerHTML = startnewgamenumberanimationobject.bignumbermils; } if (startnewgamenumberanimationobject.bignumberhkilos != 3) { startnewgamenumberanimationobject.bignumberhkilos--; O('titlesetdateanimationyear4').innerHTML = startnewgamenumberanimationobject.bignumberhkilos; } if (startnewgamenumberanimationobject.bignumbermils != 0 || startnewgamenumberanimationobject.bignumberhkilos != 3) { setTimeout(startnewgamenumberanimationdecrement4, 100); } if (startnewgamenumberanimationobject.bignumbermils === 0 && startnewgamenumberanimationobject.bignumberhkilos === 3) { startnewgamenumberanimationdecrement5(); } } function startnewgamenumberanimationdecrement5 () { if (startnewgamenumberanimationobject.bignumbertkilos != 5) { startnewgamenumberanimationobject.bignumbertkilos--; O('titlesetdateanimationhour1').innerHTML = startnewgamenumberanimationobject.bignumbertkilos; if (startnewgamenumberanimationobject.bignumbertkilos != 5) { setTimeout(startnewgamenumberanimationdecrement5, 100); } } if (startnewgamenumberanimationobject.bignumbertkilos === 5) { startnewgamenumberanimationdecrement6(); } } function startnewgamenumberanimationdecrement6 () { if (startnewgamenumberanimationobject.bignumberkilos != 3) { startnewgamenumberanimationobject.bignumberkilos--; O('titlesetdateanimationminute1').innerHTML = startnewgamenumberanimationobject.bignumberkilos; } if (startnewgamenumberanimationobject.bignumberhundreds != 5) { startnewgamenumberanimationobject.bignumberhundreds--; O('titlesetdateanimationminute2').innerHTML = startnewgamenumberanimationobject.bignumberhundreds; } if (startnewgamenumberanimationobject.bignumberkilos != 3 || startnewgamenumberanimationobject.bignumberhundreds != 5) { setTimeout(startnewgamenumberanimationdecrement6, 100); } if (startnewgamenumberanimationobject.bignumberkilos === 3 && startnewgamenumberanimationobject.bignumberhundreds === 5) { startnewgamenumberanimationdecrement7(); } } function startnewgamenumberanimationdecrement7 () { if (startnewgamenumberanimationobject.bignumbertens != 1) { startnewgamenumberanimationobject.bignumbertens--; O('titlesetdateanimationsecond1').innerHTML = startnewgamenumberanimationobject.bignumbertens; } if (startnewgamenumberanimationobject.bignumberdigits != 3) { startnewgamenumberanimationobject.bignumberdigits--; O('titlesetdateanimationsecond2').innerHTML = startnewgamenumberanimationobject.bignumberdigits; } if (startnewgamenumberanimationobject.bignumbertens != 1 || startnewgamenumberanimationobject.bignumberdigits != 3) { setTimeout(startnewgamenumberanimationdecrement7, 100); } if (startnewgamenumberanimationobject.bignumbertens === 1 && startnewgamenumberanimationobject.bignumberdigits === 3) { setTimeout(startnewgameimageanimation, 2000); } } function startnewgameimageanimation () { O('titlescreen').style.display = 'none'; O('header').style.display = 'none'; O('titlesetdateanimationbox').style.display = 'none'; O('startnewgameimagebox').style.display = 'flex'; setTimeout(startTutorial, 5000); } function startTutorial () { hasnewgamestarted = 1; localStorage.setItem('hasnewgamestarted', 1); O('titlescreen').display = 'none'; O('startnewgameimagebox').style.display = 'none'; O('tutorialbox').style.display = 'inline-block'; O('tutorialboxwords').style.display = 'inline-block'; typeWriter('tutorialboxwords', 'Hello! I am Mown. I am your guide to this game! I will show the way around and help you throughout the game. Do you understand?') } function answer0buttonappear () { S('answer0').display = 'inline-block'; } function answer0tutorial () { if (typewriter.finished = 1) { typeWriter('tutorialboxwords', 'escape'); typeWriter('tutorialboxwords', tutorialspeech[0]); S('answer0').display = 'none'; typewriter.finished = 0; typewriter.tutorialstage = 1; typewriter.speed = 50; } } function answer1buttonappear () { S('answer1').display = 'inline-block'; S('answer2').display = 'inline-block'; } function answer1tutorial () { if (typewriter.finished = 1) { typeWriter('tutorialboxwords', 'escape'); typeWriter('tutorialboxwords', tutorialspeech[1]); S('answer1').display = 'none'; S('answer2').display = 'none'; typewriter.finished = 0; typewriter.tutorialstage = 2; } } function answer2tutorial () { if (typewriter.finished = 1) { typeWriter('tutorialboxwords', 'escape'); typeWriter('tutorialboxwords', tutorialspeech[2]); S('answer1').display = 'none'; S('answer2').display = 'none'; typewriter.finished = 0; typewriter.tutorialstage = 2; } } function answer3buttonappear () { S('answer3').display = 'inline-block'; } function answer3tutorial () { if (typewriter.finished = 1) { typeWriter('tutorialboxwords', 'escape'); S('tutorialbox').display = 'none'; S('maparea').display = 'inline-block'; S('status').display = 'inline-block'; drawthomasbedroommap(); } } <gh_stars>0 import { savedData } from "./SavedData.js"; class ToDo_List { isShowPopup = false; constructor() { this.toDoListSelectors(); } toDoListSelectors() { this.inputField = document.querySelector(".taskListInput"); } setTask(data) { const allTasks = savedData.getTasks(); const newTask = this.getTaskFormat(data); const tasks = [...allTasks, newTask]; savedData.setTasks(tasks); } getTaskFormat({ id, title, createAt, expireAt } = data) { const task = { id: id || Date.now(), settled: false, title, createDate: createAt, expireDate: expireAt }; return task; } getDate(createAtDate, expireAtDate = false) { let dateNumber = 10; let oneDay = 1; const date = new Date(createAtDate); let day = expireAtDate ? date.getDate() + oneDay : date.getDate(); let month = date.getMonth() + oneDay; let year = date.getFullYear(); if (day < dateNumber) { day = "0" + day; } if (month < dateNumber) { month = "0" + month; } if (year < dateNumber) { year = "0" + year; } return `${day}-${month}-${year}`; } } export default ToDo_List; <gh_stars>0 /* @jsx createElement */ import { createElement } from './lib/React.js'; import TodoApp from './components/TodoApp.js'; import TodoInput from './components/TodoInput.js'; import ToggleAll from './components/ToggleAll.js'; import TodoList from './components/TodoList.js'; import TodoCount from './components/TodoCount.js'; const App = () => { return ( <TodoApp> <ToggleAll /> <TodoInput /> <ToggleAll /> <TodoList /> <TodoCount /> </TodoApp> ); }; export default App; function findItem(menuItem, labels) { const target = labels[0]; const rest = labels.slice(1); const foundItem = menuItem.find(item => item.label === target); if (rest.length === 0) { return foundItem; } return findItem(foundItem.submenu.items, rest); } require('electron').ipcMain.on('SPECTRON_FAKE_MENU/SEND', (_e, labels) => { const item = findItem(require('electron').Menu.getApplicationMenu().items, labels); item.click(); }); <reponame>afkgaming089/aktheak<filename>main/deploy/plugins/internal/help.js const {getParam} = kb2abot.helpers; const genHelp = (prefix, found) => { const command = found.command; let replyMsg = `Lệnh: ${command.keywords[0]}\n`; replyMsg += `Tên: ${command.name}\n`; replyMsg += `Tên lớp: ${found.className}\n`; replyMsg += `Các từ khóa: ${command.keywords.join(', ')}\n`; replyMsg += `Mô tả: ${command.description}\n`; replyMsg += '-----\n'; replyMsg += `Hướng dẫn sử dụng:\n${prefix}${command.keywords[0]} ${command.guide}`; return replyMsg; }; module.exports = { keywords: ['help'], name: '<NAME>', description: 'Hiển thị hướng dẫn, danh sách các câu lệnh', guide: '[<tên command>]', childs: [], permission: { '*': '*' }, datastoreDesign: { account: { global: {}, local: {} }, thread: { global: {}, local: {} } }, async onLoad() {}, hookType: 'none', async onMessage(message, reply) {}, async onCall(message, reply) { const prefix = this.storage.thread.global.prefix; const keyword = getParam(message.body); if (keyword) { const found = kb2abot.pluginManager.findCommandsByKeyword(keyword); if (found.length == 0) { reply( `Không tìm thấy lệnh: "${keyword}"\n Vui lòng xem danh sách lệnh ở ${prefix}help!` ); } if (found.length == 1) { reply(genHelp(prefix, found[0])); } if (found.length > 1) { let replyMsg = `Có ${found.length} lệnh: \n`; for (const f of found) { replyMsg += genHelp(prefix, f) + '\n\n'; } reply(replyMsg); } } else { let replyMsg = `Hiện tại có tổng ${ kb2abot.pluginManager.getAllCommands().length } câu lệnh!\n\n`; for (let index = 0; index < kb2abot.pluginManager.items.length; index++) { const command = kb2abot.pluginManager.items[index]; const childKeywords = []; for (const child of command._.childs) { childKeywords.push(child.keywords[0]); } if (command.keywords[0] == 'internal') replyMsg = `🔳 𝐈𝐍𝐓𝐄𝐑𝐍𝐀𝐋: ${childKeywords.join(', ')}\n` + replyMsg; else replyMsg += `▫️ ${command.keywords[0]}(${ command.name }): ${childKeywords.join(', ')}\n`; } replyMsg += `\nNhớ ${prefix}help <tên câu lệnh> để xem chi tiết và hướng dẫn sử dụng lệnh nhé!\n`; replyMsg += 'Lưu ý: Trong vài help có bộ kí tự <,>,[,] ta không cần ghi vào và "[]" nghĩa là không bắt buộc.'; reply(replyMsg); } } }; import React from "react"; import { CodePane, Deck, Heading, Link, ListItem, List, Slide, Layout, Text, Fill, Image, BlockQuote, Quote, Cite } from "spectacle"; import images from '../../images'; export default ( <Slide bgColor="white" notes={` <ul> <li>Technology Consultancy & Solution Desing</li> </ul> `} > <Link alt="DataArt" href="http://dataart.com/" style={{ display: "block" }} target="__blank" > <Image width="70%" src={images.dataart.replace("/", "")} /> </Link> </Slide> ); import React, { useCallback, useEffect, useMemo, useState, } from 'react'; import PropTypes from 'prop-types'; import { useHistory } from 'react-router-dom'; import { useDispatch, useSelector } from 'react-redux'; import styled from 'styled-components'; import get from 'lodash.get'; import { reset } from 'store/reducers/upload'; import { uploadZabo } from 'store/reducers/zabo'; import { cropImage, dataURLToBlob, gridLayoutCompareFunction, imageFileGetWidthHeight, } from 'lib/utils'; const Loading = styled.div` margin: 24px 0; padding: 0 16px; width: 100%; display: flex; `; Loading.Active = styled.div` width: 0; border-top: 5px solid pink; `; Loading.Inactive = styled.div` flex: 1; border-top: 5px solid gainsboro; `; const UploadProcess = ({ children }) => { const dispatch = useDispatch (); const history = useHistory (); const info = useSelector (state => get (state, ['upload', 'info'])); const { title, description, hasSchedule, schedules, category, } = info; const imageFiles = useSelector (state => get (state, ['upload', 'images'])); const [progress, setProgress] = useState (0); const [error, setError] = useState (null); const upload = useCallback (async () => { // e.preventDefault (); const sortedImageFiles = imageFiles.slice (); sortedImageFiles.sort (gridLayoutCompareFunction); const { width, height } = await imageFileGetWidthHeight (sortedImageFiles[0]); let ratio = width / height; if (ratio > 2) ratio = 2; else if (ratio < 0.5) ratio = 0.5; const formData = new FormData (); const sources = await Promise.all (sortedImageFiles.map (file => cropImage (file, ratio))); sources.forEach (imageSrc => { const blob = dataURLToBlob (imageSrc); formData.append ('img', blob); }); formData.append ('title', title); formData.append ('description', description); if (hasSchedule) formData.append ('schedules', JSON.stringify (schedules)); const uCats = category.filter (c => c.clicked).map (t => t.name).join ('#'); formData.append ('category', uCats); // uploadZabo from this.props dispatch ( uploadZabo (formData, percentCompleted => setProgress (percentCompleted)), ) .then (zabo => { setProgress (0); history.push (`/zabo/${zabo._id}`); dispatch (reset ()); }) .catch (err => { console.error (err); setError (err); setProgress (0); alert (err.error); }); }, [info, imageFiles]); useEffect (() => { upload (); }, []); return React.Children.only (children (progress, error)); }; UploadProcess.propTypes = { children: PropTypes.func, }; UploadProcess.defaultProps = { }; export default UploadProcess; import './App.css'; import Header from './Header'; function App() { return ( // Podemos ajustar esses componentes através de suas propriedades e podemos passar propriedades para um componente filho, no nosso exemplo, o header esta sendo utilizado como filho de app, através de atributos, que seriam atributos do html e transformar nas propriedades dentro da nossa função que cria nosso objeto. // Com propriedades, iremos criar um header genérico que servirá pra qualquer aplicação e podemos transformar ele ainda mais genérico, podendo alterar a cor através das propriedades, podendo colocar vários links, então quanto mais genérico nós querermos pdemos fazer desde que seja preprarado pra isso. <Header name='José' links={['Sobre', 'Comprar', 'Contato']}> </Header> ) } export default App; <reponame>Janchorizo/exploreAT--1word4pics var vows = require("vows"), assert = require("assert"), crossfilter = require("../"); var suite = vows.describe("version"); suite.addBatch({ "version": { topic: crossfilter.version, "has the form major.minor.patch[-...]": function(version) { assert.match(version, /^[0-9]+\.[0-9]+\.[0-9]+-?[0-9A-Za-z-\.]./); } } }); suite.export(module); import toggle from './toggleattribute'; if (window.Element && !Element.prototype.toggleAttribute) { Element.prototype.toggleAttribute = toggle; } import React from 'react' import './Header.scss' import '../../styles.scss' import NavBar from '../Buttons/NavBar/NavBar' import logo from '../../assets/images/logo.png' //import imageHeader from '../../images/cabecera-estatica3.svg'; import imageHeader from '../../images/portada_0228.png'; import frameImage from '../../images/marco-verde.svg'; import backgroundImage from '../../images/imagen-fondo.svg'; import BurgerButtons from '../Buttons/BurgerButtons/BurgerButtons'; export default function Header() { return ( <> <header className="header"> {/*<img className="Header_logo" src={logo} alt="Logo" />*/} <div className="header-main-image"> <img src={imageHeader} max-width='800px' width='100%' ></img> {/*<img className="frame-image" src={frameImage}></img> <img className="background-image" src={backgroundImage} width="500" height="1000"></img> { <div className="frame-image"> <img src={backgroundImage}></img> </div> */} {/*<div className='text-header'>Únete a nosotros</div>*/} {/*<h1>ÚNETE A NOSOTROS</h1>*/} </div> </header> </> ) } <reponame>bruceLeeO/web-components (function(window) { var isExpressionInArrs = function(arrs,exp) { //console.log("arrs.... "+arrs); var arrLen = arrs.length; //console.log("exp.length: "+exp.length+" --- arrLen: "+arrLen); var frg = ""; var subStr = arrs; while (arrLen > 0) { for (var i = 0; i < arrLen; i++) { subStr = arrs.slice(i); //console.log("subStr is currently.... "+subStr); frg = subStr.slice(0,exp.length); //console.log("fragments.... "+frg); //console.log("exp.... "+exp); if (frg === exp) return true; } //console.log(arrLen); arrLen--; } return false; } var currdeg = 0; var nex = document.getElementsByClassName("foursided-carousel-next"); var pre = document.getElementsByClassName("foursided-carousel-prev"); var dots = document.getElementsByClassName("dot"); var dot1 = document.getElementById("dot1"); var dot2 = document.getElementById("dot2"); var dot3 = document.getElementById("dot3"); var dot4 = document.getElementById("dot4"); dot1.onclick = function(evt) { console.log("dot1 is pressed... "); for (var i = 0; i < dots.length; i++) { if (isExpressionInArrs(dots[i].className,"dot--active")) { if (dots[i].id === "dot2") { currdeg += 90; } if (dots[i].id === "dot3") { currdeg += 180; } if (dots[i].id === "dot4") { currdeg += 270; } //console.log("active is present .... in dots["+i+"].className "+dots[i].className); dots[i].className = dots[i].className.replace(" dot--active",""); //console.log("replace active in dots["+i+"].className "+dots[i].className); evt.currentTarget.className += " dot--active"; } } document.getElementById("foursided-carousel-axis").style.transform = "rotateY("+currdeg+"deg)"; } dot2.onclick = function(evt) { console.log("dot2 is pressed... "); for (var i = 0; i < dots.length; i++) { if (isExpressionInArrs(dots[i].className,"dot--active")) { if (dots[i].id === "dot1") { currdeg -= 90; } if (dots[i].id === "dot3") { currdeg += 90; } if (dots[i].id === "dot4") { currdeg += 180; } //console.log("active is present .... in dots["+i+"].className "+dots[i].className); dots[i].className = dots[i].className.replace(" dot--active",""); //console.log("replace active in dots["+i+"].className "+dots[i].className); evt.currentTarget.className += " dot--active"; } } document.getElementById("foursided-carousel-axis").style.transform = "rotateY("+currdeg+"deg)"; } dot3.onclick = function(evt) { console.log("dot3 is pressed... "); for (var i = 0; i < dots.length; i++) { if (isExpressionInArrs(dots[i].className,"dot--active")) { if (dots[i].id === "dot1") { currdeg -= 180; } if (dots[i].id === "dot2") { currdeg -= 90; } if (dots[i].id === "dot4") { currdeg += 90; } //console.log("active is present .... in dots["+i+"].className "+dots[i].className); dots[i].className = dots[i].className.replace(" dot--active",""); //console.log("replace active in dots["+i+"].className "+dots[i].className); evt.currentTarget.className += " dot--active"; } } document.getElementById("foursided-carousel-axis").style.transform = "rotateY("+currdeg+"deg)"; } dot4.onclick = function(evt) { console.log("dot4 is pressed... "); for (var i = 0; i < dots.length; i++) { if (isExpressionInArrs(dots[i].className,"dot--active")) { if (dots[i].id === "dot1") { currdeg -= 270; } if (dots[i].id === "dot2") { currdeg -= 180; } if (dots[i].id === "dot3") { currdeg -= 90; } //console.log("active is present .... in dots["+i+"].className "+dots[i].className); dots[i].className = dots[i].className.replace(" dot--active",""); //console.log("replace active in dots["+i+"].className "+dots[i].className); evt.currentTarget.className += " dot--active"; } } document.getElementById("foursided-carousel-axis").style.transform = "rotateY("+currdeg+"deg)"; } nex[0].onclick = function(evt) { console.log("n is clicked"); currdeg = currdeg - 90; console.log("currdeg: "+currdeg); document.getElementById("foursided-carousel-axis").style.transform = "rotateY("+currdeg+"deg)"; for (var i = 0; i < dots.length; i++) { if (isExpressionInArrs(dots[i].className,"dot--active")) { //console.log("active is present .... in dots["+i+"].className "+dots[i].className); dots[i].className =dots[i].className.replace(" dot--active",""); //console.log("replace active in dots["+i+"].className "+dots[i].className); if (dots[i].id === "dot1" || dots[i].id === "dot2" || dots[i].id === "dot3") { dots[i+1].className += " dot--active"; break; } else { if (dots[i].id === "dot4") { //console.log(" dot id is dot4............."); dots[0].className += " dot--active"; break; } } } } } pre[0].onclick = function(evt) { console.log("p is clicked"); currdeg = currdeg + 90; //console.log("currdeg: "+currdeg); document.getElementById("foursided-carousel-axis").style.transform = "rotateY("+currdeg+"deg)"; for (var i = 0; i < dots.length; i++) { if (isExpressionInArrs(dots[i].className,"dot--active")) { //console.log("active is present .... in dots["+i+"].className "+dots[i].className); dots[i].className =dots[i].className.replace(" dot--active",""); //console.log("replace active in dots["+i+"].className "+dots[i].className); if (dots[i].id === "dot4" || dots[i].id === "dot3" || dots[i].id === "dot2") { dots[i-1].className += " dot--active"; break; } else { if (dots[i].id === "dot1") { //console.log(" dot id is dot4............."); dots[3].className += " dot--active"; break; } } } } } //console.log("currdeg: "+currdeg); })(window);<reponame>CMBStudios/VueAdmin import Vue from 'vue' import { shallowMount, mount } from '@vue/test-utils' import BootstrapVue from 'bootstrap-vue' import Message from '@/views/apps/email/Message' Vue.use(BootstrapVue) describe('Message.vue', () => { it('has a name', () => { expect(Message.name).toMatch('message') }) it('is Vue instance', () => { const wrapper = shallowMount(Message) expect(wrapper.isVueInstance()).toBe(true) }) it('is Message', () => { const wrapper = shallowMount(Message) expect(wrapper.is(Message)).toBe(true) }) it('should render correct content', () => { const wrapper = mount(Message) expect(wrapper.find('div.email-app > nav > a.btn').text()).toMatch('New Email') }) test('renders correctly', () => { const wrapper = shallowMount(Message) expect(wrapper.element).toMatchSnapshot() }) }) //============================================================================= // Yanfly Engine Plugins - Event Encounter Aid // YEP_EventEncounterAid.js //============================================================================= var Imported = Imported || {}; Imported.YEP_EventEncounter = true; var Yanfly = Yanfly || {}; Yanfly.EEA = Yanfly.EEA || {}; //============================================================================= /*: * @plugindesc v1.00 事件遭遇助手 * @author Yanfly Engine Plugins * * @help * ============================================================================ * Introduction * ============================================================================ * * 对于想要设置明雷的玩家,你也许发现很难设置偷袭事件。这个插件通过不同情 * 况的脚步很方便的事件和玩家所处位置 * * ============================================================================ * Notetags * ============================================================================ * * 你可以把这些标签放在任何一个事件页顶部,这些事件将会开启事件遭遇的特殊 * 效果. * * 事件标签: * * <Encounter Lock> * <Encounter Direction Lock> * - 这将让事件不会马上面对玩家,而是检查面对方向 * * <Follower Touch> * <Follower Trigger> * -这将允许事件被跟随者触发 * * ============================================================================ * Event - Conditional Branch - Script Calls * ============================================================================ * * 你可以使用下面的脚本: * * Script Calls * * this.checkEventFacingPlayerFront() * - 事件在玩家前面 * * this.checkEventFacingPlayerBack() * - 事件在玩家后面 * * this.checkEventFacingPlayerSide() * - 事件在玩家侧面 * * this.checkPlayerFacingEventFront() * - 玩家在事件前面 * * this.checkPlayerFacingEventBack() * - 玩家在事件后面 * * this.checkPlayerFacingEventSide() * - 玩家在事件侧面 * 请确保拼写正确,他们是很严格的语句。 * Make sure these are spelled correctly. They are also case-sensitive. This * means that even if you were to misspell or put a single letter in the wrong * case, the effect will cease to work as this is code we're dealing with. */ //============================================================================= //============================================================================= // DataManager //============================================================================= DataManager.processEEANotetags1 = function(obj) { var notedata = obj.note.split(/[\r\n]+/); obj.encounterDirectionLock = false; obj.encounterFollowerTrigger = false; for (var i = 0; i < notedata.length; i++) { var line = notedata[i]; if (line.match(/<(?:ENCOUNTER LOCK|ENCOUNTER DIRECTION LOCK)>/i)) { obj.encounterDirectionLock = true; } if (line.match(/<(?:FOLLOWER TRIGGER|FOLLOWER TOUCH)>/i)) { obj.encounterFollowerTrigger = true; } } }; //============================================================================= // Game_CharacterBase //============================================================================= Game_CharacterBase.prototype.debugShowDirections = function(ev) { return; console.log(' This X: ' + this.x + ', This Y: ' + this.y); console.log('Event X: ' + ev.x + ', Event Y: ' + ev.y); }; Game_CharacterBase.prototype.isFacingTowards = function(ev) { switch (this.direction()) { case 1: // Down Left return [8, 9, 6].contains(ev.direction()); break; case 2: // Down return [7, 8, 9].contains(ev.direction()); break; case 3: // Down Right return [4, 7, 8].contains(ev.direction()); break; case 4: // Left return [9, 6, 3].contains(ev.direction()); break; case 6: // Right return [7, 4, 1].contains(ev.direction()); break; case 7: // Up Left return [2, 3, 6].contains(ev.direction()); break; case 8: // Up return [1, 2, 3].contains(ev.direction()); break; case 9: // Up Right return [4, 1, 2].contains(ev.direction()); break; } return false; }; Game_CharacterBase.prototype.isFacingAway = function(ev) { switch (this.direction()) { case 1: // Down Left return [4, 1, 2].contains(ev.direction()); break; case 2: // Down return [1, 2, 3].contains(ev.direction()); break; case 3: // Down Right return [2, 3, 6].contains(ev.direction()); break; case 4: // Left return [7, 4, 1].contains(ev.direction()); break; case 6: // Right return [9, 6, 3].contains(ev.direction()); break; case 7: // Up Left return [4, 7, 8].contains(ev.direction()); break; case 8: // Up return [7, 8, 9].contains(ev.direction()); break; case 9: // Up Right return [8, 9, 6].contains(ev.direction()); break; } return false; }; Game_CharacterBase.prototype.isFacingSideways = function(ev) { switch (this.direction()) { case 1: // Down Left return [4, 7, 8, 2, 3, 6].contains(ev.direction()); break; case 2: // Down return [7, 4, 1, 9, 6, 3].contains(ev.direction()); break; case 3: // Down Right return [4, 1, 2, 8, 9, 6].contains(ev.direction()); break; case 4: // Left return [7, 8, 9, 1, 2, 3].contains(ev.direction()); break; case 6: // Right return [7, 8, 9, 1, 2, 3].contains(ev.direction()); break; case 7: // Up Left return [4, 1, 2, 8, 9, 6].contains(ev.direction()); break; case 8: // Up return [7, 4, 1, 9, 6, 3].contains(ev.direction()); break; case 9: // Up Right return [4, 7, 8, 2, 3, 6].contains(ev.direction()); break; } return false; }; Game_CharacterBase.prototype.isPositionFrontOf = function(ev) { this.debugShowDirections(ev); switch (this.direction()) { case 1: // Down Left return ev.y > this.y; break; case 2: // Down return ev.y > this.y; break; case 3: // Down Right return ev.y > this.y; break; case 4: // Left return ev.x < this.x; break; case 6: // Right return ev.x > this.x; break; case 7: // Up Left return ev.y < this.y; break; case 8: // Up return ev.y < this.y; break; case 9: // Up Right return ev.y < this.y; break; } return false; }; Game_CharacterBase.prototype.isPositionBackOf = function(ev) { this.debugShowDirections(ev); switch (this.direction()) { case 1: // Down Left return ev.y < this.y; break; case 2: // Down return ev.y < this.y; break; case 3: // Down Right return ev.y < this.y; break; case 4: // Left return ev.x > this.x; break; case 6: // Right return ev.x < this.x; break; case 7: // Up Left return ev.y > this.y; break; case 8: // Up return ev.y > this.y; break; case 9: // Up Right return ev.y > this.y; break; } return false; }; Game_CharacterBase.prototype.isPositionSideOf = function(ev) { this.debugShowDirections(ev); switch (this.direction()) { case 1: // Down Left return (this.x < ev.x && this.y > ev.y) || (this.x > ev.x && this.y < ev.y) break; case 2: // Down return this.x !== ev.x; break; case 3: // Down Right return (this.x > ev.x && this.y > ev.y) || (this.x < ev.x && this.y < ev.y) break; case 4: // Left return this.y !== ev.y; break; case 6: // Right return this.y !== ev.y; break; case 7: // Up Left return (this.x > ev.x && this.y > ev.y) || (this.x < ev.x && this.y < ev.y) break; case 8: // Up return this.x !== ev.x; break; case 9: // Up Right return (this.x < ev.x && this.y > ev.y) || (this.x > ev.x && this.y < ev.y) break; } return false; }; //============================================================================= // Game_Event //============================================================================= Yanfly.EEA.Game_Event_start = Game_Event.prototype.start; Game_Event.prototype.start = function() { if (this.isEncounterDirectionLocked()) { var list = this.list(); if (list && list.length > 1) { this._starting = true; if (this.isTriggerIn([0,1,2])) this.encounterLock(); } } else { Yanfly.EEA.Game_Event_start.call(this); } }; Game_Event.prototype.encounterLock = function() { this._prelockDirection = this.direction(); this._locked = true; }; Game_Event.prototype.isEncounterDirectionLocked = function() { if (this.event().encounterDirectionLock === undefined) { DataManager.processEEANotetags1(this.event()); } return this.event().encounterDirectionLock; }; Yanfly.EEA.Game_Event_checkEventTriggerTouch = Game_Event.prototype.checkEventTriggerTouch; Game_Event.prototype.checkEventTriggerTouch = function(x, y) { Yanfly.EEA.Game_Event_checkEventTriggerTouch.call(this, x, y); if ($gameMap.isEventRunning()) return; if (this._trigger !== 2) return; if (!this.isFollowerTriggerTouch()) return; if (this.isJumping()) return; if (!this.isNormalPriority()) return; var followers = $gamePlayer.followers().visibleFollowers(); var length = followers.length; for (var i = 0; i < length; ++i) { var follower = followers[i]; if (follower && follower.pos(x, y)) this.start(); } }; Game_Event.prototype.isFollowerTriggerTouch = function() { if (this.event().encounterFollowerTrigger === undefined) { DataManager.processEEANotetags1(this.event()); } return this.event().encounterFollowerTrigger; }; //============================================================================= // Game_Interpreter //============================================================================= Game_Interpreter.prototype.checkEventFacingPlayerFront = function() { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return ev.isFacingTowards(pl) && pl.isPositionFrontOf(ev); }; Game_Interpreter.prototype.checkEventFacingPlayerBack = function() { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return ev.isFacingAway(pl) && pl.isPositionBackOf(ev); }; Game_Interpreter.prototype.checkEventFacingPlayerSide = function() { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return ev.isFacingSideways(pl) && pl.isPositionSideOf(ev); }; Game_Interpreter.prototype.checkPlayerFacingEventFront = function() { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return pl.isFacingTowards(ev) && ev.isPositionFrontOf(pl); }; Game_Interpreter.prototype.checkPlayerFacingEventBack = function() { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return pl.isFacingAway(ev) && ev.isPositionBackOf(pl); }; Game_Interpreter.prototype.checkPlayerFacingEventSide = function() { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return pl.isFacingSideways(ev) && ev.isPositionSideOf(pl); }; //============================================================================= // End of File //============================================================================= <reponame>MehGokalp/vendor-bear const idGenerator = require('uniqid'); const utils = require('../service/utils'); /** * @param card Mongo scheme */ const populate = (card) => { if (!card.reference) { card.reference = idGenerator().slice(0, 15); } if (!card.cardNumber) { card.cardNumber = utils.generateCreditCardNumber(); } if (!card.cvc) { card.cvc = utils.generateCVC(); } }; module.exports = { populate: populate }; <reponame>vpanjganj/blackjack /** * Created by Vahid on 09/06/15. */ 'use strict'; // Declare app level module which depends on views, and components var app = angular.module("blackjack", [ 'filters', 'services', 'controllers', 'directives', 'ui.bootstrap' ]); var filters = angular.module('filters', []); var services = angular.module('services', []);//services holds the definitions for classes var directives = angular.module('directives', []); var controllers = angular.module('controllers', []); <gh_stars>0 import Container from "../../../container"; import {Heading} from "../../../atoms/typography/heading"; import {Paragraph} from "../../../atoms/typography/paragraph"; import TextBlockWithImage from "../../../molecules/mixed-blocks/text-block-with-absolute-image"; import OkIcon from "../../../../images/icons/ok.inline.svg"; import IdetifyIcon from "../../../../images/icons/identify-your-unique-selling-point.inline.svg" import LookIcon from "../../../../images/icons/look-at-who-your-competitors-are-in-the-space.inline.svg" import MarketIcon from "../../../../images/icons/understand-your-market.inline.svg" import {color} from "../../../../components/styles/colors"; import React from "react"; import styled from "styled-components"; import Curve from "../../../atoms/shapes/curve"; import {gradient} from "../../../atoms/styles/colors"; const ContainerWrapper = styled.div` background: rgb(255,255,255); background-image: ${gradient.orange3}; padding-bottom: 100px; position: relative; padding-top: 120px; `; const GridSection = styled.div` width: 100%; `; const TitleBox = styled.div` width: 100%; position: relative; max-width: 750px; @media (min-width:750px) { margin: 0 auto; } h2{ color: #1d1d1d; font-size: 40px; text-align: left; margin-bottom: 24px; } `; const GridSectionList = styled.div` display: grid; grid-gap: 10px; grid-template-columns: 100%; justify-content: center; column-gap: 30px; row-gap: 70px; margin-top: 76px; margin-bottom: 76px;; @media (min-width: 490px){ grid-template-columns: 470px; } @media (min-width: 992px){ grid-template-columns: 470px 470px; } `; const AbsoluteCurve = styled.div` position: absolute; left: -27px; top: -16px; transform: rotate(-90deg); `; const ValidatingBusinessIdea = () => ( <ContainerWrapper> <Container> <GridSection> <TitleBox> <AbsoluteCurve> <Curve color={color.blue1}/> </AbsoluteCurve> <Heading size={2} left>Validating Your Party Planning Business Idea</Heading> <Paragraph big> These are all great starting points, but you will need to build on them to make the business your own. You have unique skills and insight that you can use to start an event planning business that will really stand out. Before committing too much time, energy and money into your new party or event planning business, it’s important to test the marketplace. </Paragraph> <Paragraph big> Not every idea you have will make it through to becoming a successful planning business. There are all sorts of reasons to say “yes” or “no” to specific businesses; think about what your strengths and weaknesses are so you can choose one you’d be great at. </Paragraph> </TitleBox> <GridSectionList> <TextBlockWithImage width={100} widthUnit="%" SvgImage={IdetifyIcon} imageBackgroundColor={color.green2} imageShadowColor={color.green2}> <Heading size={3} template={4}> Identify your planning business’ unique selling points (USPs) </Heading> <Paragraph bottomPadding={0} bottomMargin={0}> Decide on the main benefits of your business and how you’re going to communicate them. Whether that’s because of your niche, experience, skills or services, you will need to set yourself apart from competitors to attract the right event planning clients. </Paragraph> </TextBlockWithImage> <TextBlockWithImage width={100} widthUnit="%" SvgImage={LookIcon} imageBackgroundColor={color.babyblue2} imageShadowColor={color.babyblue2}> <Heading size={3} template={4}> Look at who your competitors are in the space </Heading> <Paragraph bottomPadding={0} bottomMargin={0}> Having competitors is a good thing as it shows there’s a market, but it’s still vital to find your own space. Look into who the other event and party planners are and the type of clients they have. Try to identify some gaps in the marketplace. </Paragraph> </TextBlockWithImage> <TextBlockWithImage width={100} widthUnit="%" SvgImage={MarketIcon} imageBackgroundColor={color.orange2} imageShadowColor={color.orange2}> <Heading size={3} template={4}> Understand your market </Heading> <Paragraph bottomPadding={0} bottomMargin={0}> Party and event planning relies on having enough potential clients in your local marketplace. Investigate how many of a specific type of event happen in your city on a regular basis to learn if there’s enough business for a new event planning company. Clearly identify exactly who your customers are likely to be, where they hang out and how you’re going to reach them. This will be essential to your marketing, communications, sales and customer support. </Paragraph> </TextBlockWithImage> <TextBlockWithImage width={100} widthUnit="%" SvgImage={OkIcon} imageBackgroundColor={color.purple2} imageShadowColor={color.purple2}> <Heading size={3} template={4}> Talk to clients </Heading> <Paragraph bottomPadding={0} bottomMargin={0}> Speak with your potential clients to understand local nuances and what they’re looking for from an event or party planning business. Validate your business idea by asking if they would commit to spending real money on you as an event planner. </Paragraph> </TextBlockWithImage> </GridSectionList> </GridSection> </Container> </ContainerWrapper> ); export default ValidatingBusinessIdea; if (typeof window !== 'undefined') console.error('ds6 icon not found: auction'); /* $Id: clustermarker_marker.js,v 1.1 2009/02/12 23:45:23 bdragon Exp $ */ /** * @file * GMap Markers * <NAME>'s ClusterMarker version */ /*global ClusterMarker, Drupal, GMarker */ // Replace to override marker creation Drupal.gmap.factory.marker = function (loc, opts) { return new GMarker(loc, opts); }; Drupal.gmap.addHandler('gmap', function (elem) { var obj = this; obj.bind('init', function () { obj.clustermarker = 0; }); obj.bind('iconsready', function () { if (!obj.clustermarker) { var options = Drupal.settings.gmap_markermanager; if (options.clusterMarkerIcon.length) { options.clusterMarkerIcon = Drupal.gmap.getIcon(options.clusterMarkerIcon, 0); } else { delete options.clusterMarkerIcon; } options.borderPadding = +options.borderPadding; options.fitMapMaxZoom = +options.fitMapMaxZoom; options.intersectPadding = +options.intersectPadding; obj.clusterMarker = new ClusterMarker(obj.map, options); } }); obj.bind('addmarker', function (marker) { obj.clusterMarker.addMarkers([marker.marker]); }); obj.bind('delmarker', function (marker) { // @@@TODO: Implement this! }); obj.bind('clearmarkers', function () { obj.clusterMarker.removeMarkers(); }); }); "use strict"; const path = require("path"); const fs = require("fs-extra"); const readline = require("readline"); const root = path.normalize(path.join(__dirname, "..")); let guh = require("../package"); const rl = readline.createInterface({ output: process.stdout, input: process.stdin }); let out; let name; if (process.argv[3]) { out = process.argv[3]; name = path.parse(out).name; } // Promise wrapper for readline const prompt = (text, fallback) => { return new Promise(resolve => { rl.question(text, answer => { if (!answer) { resolve(fallback); return; } resolve(answer); }) }); }; const answers = {}; // Patterns for files we shouldn't copy const blacklist = [ /^node_modules[\\\/](?!app)/, /^.git$/, /^.sass-cache$/, /^bin$/, /^(debug|production)$/, /^package.json$/, /^(CHANGES.md|README.md|LICENSE.md)$/, /^[^\/]+\.sublime-/ ]; // We use these dependencies only in the generator. const blackDeps = new Set(["fs-extra"]); const README = (name) => ` # ${ name } ${ answers.description } `.trim(); // Let's go! prompt(`Project name? ${name ? "(" + name + ")" : ""} `, name) .then(projectName => { answers.projectName = projectName; const existing = out || ("./" + projectName); return prompt(`Project path? ${existing} `, existing); }) .then(projectPath => { answers.path = projectPath; return prompt(`Description? `, "Generated with guh") }) .then(description => { answers.description = description; rl.close(); }) .then(() => { out = answers.path || out; name = answers.projectName || name; if (!path.isAbsolute(out)) { out = path.join(process.cwd(), out); } // We're building from `root` to `out` fs.mkdirsSync(out); return new Promise((resolve, reject) => { fs.copy(root, out, { filter: (file) => { const relative = path.relative(root, file); for (const reg of blacklist) { if (reg.test(relative)) { return false; } } return true; } }, (err) => { if (err) { console.error(err); reject(err); return; } resolve(); }); }); }).then(() => { // Write a readme fs.writeFileSync(path.join(out, "README.md"), README(name)); // Write new package.json const pack = { name: name, version: "1.0.0", description: answers.description, guh: { version: guh.version }, dependencies: guh.dependencies, devDependencies: guh.devDependencies, bundleDependencies: guh.bundleDependencies, scripts: guh.scripts }; const deps = pack.dependencies; const newDeps = {}; for (const key in deps) { if (deps.hasOwnProperty(key)) { if (!blackDeps.has(key)) { newDeps[key] = deps[key]; } } } pack.dependencies = newDeps; const packBody = JSON.stringify(pack, null, 2); fs.writeFileSync(path.join(out, "package.json"), packBody); // If the user has a sublime-project file, let's copy it! if (fs.lstatSync(path.join(root, "guh.sublime-project"))) { let body = fs.readFileSync(path.join(root, "guh.sublime-project")).toString("utf8"); body = body.replace(/guh/g, name); fs.writeFileSync(path.join(out, `${name}.sublime-project`), body); } console.log("\nScaffolded new project at ", out); console.log("You should change into that directory and run \"npm install\""); console.log("After that's done, you can use \"guh build\" to build it!"); }).catch(e => { console.error(e); });<filename>react-ui/src/components/GetPosts.js<gh_stars>0 import React from "react"; // Create GetPosts class component class GetPosts extends React.Component { constructor(props) { super(props); // Set initial state variables. this.state = { isLoaded: props.isLoaded, titlesArray: [], postsArray: [], idArray: [], authorArray: [], error: null, dateCreatedArray: [], dateModifiedArray: [], message: null, }; } // Component did mount function runs once only componentDidMount() { // Fetch posts from db fetch("/getposts") .then((res) => res.json()) .then( (result) => { // Save post info to state this.setState( { isLoaded: true, titlesArray: result.titles, postsArray: result.posts, idArray: result.ids, authorArray: result.authors, dateCreatedArray: result.datecreated, dateModifiedArray: result.datemodified, message: result.message, }, () => { console.log("Db says: " + this.state.message); // Send post info to function in app.js (lifting state up) this.props.loadPosts( this.state.isLoaded, this.state.titlesArray, this.state.postsArray, this.state.idArray, this.state.authorArray, this.state.dateCreatedArray, this.state.dateModifiedArray ); } ); }, (error) => { this.setState({ isLoaded: true, error, }); } ); // End of componentdidmount } // Nothing to return render() { return null; } } // Export component to be used by other files export default GetPosts; "use strict"; /* * Copyright © 2018 Atomist, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); /** * A code action response that affects delivery: * failing the current goal or requiring approval, * causing dependent goals to fail or wait. */ var PushReactionResponse; (function (PushReactionResponse) { /** * Fail execution of the present goalset. Any dependent goals will stop. * Will not stop execution of non-dependent goals. */ PushReactionResponse["failGoals"] = "fail"; /** * Require approval to proceed to dependent goals in the present goalset. */ PushReactionResponse["requireApprovalToProceed"] = "requireApproval"; })(PushReactionResponse = exports.PushReactionResponse || (exports.PushReactionResponse = {})); function isPushReactionRegistration(a) { const maybe = a; return !!maybe.name && !!maybe.action; } /** * Convert an action function to a PushReaction if necessary * @param {PushReactionRegisterable<any>} prr * @return {PushReactionRegistration} */ function toPushReactionRegistration(prr) { return isPushReactionRegistration(prr) ? prr : { name: "Raw push reaction", action: prr, }; } exports.toPushReactionRegistration = toPushReactionRegistration; /** * Compute the relevant actions for this push. Some may be filtered out * by their push tests. */ function relevantCodeActions(registrations, pli) { return Promise.all(registrations.map((t) => __awaiter(this, void 0, void 0, function* () { return (!t.pushTest || (yield t.pushTest.mapping(pli))) ? t : undefined; }))) .then(elts => elts.filter(x => !!x)); } exports.relevantCodeActions = relevantCodeActions; //# sourceMappingURL=PushReactionRegistration.js.mapimport React from 'react'; /** * A menu component containing what is displayed other than the canvas such as * 1. buttons (restat and join) * 2. number of players */ class Menu extends React.Component { render() { let playerCount = this.props.playerCount; return ( <div> {this.props.single?"": (<h1>{playerCount} player{playerCount === 1? "" : "s"} in this room</h1>)} <button type="button" class="btn btn-outline-primary" style={{margin:"auto auto 2em 1em"}} variant="primary" onClick={this.props.removeText}>Restart</button> <br /> {this.props.single?"": ( <button type="button" class="btn btn-outline-primary" onClick={this.props.handleJoin}> Join</button>)} </div> ) } } export default Menu; <filename>static/js/main.js<gh_stars>0 'use strict'; var PIECES = { none: 0, pawn: 1, knight: 2, bishop: 3, rook: 4, queen: 5, king: 6 }; var TEAM = { none: 0, black: 7, white: 2, }; var BOARD; var PLAYER_TEAM = TEAM.none; var SOCKET; /** * Column/letter decrease by one */ function col_decrease(col, times) { var map = { a: undefined, b: "a", c: "b", d: "c", e: "d", f: "e", g: "f", h: "g" }; if (times) { for (var i = 0; i < times; i++) { col = map[col]; } return col; } else { return map[col]; } } /** * Column/letter increase by one */ function col_increase(col, times) { var map = { a: "b", b: "c", c: "d", d: "e", e: "f", f: "g", g: "h", h: undefined }; if (times) { for (var i = 0; i < times; i++) { col = map[col]; } return col; } else { return map[col]; } } /** * Chess board click callback. */ function click() { if (BOARD.turn !== PLAYER_TEAM) return; if (BOARD.selected) { selected_click(this.id); } else { not_selected_click(this.id); } } /** * Chess board click handler when figure has been selected. */ function selected_click(id) { var block = BOARD[id]; if (block.team === PLAYER_TEAM) { BOARD.unselect(); BOARD.select(id); return; } var move_to = BOARD.selected_move_area.indexOf(id); if (move_to !== -1) { BOARD.move(BOARD.selected_move_area[move_to]); } } /** * Chess board click handler when figure has NOT been selected. */ function not_selected_click(id) { var block = BOARD[id]; if ((block.piece === PIECES.none) || !block.team || (PLAYER_TEAM !== block.team)) { return; } BOARD.select(id); } /** * Chess board class */ function ChessBoard() { /** * Function iterator over board. * Requires functor: func(me: reference to board, id: "<col><row>") */ this.iterate = function(functor) { ["a", "b", "c", "d", "e", "f", "g", "h"].forEach(function(col) { for (var i = 1; i < 9; i++) functor(this, col+i); }, this); }; this.name = undefined; this.side = undefined; /* text representation of team */ this.turn = TEAM.white; this.selected = undefined; this.selected_move_area = []; this.king_pos = undefined; this.king_moved = false; this.h_rook_moved = false; this.a_rook_moved = false; this.king_checked = false; this.en_passant_to = undefined; this.set_name = function(name) { this.name = name; document.getElementById("party_name").innerHTML = decodeURIComponent(name); }; //Initialize board this.iterate(function(me, id) { me[id] = { div: document.getElementById(id), team: TEAM.none, piece: PIECES.none }; me[id].div.onclick=click; }); /** * Ends current turn. */ this.turn_end = function() { if (BOARD.turn === TEAM.white) { BOARD.turn = TEAM.black; document.getElementById("menu_turn").innerHTML = "BLACK"; } else if (BOARD.turn === TEAM.black) { BOARD.turn = TEAM.white; document.getElementById("menu_turn").innerHTML = "WHITE"; } }; /** * Resets element/board to initial values(empty). * * @param id Specify if only specific element requires reset. Optional */ this.reset = function(id) { if (id) { var block = this[id]; block.team = TEAM.none; block.piece = PIECES.none; block.div.className = block.div.className .replace(/((black)|(white))_[^ ]+/, "") .replace("selected", ""); } else { this.iterate(function(me, id) { me.reset(id); }); } }; /* Fires sync event with board's data */ this.sync_game = function(socket) { var data = { name: this.name, side: PLAYER_TEAM, sync_data: { turn: this.turn, board: {} } }; ["a", "b", "c", "d", "e", "f", "g", "h"].forEach(function(col) { var pos; for (var idx = 1; idx < 9; idx++) { pos = col + idx; data.sync_data.board[pos] = {}; data.sync_data.board[pos].team = this[pos].team; data.sync_data.board[pos].piece = this[pos].piece; } }, this); socket.emit("sync_game", data); }; /* Sets board element with data into position */ this.set_board_elem = function(position, data) { var element = this[position]; var team_str; if (data.team === TEAM.black) team_str = " black"; else if (data.team === TEAM.white) team_str = " white"; element.team = data.team; element.piece = data.piece; switch (data.piece) { case PIECES.pawn: element.div.className += team_str + "_pawn"; break; case PIECES.rook: element.div.className += team_str + "_rook"; break; case PIECES.knight: element.div.className += team_str + "_knight"; break; case PIECES.bishop: element.div.className += team_str + "_bishop"; break; case PIECES.queen: element.div.className += team_str + "_queen"; break; case PIECES.king: this.king_pos = position; element.div.className += team_str + "_king"; break; } }; /* Restores board from sync data */ this.read_sync = function(data) { this.reset(); this.turn = data.turn; if (this.turn === TEAM.white) document.getElementById("menu_turn").innerHTML = "WHITE"; else if (this.turn === TEAM.black) document.getElementById("menu_turn").innerHTML = "BLACK"; ["a", "b", "c", "d", "e", "f", "g", "h"].forEach(function(col) { var pos; for (var idx = 1; idx < 9; idx++) { pos = col + idx; this.set_board_elem(pos, data.board[pos]); } }, this); if (this.is_me_check()) this.me_checked(); }; /** * Selects element on board. * * @param id Id of board's element. */ this.select = function(id) { var block = BOARD[id]; block.div.className += " selected"; this.selected = id; this.set_avail_area(); }; /** * Unselect currently selected element. */ this.unselect = function() { if (this.selected) { this.selected = undefined; this.selected_move_area.length = 0; this.iterate(function(me, id) { var block = me[id].div; block.className = block.className.replace("selected", ""); }); } }; /** * Check if enemy king has been checked after move. * * @param moved_to Location where piece has moved. */ this.is_enemy_check = function(moved_to) { var move_area = this.get_avail_area(moved_to); for (var idx = 0; idx < move_area.length; idx++) { var block = BOARD[move_area[idx]]; if (block.piece === PIECES.king && block.team !== PLAYER_TEAM) { block.div.className = block.div.className + " checked"; SOCKET.emit("check", { name: this.name, side: PLAYER_TEAM, }); break; } } }; this.pawn_promo = function(new_piece, position) { var pos = this[position]; var figure_map = {}; figure_map[PIECES.queen] = "queen"; figure_map[PIECES.rook] = "rook"; figure_map[PIECES.bishop] = "bishop"; figure_map[PIECES.knight] = "knight"; pos.piece = new_piece; pos.div.className = pos.div.className.replace(/_[^]+/, "_" + figure_map[new_piece]); }; /** * Check if pawn's promotion is needed. */ this.is_pawn_promo = function(pos) { var move_to = pos.div.id; if ((pos.team === TEAM.black && move_to[1] === "1") || (pos.team === TEAM.white && move_to[1] === "8")) { var promo_select = document.getElementById("pawn_promo"); var figure_name = promo_select.options[promo_select.selectedIndex].value; var figure_map = { Queen: PIECES.queen, Rook: PIECES.rook, Bishop: PIECES.bishop, Knight: PIECES.knight }; pos.piece = figure_map[figure_name]; pos.div.className = pos.div.className.replace(/_[^]+/, "_" + figure_name.toLowerCase()); SOCKET.emit("pawn_promo", { name: this.name, side: PLAYER_TEAM, new_piece: pos.piece, pos: move_to }); } }; /** * @brief Gets movement area of enemy. * * Emulates set by using object's keys. */ this.get_enemy_avail_area = function() { var set_enemy_moves = {}; ["a", "b", "c", "d", "e", "f", "g", "h"].forEach(function(col) { for (var i = 1; i < 9; i++) { var enemy_pos = col+i; if (this[enemy_pos].team === TEAM.none || this[enemy_pos].team === PLAYER_TEAM) continue; var old_team = PLAYER_TEAM; /* Avoid castling calculation for enemy king */ var old_king_moved = this.king_moved; this.king_moved = true; if (PLAYER_TEAM === TEAM.black) PLAYER_TEAM = TEAM.white; else PLAYER_TEAM = TEAM.black; var enemy_area = this.get_avail_area(enemy_pos, true); for (var enemy_idx = 0; enemy_idx < enemy_area.length; enemy_idx++) { set_enemy_moves[enemy_area[enemy_idx]] = true; } PLAYER_TEAM = old_team; this.king_moved = old_king_moved; } }, this); return set_enemy_moves; }; /** * Checks own king upon event from server. */ this.me_checked = function() { this.king_checked = true; this[this.king_pos].div.className = this[this.king_pos].div.className + " checked"; }; /** * Uncheck divs. */ this.uncheck = function(king_pos, old_pos) { this[king_pos].div.className = this[king_pos].div.className.replace(/ checked/, ""); if (old_pos) this[old_pos].div.className = this[old_pos].div.className.replace(/ checked/, ""); }; /** * Uncheck divs king. */ this.me_uncheck = function(old_pos) { this.king_checked = false; this.uncheck(this.king_pos, old_pos); SOCKET.emit("uncheck", { name: this.name, side: PLAYER_TEAM, king_pos: this.king_pos, old_pos: old_pos }); }; /** * Checks if player's king got exposed to enemy. * * @return Bool. */ this.is_me_check = function() { return this.king_pos in this.get_enemy_avail_area(); }; /** * Checks if castling possibility is lost */ this.is_castling_lost = function(pos) { if (pos.piece === PIECES.king) { this.king_moved = true; var pos_id = pos.div.id; var num; if (PLAYER_TEAM === TEAM.black) num = "8"; else num = "1"; if (pos_id[1] === num) { var old_selected = this.selected; //move rook according castling if (!this.h_rook_moved && pos_id[0] === "g") { this.selected = "h" + num; this.move(col_decrease(this.king_pos[0]) + num, false); this.selected = old_selected; } else if (!this.a_rook_moved && pos_id[0] === "c") { this.selected = "a" + num; this.move(col_increase(this.king_pos[0]) + num, false); this.selected = old_selected; } } } else if (pos.piece === PIECES.rook) { if (this.selected[0] === "h") this.h_rook_moved = true; else if (this.selected[0] === "a") this.a_rook_moved = true; this.king_moved = this.h_rook_moved && this.a_rook_moved; } if (this.king_moved) { this.get_avail_castling_king = function() { return []; }; this.is_castling_lost = function() { return true; }; } }; /** * Handles En passant move. */ this.is_move_en_passant = function(to) { if (to === this.en_passant_to) { var passanted_pawn_pos = to[0]; if (PLAYER_TEAM === TEAM.white) passanted_pawn_pos += "5"; else passanted_pawn_pos += "4"; SOCKET.emit("en_passant", { name: this.name, side: PLAYER_TEAM, poor_pawn: passanted_pawn_pos }); this.reset(passanted_pawn_pos); } this.en_passant_to = undefined; }; /** * Checks if it is possible to perform En passant. */ this.is_en_passant = function(pos) { return this.en_passant_to && pos && (this[pos].team === TEAM.none && pos === this.en_passant_to); }; /** * Set if En passant is possible for moved pawn. */ this.en_passant = function(from, to) { if (PLAYER_TEAM === TEAM.white && from[1] === "7" && to[1] === "5") { this.en_passant_to = from[0] + "6"; } else if (PLAYER_TEAM === TEAM.black && from[1] === "2" && to[1] === "4") { this.en_passant_to = from[0] + "3"; } }; /** * Performs enemy move. */ this.enemy_move = function(from, to) { var old_pos = this[from]; var new_pos = this[to]; new_pos.team = old_pos.team; new_pos.piece = old_pos.piece; new_pos.div.className = new_pos.div.className.replace(/((black)|(white))_[^ ]+/, "") + " " + old_pos.div.className.split(/\s+/)[1]; if (new_pos.piece === PIECES.pawn) this.en_passant(from, to); this.reset(from); }; /** * @brief Moves piece to new location. * * Clear selection and checks for enemy king being checked * by this move. * Cancel move if own king is under threat. * * @param to New location. * @param finished Last move(in case of castling). */ this.move = function(to, finished) { if (finished === undefined) finished = true; var old_pos = this[this.selected]; var new_pos = this[to]; if (old_pos.piece === PIECES.king) this.king_pos = to; new_pos.team = old_pos.team; new_pos.piece = old_pos.piece; new_pos.div.className = new_pos.div.className.replace(/((black)|(white))_[^ ]+/, "") + " " + old_pos.div.className.split(/\s+/)[1]; if (this.is_me_check()) { this.reset(to); if (old_pos.piece === PIECES.king) this.king_pos = this.selected; return; } else if (this.king_checked) { this.me_uncheck(this.selected); } SOCKET.emit("move", { name: this.name, side: PLAYER_TEAM, old_pos: this.selected, new_pos: to, finished: finished }); if (new_pos.piece === PIECES.pawn) { this.is_move_en_passant(to); this.is_pawn_promo(new_pos); } this.en_passant_to = undefined; this.is_castling_lost(new_pos); this.is_enemy_check(to); if (finished) this.turn_end(); this.reset(this.selected); this.selected = undefined; }; /** * Store available area for move of currently selected piece. */ this.set_avail_area = function() { this.selected_move_area = this.get_avail_area(); }; /** * Checks if location on board belongs to enemy team. */ this.is_enemy_team = function(loc) { return Math.abs(this[loc].team - PLAYER_TEAM) === 5; }; /** * Returns array of possible moves for pawn. * * @param eat Flag for special handling of king's check. */ this.get_avail_area_pawn = function(col, row, cur, eat) { var result = []; var new_row; if (cur.team === TEAM.white) { new_row = row + 1; } else { new_row = row - 1; } var move = col + new_row; var eat_left = col_decrease(col) + new_row; var eat_right = col_increase(col) + new_row; //Check if can eat if (eat_left && (eat || this.is_enemy_team(eat_left) || this.is_en_passant(eat_left))) { result.push(eat_left); } if (eat_right && (eat || this.is_enemy_team(eat_right) || this.is_en_passant(eat_right))) { result.push(eat_right); } if (eat) return result; if (this[move].team === TEAM.none) { result.push(move); //First move can be for 2 cells //See TEAM enum for logic if ((cur.team - row) === 0) { if (cur.team === TEAM.white) { move = col + (row + 2); } else { move = col + (row - 2); } if (this[move].team === TEAM.none) result.push(move); } } return result; }; /** * Returns array of possible moves for knight. */ this.get_avail_area_knight = function(col, row) { var result = []; var moves = [ [col_decrease(col, 2), [row+1, row-1]], [col_decrease(col), [row+2, row-2]], [col_increase(col), [row+2, row-2]], [col_increase(col, 2), [row+1, row-1]] ].filter(function(elem) { return elem[0]; }); for (var idx = 0; idx < moves.length; idx++) { var new_col = moves[idx][0]; var new_rows = moves[idx][1]; for (var jdx = 0; jdx < new_rows.length; jdx++) { if (new_rows[jdx] > 0 && new_rows[jdx] < 9) { var new_move = new_col + new_rows[jdx]; if (this[new_move].team !== PLAYER_TEAM) result.push(new_move); } } } return result; }; /** * Checks if it is possible to move in loops * * @returns [is_break; is_to_add] */ this.board_is_move_ok = function(move) { var result = [false, false]; if (this[move].team === TEAM.none) { result[1] = true; } else if (this.is_enemy_team(move)) { result[1] = true; result[0] = true; } else { result[0] = true; } return result; }; /** * Returns array of possible moves for bishop. */ this.get_avail_area_bishop = function(col, row) { var result = []; var move, move_check; var idx = row - 1; var col_idx = col_decrease(col); for (; idx > 0 && col_idx !== undefined; col_idx = col_decrease(col_idx)) { move = col_idx + idx; move_check = this.board_is_move_ok(move); if (move_check[1]) result.push(move); if (move_check[0]) break; idx--; } idx = row + 1; col_idx = col_decrease(col); for (; idx < 9 && col_idx !== undefined; col_idx = col_decrease(col_idx)) { move = col_idx + idx; move_check = this.board_is_move_ok(move); if (move_check[1]) result.push(move); if (move_check[0]) break; idx++; } idx = row - 1; col_idx = col_increase(col); for (; idx > 0 && col_idx !== undefined; col_idx = col_increase(col_idx)) { move = col_idx + idx; move_check = this.board_is_move_ok(move); if (move_check[1]) result.push(move); if (move_check[0]) break; idx--; } idx = row + 1; col_idx = col_increase(col); for (; idx < 9 && col_idx !== undefined; col_idx = col_increase(col_idx)) { move = col_idx + idx; move_check = this.board_is_move_ok(move); if (move_check[1]) result.push(move); if (move_check[0]) break; idx++; } return result; }; /** * Returns array of possible moves for rook. */ this.get_avail_area_rook = function(col, row) { var result = []; var move, move_check; for (var idx_down = row - 1; idx_down > 0; idx_down--) { move = col + idx_down; move_check = this.board_is_move_ok(move); if (move_check[1]) result.push(move); if (move_check[0]) break; } for (var idx_up = row + 1; idx_up < 9; idx_up++) { move = col + idx_up; move_check = this.board_is_move_ok(move); if (move_check[1]) result.push(move); if (move_check[0]) break; } for (var col_left = col_decrease(col); col_left !== undefined; col_left = col_decrease(col_left)) { move = col_left + row; move_check = this.board_is_move_ok(move); if (move_check[1]) result.push(move); if (move_check[0]) break; } for (var col_right = col_increase(col); col_right !== undefined; col_right = col_increase(col_right)) { move = col_right + row; move_check = this.board_is_move_ok(move); if (move_check[1]) result.push(move); if (move_check[0]) break; } return result; }; /** * @brief Returns array of possible castling moves for king. * * Overridden when castling is no longer possible. */ this.get_avail_castling_king = function() { var result = []; if (this.king_moved) return result; if (this.h_rook_moved && this.a_rook_moved) return result; var num; if (PLAYER_TEAM === TEAM.black) num = "8"; else num = "1"; var h_pos = this["h" + num]; var a_pos = this["a" + num]; var set_enemy_moves = this.get_enemy_avail_area(); function is_empty(pos) { return this[pos].team === TEAM.none; } function is_can_castle(pos) { return !(pos in set_enemy_moves); } if (!this.h_rook_moved && h_pos.team === PLAYER_TEAM && h_pos.piece === PIECES.rook) { var move_h = ["f" + num, "g" + num]; if (move_h.every(is_empty, this) && move_h.every(is_can_castle, this)) { result.push("g" + num); } } if (!this.a_rook_moved && a_pos.team === PLAYER_TEAM && a_pos.piece === PIECES.rook) { var move_a = ["d" + num, "c" + num, "b" + num]; if (move_a.every(is_empty, this) && move_a.slice(0, 2).every(is_can_castle, this)) { result.push("c" + num); } } return result; }; /** * Returns array of possible moves for king. */ this.get_avail_area_king = function(col, row) { var col_left = col_decrease(col); var col_right = col_increase(col); var row_up = row + 1; var row_down = row - 1; var possible_moves = [[col_left, row_up], [col, row_up], [col_right, row_up], [col_left, row], [col_right, row], [col_left, row_down], [col, row_down], [col_right, row_down]]; return possible_moves.filter(function(val) { var col = val[0]; var row = val[1]; if (col === undefined || row < 1 || row > 8) return false; return this.board_is_move_ok(col+row)[1]; }, this).map(function(val) { return val[0] + val[1]; }); }; /** * Returns array of possible moves of currently selected piece. * * @param pos Piece location. * @param eat Flag for pawn to get eat-only moves. * * @return List of possible moves. */ this.get_avail_area = function(pos, eat) { var result = []; if (!pos) { pos = this.selected; } var col = pos[0]; var row = parseInt(pos[1]); var cur = this[pos]; switch (cur.piece) { case PIECES.pawn: result = this.get_avail_area_pawn(col, row, cur, eat); break; case PIECES.knight: result = this.get_avail_area_knight(col, row); break; case PIECES.bishop: result = this.get_avail_area_bishop(col, row); break; case PIECES.rook: result = this.get_avail_area_rook(col, row); break; case PIECES.queen: result = this.get_avail_area_bishop(col, row, cur); result = result.concat(this.get_avail_area_rook(col, row, cur)); break; case PIECES.king: result = this.get_avail_area_king(col, row); result = result.concat(this.get_avail_castling_king()); break; } return result; }; } /** * @brief Sets initial pieces at default positions. * * Must be called once. * To reset board use chess_reset function. */ function chess_init(part_name, side) { if (BOARD === undefined) { BOARD = new ChessBoard(); } var figure_map = { a: ["rook", PIECES.rook], b: ["knight", PIECES.knight], c: ["bishop", PIECES.bishop], d: ["queen", PIECES.queen], e: ["king", PIECES.king], f: ["bishop", PIECES.bishop], g: ["knight", PIECES.knight], h: ["rook", PIECES.rook] }; ["a", "b", "c", "d", "e", "f", "g", "h"].forEach(function(col) { //black var col8 = col + 8; var col7 = col + 7; BOARD[col8].div.className += " black_" + figure_map[col][0]; BOARD[col8].team = TEAM.black; BOARD[col8].piece = figure_map[col][1]; BOARD[col7].div.className += " black_pawn"; BOARD[col7].team = TEAM.black; BOARD[col7].piece = PIECES.pawn; //white var col1 = col + 1; var col2 = col + 2; BOARD[col1].div.className += " white_" + figure_map[col][0]; BOARD[col1].team = TEAM.white; BOARD[col1].piece = figure_map[col][1]; BOARD[col2].div.className += " white_pawn"; BOARD[col2].team = TEAM.white; BOARD[col2].piece = PIECES.pawn; }); /* Joined someone's game */ if (side) { BOARD.set_name(part_name); BOARD.side = side; side_determ(side); } } function side_determ(side) { if (side === "black") { PLAYER_TEAM = TEAM.black; BOARD.king_pos = "e8"; } else { PLAYER_TEAM = TEAM.white; BOARD.king_pos = "e1"; } switch_side(); } /** * Reverses rows nums for board wrapper. */ function reverse_board_wrapper() { //TODO: this is a way too awful code. Improve it! var board_wrap = document.getElementById("board_wrap").childNodes[0]; var nodes = board_wrap.childNodes; var row_arr, col_arr; var idx; if (nodes[1].childNodes[0].innerHTML === "8") { nodes[1].childNodes[0].innerHTML = "1"; nodes[1].childNodes[2].innerHTML = "1"; row_arr = ["2", "3", "4", "5", "6", "7", "8"]; col_arr = ["h", "g", "f", "e", "d", "c", "b", "a"]; } else { nodes[1].childNodes[0].innerHTML = "8"; nodes[1].childNodes[2].innerHTML = "8"; row_arr = ["7", "6", "5", "4", "3", "2", "1"]; col_arr = ["a", "b", "c", "d", "e", "f", "g", "h"]; } for (idx = 2; idx < nodes.length - 1; idx++) { var row = row_arr[idx-2]; nodes[idx].childNodes[0].innerHTML = row; nodes[idx].childNodes[1].innerHTML = row; } for (idx = 0; idx < col_arr.length; idx++) { nodes[0].childNodes[idx+1].innerHTML = col_arr[idx]; nodes[nodes.length-1].childNodes[idx+1].innerHTML = col_arr[idx]; } } /** * Reverse chess_board */ function reverse_board() { var chess_board = document.getElementById("chess_board"); var nodes = chess_board.childNodes; var array_nodes = []; for (var idx = 0; idx < nodes.length; idx++) { array_nodes.unshift(nodes[idx]); } for (idx = 0; idx < nodes.length; idx++) { chess_board.appendChild(array_nodes[idx]); } reverse_board_wrapper(); } /** * Reverse player side. */ function switch_side() { if (PLAYER_TEAM === TEAM.white) { document.getElementById("menu_side").value = "White"; document.getElementById("menu_team").innerHTML = "WHITE"; } else if (PLAYER_TEAM === TEAM.black) { document.getElementById("menu_side").value = "Black"; document.getElementById("menu_team").innerHTML = "BLACK"; reverse_board(); } } /** * Cleans game and initialize board anew. */ function reset() { BOARD.reset(); chess_init(); } window.onbeforeunload = function() { SOCKET.close(); }; /** * Gets random int between min/max inclusively. */ function get_rand_int(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } /** * Gets side to play by simply picking random between (1,10) */ function get_random_side() { if (get_rand_int(1, 10) > 5) return "white"; else return "black"; } window.onload = function() { SOCKET = io(); var op_connected = true; var form = document.getElementById("party_form"); if (form) { form.btn.disabled = false; //In case of history move back form.addEventListener("submit", function(evet) { evet.preventDefault(); var party_name = encodeURIComponent(form.form_name.value); var side = form.form_side.value.toLowerCase(); var type = form.form_party_type.value.toLowerCase(); if (side === "random") side = get_random_side(); PLAYER_TEAM = side; SOCKET.emit("party_create", party_name, side, type); form.btn.disabled = true; //disable until we'll get reply. return false; }); SOCKET.on("create_ok", function(name_enc, side_enc) { BOARD.set_name(name_enc); BOARD.side = side_enc; //remove form. form = undefined; //Modify url to contain information for party restoration on reload. window.history.pushState("game", "Chess.js", "?game=" + name_enc + "&side=" + side_enc); document.body.removeChild(document.body.childNodes[2]); var enemy_side_enc; side_determ(side_enc); if (PLAYER_TEAM === TEAM.white) { enemy_side_enc = "black"; } else { enemy_side_enc = "white"; } //Pop-up waiting window document.getElementById('wait').style = ""; document.getElementById('wait_ref').href = "/?game=" + name_enc + "&side=" + enemy_side_enc; }); SOCKET.on("create_fail", function() { form.btn.disabled = false; PLAYER_TEAM = TEAM.none; window.alert("Failed to create party!\nParty with such name is already registered."); }); } SOCKET.on("joined", function() { document.getElementById("overlay").style = "display: none"; document.getElementById('wait').style = "display:none"; if (!op_connected) { op_connected = true; BOARD.sync_game(SOCKET); } }); SOCKET.on("join_ok", function() { document.getElementById("overlay").style = "display: none"; document.getElementById('wait').style = "display:none"; }); SOCKET.on("join_fail", function() { var wait_pop = document.getElementById('wait'); PLAYER_TEAM = TEAM.none; wait_pop.childNodes[0].innerHTML = "Sorry, but you cannot join this game!"; wait_pop.childNodes[1].innerHTML = "Feel free to go back and create your own game."; wait_pop.childNodes[2].href = "/"; wait_pop.childNodes[2].innerHTML = "Go back"; document.getElementById("overlay").style = ""; wait_pop.style = ""; }); SOCKET.on("move", function(move_data) { var from = move_data.old_pos; var to = move_data.new_pos; BOARD.enemy_move(from, to); if (move_data.finished) BOARD.turn_end(); }); SOCKET.on("check", function() { BOARD.me_checked(); }); SOCKET.on("uncheck", function(king_pos, old_pos) { BOARD.uncheck(king_pos, old_pos); }); SOCKET.on("pawn_promo", function(piece, pos) { BOARD.pawn_promo(piece, pos); }); SOCKET.on("sync_game", function(sync_data) { BOARD.read_sync(sync_data); }); SOCKET.on("en_passant", function(poor_pawn) { BOARD.reset(poor_pawn); }); SOCKET.on("opponent_disconnect", function() { var wait_pop = document.getElementById('wait'); wait_pop.childNodes[0].innerHTML = "Your opponent has been disconnected..."; wait_pop.childNodes[1].innerHTML = "Use your link below to invite your friend for a game"; wait_pop.childNodes[2].innerHTML = "Link"; if (PLAYER_TEAM === TEAM.white) { wait_pop.childNodes[2].href = "/?game=" + BOARD.name + "&side=black"; } else { wait_pop.childNodes[2].href = "/?game=" + BOARD.name + "&side=white"; } document.getElementById("overlay").style = ""; wait_pop.style = ""; op_connected = false; }); SOCKET.on("connect", function() { if (BOARD.name) { SOCKET.emit("party_join", BOARD.name, BOARD.side); } }); SOCKET.on("disconnect", function() { var wait_pop = document.getElementById('wait'); wait_pop.childNodes[0].innerHTML = "Connection to server has been lost..."; wait_pop.childNodes[1].innerHTML = "Please wait a bit or try to contact the one who messed it."; wait_pop.childNodes[2].innerHTML = ""; }); }; $(function(){ $('a#adesignproject').on('click', function(){ if ( $('body').hasClass('offcanvas') ) { $('body').removeClass('offcanvas'); $('.js-zz-nav-toggle').removeClass('active'); } $('html,body').stop().animate({ scrollTop: $('#design-project').offset().top }, 1000); }); $('a#aremontproject').on('click', function(){ if ( $('body').hasClass('offcanvas') ) { $('body').removeClass('offcanvas'); $('.js-zz-nav-toggle').removeClass('active'); } $('html,body').stop().animate({ scrollTop: $('#remont-project').offset().top }, 1000); }); $('a#aadvantages').on('click', function(){ if ( $('body').hasClass('offcanvas') ) { $('body').removeClass('offcanvas'); $('.js-zz-nav-toggle').removeClass('active'); } $('html,body').stop().animate({ scrollTop: $('#advantages').offset().top }, 1000); }); $('a#avideorow').on('click', function(){ if ( $('body').hasClass('offcanvas') ) { $('body').removeClass('offcanvas'); $('.js-zz-nav-toggle').removeClass('active'); } $('html,body').stop().animate({ scrollTop: $('#videorow').offset().top }, 1000); }); $('a#aphotorow').on('click', function(){ if ( $('body').hasClass('offcanvas') ) { $('body').removeClass('offcanvas'); $('.js-zz-nav-toggle').removeClass('active'); } $('html,body').stop().animate({ scrollTop: $('#photorow').offset().top }, 1000); }); $('a#zzfooter').on('click', function(){ if ( $('body').hasClass('offcanvas') ) { $('body').removeClass('offcanvas'); $('.js-zz-nav-toggle').removeClass('active'); } $('html,body').stop().animate({ scrollTop: $('#zz-footer').offset().top }, 1000); }); }); // 用户信息相关接口 import { post } from './http' // 创建文档 export const createOfficeFile = p => post('/office/createofficefile', p); // 编辑文档 export const editOfficeFile = p => post('/office/editofficefile', p); // 查看文档 export const previewOfficeFile = p => post('/office/previewofficefile', p);<filename>src/main.js /*! ========================================================= * Vue Argon Design System - v1.1.0 ========================================================= * Product Page: https://www.creative-tim.com/product/argon-design-system * Copyright 2019 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/argon-design-system/blob/master/LICENSE.md) * Coded by www.creative-tim.com ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import Argon from "./plugins/argon-kit"; import './registerServiceWorker'; import Vuex from 'vuex'; import 'es6-promise/auto' import VueSmoothScroll from 'vue2-smooth-scroll' const Web3 = require("web3"); const infuraKey = "d9cfa420001b4d6a9ab961286b8e7ff7" if (window.ethereum) { window.web3 = new Web3(window.ethereum); } else if (window.web3) { window.web3 = new Web3(window.web3.currentProvider); } else { window.web3 = new Web3('https://ropsten.infura.io/v3/' + infuraKey); } Vue.use(VueSmoothScroll) Vue.use(Vuex); Vue.config.productionTip = false; Vue.use(Argon); const store = new Vuex.Store({ state: { abi: require('./contract.abi.json'), lockabi: require('./lock.abi.json'), telikosabi: require('./telikos.abi.json'), contractAddr: "0xA81a85A8A51900Cc7A7bd86DdC6250754480a147", telikosAddr: null, genesisBlock: 8512076, pending: false, messages: [], }, mutations: { setPending(state, val) { state.pending = val }, addMessage(state, val) { state.messages.push(val) }, }, getters: { ABI: state => { return state.abi; }, LockABI: state => { return state.abi }, TelikosABI: state => { return state.telikosabi }, ContractAddr: state => { return state.contractAddr; }, TelikosAddr: state => { return state.telikosAddr; }, Pending: state => { return state.pending }, Messages: state => { return state.messages }, GenesisBlock: state => { return state.genesisBlock; }, } }); window.web3.displayWei = function(wei) { let deci = -1 if(!wei) return "0.0" wei = window.web3.utils.fromWei(wei.toString()) deci = wei.toString().indexOf('.') if(deci == -1 ) return wei deci = Math.min(wei.length, deci+3) return wei.substr(0, deci+1) } window.web3.displayAddr = function(addr) { var output = addr.substr(0, 7) output = output + '...' + output.substr(-5, 5) return output } , new Vue({ store, router, render: h => h(App) }).$mount("#app"); import React from "react" import {Link} from "react-router-dom" function Header() { return ( <header> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/profile">Profile</Link></li> </ul> </header> ) } export default Headerimport React, { Component } from 'react'; // Components import Button from '../../components/Button'; // Local Relatives import styles from './Home.style'; class Home extends Component { render() { const maxGameCodeLength = '5'; return ( <div style={styles.container}> <div style={styles.headingContainer}> <h1 style={styles.headingText}>Huntinator</h1> <h1 style={styles.headingText}>3000</h1> </div> <div style={styles.gameCodeContainer}> <span style={styles.enterGameCodeText}>enter game code</span> <input type="number" name="game_code" style={styles.gameCodeInput} maxLength={maxGameCodeLength} /> </div> <div style={styles.generateBtnContainer}> <Button text={'Generate New Game'} style={styles.generateBtn} onPress={() => alert('button pressed')} /> </div> </div> ); } } export default Home; const crypto = require( 'crypto' ); const generateRandomString = ( length ) => crypto.randomBytes( length ).toString( 'hex' ); const getRootUrlFromEnv = ( envSlug ) => { const envMap = { production: 'https://wordpress.com', local: 'http://calypso.localhost:3000', wpcalypso: 'https://wpcalypso.wordpress.com', }; const resultEnv = envMap[ envSlug ]; return resultEnv ? resultEnv : envMap.production; }; const asyncIf = async ( conditionFunc, ifFunc, elseFunc ) => { try { await conditionFunc(); return await ifFunc(); } catch { if ( elseFunc ) { return await elseFunc(); } } }; module.exports = { asyncIf, generateRandomString, getRootUrlFromEnv, }; <reponame>Li-YangZhong/professional-javascript-for-web-developers function doSomething() { "use strict"; // function body } <gh_stars>100-1000 export const tracking = { h: ".32em", l: ".16em", m: ".18em", s: ".04em", x: ".02em", n: "0" }; export const track = tracking; /** * Given a product slug, return the relative path to single product page */ export const fromProductSlugToUrl = (slug) => `/products/${slug}` <reponame>496Meneses/front-end-Postgrados import React,{useState} from 'react'; import { Formik } from 'formik'; import * as Yup from 'yup'; import {CreateProfessorApi} from './service' import 'bootstrap/dist/css/bootstrap.min.css'; import './hidden.css' import { Box, Button, TextField, Container, Typography, } from '@material-ui/core'; const CreateProfessorView = () => { const [name, setname] = useState("") const [identification, setidentification] = useState() const [lastName, setlastName] = useState("") const [isInternal, setisInternal] = useState("Si") const [age, setage] = useState("") const [departmentI, setdepartmentI] = useState("") //obtener inputs const handleChangeIdentification = (e) =>{ setidentification(e.target.value); } const handleChangeName = (e) =>{ setname(e.target.value); } const handleChangeLastName = (e) =>{ setlastName(e.target.value); } const handleChangeDepartmentI = (e) =>{ setdepartmentI(e.target.value) } const handleChangeIsInternal = (e) =>{ let selecteds = document.getElementById("selectedIsInternal"); setisInternal(selecteds.options[selecteds.selectedIndex].text); console.log(isInternal); if (selecteds.options[selecteds.selectedIndex].text === "No"){ setisInternal(false); } else{ setisInternal(true); } } const handleCreate = () =>{ if(isInternal === "Si"){ setisInternal(1) }else{ setisInternal(0) } CreateProfessorApi({ "cedula": identification, "nombre": name, "apellido": lastName, "es_interno": isInternal }).then((result)=>{ document.getElementById("contenedorProfesor").innerHTML="<div class='alert alert-success' role='alert'>Profesor creado correctamente!</div>"; }).catch(()=>{ document.getElementById("contenedorProfesor").innerHTML="<div class='alert alert-danger' role='alert'>Error!.Verifica los datos!</div>"; }); } const handleSubmit = (event) =>{ handleCreate(); event.preventDefault(); } return( <Container maxWidth="sm"> <Typography color="textPrimary" variant="h2" > Crear Profesor </Typography> <Formik initialValues={{ identification:'', name:'', lastName:'' }} validationSchema={ Yup.object().shape({ identification: Yup.string().max(255).required('Identification is required'), name: Yup.string().max(255).required('Name is required'), lastName: Yup.string().max(255).required('LastName is required'), departmentI: Yup.string().max(255).required('Department is required'), institution: Yup.string().max(255).required('Institutio is required') }) } onSubmit={() => { }} > {({ errors, handleBlur, handleChange, isSubmitting, touched, values }) => ( <> <Box display="flex" flexDirection="column" height="100%" justifyContent="center" > <form onSubmit={handleSubmit}> <Box mb={3}> <TextField error={Boolean(touched.identification && errors.identification)} fullWidth helperText={touched.identification && errors.identification} label="Cedula" margin="normal" name="identification" onBlur={handleBlur} onChange={handleChangeIdentification} type="text" value={values.identification} variant="outlined" /> <TextField error={Boolean(touched.name && errors.name)} fullWidth helperText={touched.name && errors.name} label="Nombre" margin="normal" name="name" onBlur={handleBlur} onChange={handleChangeName} type="text" value={values.name} variant="outlined" /> <TextField error={Boolean(touched.lastName && errors.lastName)} fullWidth helperText={touched.lastName && errors.lastName} label="Apellidos" margin="normal" name="lastName" onBlur={handleBlur} onChange={handleChangeLastName} type="text" value={values.lastName} variant="outlined" /> <div style={{display:'flex', marginTop: '10px', marginBottom: '10px'}}> <Typography color="textPrimary" variant="h6" > ¿Es interno? </Typography> <select style={{marginTop: '0px' , width: '50px', height: '25px', marginLeft:'15px'}} id="selectedIsInternal" onChange={handleChangeIsInternal}> <option value="Si">Si</option> <option value="No">No</option> </select> </div> <span> {isInternal ? ( <div /* Este es el div 1 */ className="redd" > <TextField error={Boolean(touched.departmentI && errors.departmentI)} fullWidth helperText={touched.departmentI && errors.departmentI} label="Departamento de la institucion en la que trabaja" margin="normal" name="departmentI" onBlur={handleBlur} type="text" value={values.departmentI} variant="outlined" /> </div> ) : ( <div /* Este es el div 2 */ className="red2" > <TextField error={Boolean(touched.institution && errors.institution)} fullWidth helperText={touched.institution && errors.institution} label="Institucion a la que pertenece" margin="normal" name="institution" onBlur={handleBlur} type="text" value={values.institution} variant="outlined" /></div> )} </span> <Box my={2}> <Button color="primary" fullWidth size="large" type="submit" variant="contained" > Crear </Button> </Box> </Box> </form> </Box> </>)} </Formik> </Container> ) } export default CreateProfessorView; 'use strict'; const autoprefixer = require('autoprefixer'); const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); const eslintFormatter = require('react-dev-utils/eslintFormatter'); const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); const getClientEnvironment = require('./env'); const paths = require('./paths'); // Webpack uses `publicPath` to determine where the app is being served from. // In development, we always serve from the root. This makes config easier. const publicPath = '/'; const publicUrl = ''; // Get environment variables to inject into our app. const env = getClientEnvironment(publicUrl); // This is the development configuration. // The production configuration is different and lives in a separate file. module.exports = { devtool: 'cheap-module-source-map', // The first two entry points enable "hot" CSS and auto-refreshes for JS. entry: [ require.resolve('./polyfills'), require.resolve('react-dev-utils/webpackHotDevClient'), paths.appIndexJs, ], output: { // Add /* filename */ comments to generated require()s in the output. pathinfo: true, // This does not produce a real file. It's just the virtual path that is // served by WebpackDevServer in development. This is the JS bundle // containing code from all our entry points, and the Webpack runtime. filename: 'static/js/bundle.js', // There are also additional JS chunk files if you use code splitting. chunkFilename: 'static/js/[name].chunk.js', // This is the URL that app is served from. We use "/" in development. publicPath: publicPath, // Point sourcemap entries to original disk location (format as URL on Windows) devtoolModuleFilenameTemplate: info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'), }, resolve: { modules: ['node_modules', paths.appNodeModules].concat( // It is guaranteed to exist because we tweak it in `env.js` process.env.NODE_PATH.split(path.delimiter).filter(Boolean) ), extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx', 'cjsx', 'coffee'], alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web', }, plugins: [ new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]), ], }, module: { strictExportPresence: true, rules: [ // First, run the linter. // It's important to do this before Babel processes the JS. { test: /\.(js|jsx|mjs)$/, enforce: 'pre', use: [ { options: { formatter: eslintFormatter, eslintPath: require.resolve('eslint'), }, loader: require.resolve('eslint-loader'), }, ], include: paths.appSrc, }, { oneOf: [ { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], loader: require.resolve('url-loader'), options: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]', }, }, // Process JS with Babel. { test: /\.(js|jsx|mjs)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { cacheDirectory: true, }, }, { test: /\.css$/, use: [ require.resolve('style-loader'), { loader: require.resolve('css-loader'), options: { importLoaders: 1, }, }, { loader: require.resolve('postcss-loader'), options: { // Necessary for external CSS imports to work // https://github.com/facebookincubator/create-react-app/issues/2677 ident: 'postcss', plugins: () => [ require('postcss-flexbugs-fixes'), autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ], flexbox: 'no-2009', }), ], }, }, ], }, { test: /\.css$/, loaders: ['style', 'css']}, { test: /\.cjsx$/, loaders: ['react-hot', 'coffee', 'cjsx']}, { test: /\.coffee$/, use: 'coffee-loader' }, { exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/], loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[hash:8].[ext]', }, }, ], }, // ** STOP ** Are you adding a new loader? // Make sure to add the new loader(s) before the "file" loader. ], }, plugins: [ // Makes some environment variables available in index.html. // In development, this will be an empty string. new InterpolateHtmlPlugin(env.raw), // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, }), // Add module names to factory functions so they appear in browser profiler. new webpack.NamedModulesPlugin(), new webpack.DefinePlugin(env.stringified), // This is necessary to emit hot updates (currently CSS only): new webpack.HotModuleReplacementPlugin(), // See https://github.com/facebookincubator/create-react-app/issues/240 new CaseSensitivePathsPlugin(), // See https://github.com/facebookincubator/create-react-app/issues/186 new WatchMissingNodeModulesPlugin(paths.appNodeModules), // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), // "url" loader works like "file" loader except that it embeds assets // smaller than specified limit in bytes as data URLs to avoid requests. // A missing `test` is equivalent to a match. ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty', }, performance: { hints: false, }, }; import React from "react"; import {Col, Row, Container} from "../components/Grid"; import Jumbotron from "../components/Jumbotron"; import {Link} from "react-router-dom"; function NoMatch() { return ( <Container fluid> <Row> <Col size="md-12"> <Jumbotron> <h1 className="text-center display-1 font-weight-bold"><span className="ivan">404 Page Not Found</span></h1> <h1 className="text-center display-1"> <span role="img" aria-label="Face With Rolling Eyes Emoji"> 🙄 </span> </h1> <Row> <Link className="btn btn-neutral text-center" to="/" > Go Back Home </Link> </Row> </Jumbotron> </Col> </Row> </Container> ); } export default NoMatch; <reponame>brandoncarl/preschool /** compilers.js Copyright 2016 <NAME> MIT Licensed */ // // Dependencies // var desires = require("desires"), specs = require("./specifications"), byName = {}, byExt = {}, cache = {}, root; /** Loads a processor (templating, transpiler, minification), and standardizes callback to be fn(err, compiled). Defaults to `npm install` packages if they are missing. To disable, set `options.fetch` to `false`; Most packages are referenced by their npm name, common exceptions include: javascript, html, css, es2015, and react. Note that the callback is node style (err, compiled). @param {String} name Name of module (npm install name). @param {Object} options Options include {fetch} and {dir} (install directory). @returns {Function} Processor of format `fn(str, options, next)` @example compilers("typescript") // => fn(str, options, next) for typescript **/ root = module.exports = function(name, options) { // Return cache if available if (cache[name]) return cache[name]; var pipeline = byName[name], syntax = pipeline.syntax, modules; // Set default options options = options || {}; // Optionally fetch modules using `npm install` if (options.fetch || "undefined" === typeof options.fetch) modules = pipeline.modules.map(function(x) { return desires(x, { dir : options.dir }); }); else modules = pipeline.modules.map(function(x) { return require(x); }); // If blank, return if ("" === syntax) { cache[name] = function(str, options, next) { return next(null, str); }; return cache[name]; } // Add core module to beginning (with dot property unless brackets) if (-1 === syntax.indexOf("$0")) syntax = "$0" + (("(" === syntax[0] || "[" === syntax[0]) ? "" : ".") + syntax; // Reinsert modules modules.forEach(function(mod, i) { syntax = syntax.replace(new RegExp("\\$" + i, "g"), "modules[" + i + "]"); }); // While using "eval" is typically considered to be bad form, when calling another function the // performance does not appear suffer in V8. See http://jsperf.com/eval-function-call. // We find that "eval" is slightly faster if (-1 === syntax.indexOf("next)")) if (pipeline.suffix) syntax = "try { next(null," + syntax + pipeline.suffix + "); } catch (err) { next(err); }" else syntax = "try { next(null," + syntax + "); } catch (err) { next(err); }" else if (pipeline.suffix) syntax = syntax.replace("next", "function(err, compiled) { next(err, compiled" + pipeline.suffix + "); }") cache[name] = createFunction(modules, syntax, pipeline.options); return cache[name]; }; /** Returns the default pipeline for an extension. Leading "." is removed. @param {String} ext The file extension. @returns {String} Name of the default pipeline. @example compilers.defaultCompilerForExtension("ts"); // => "typescript" **/ root.defaultCompilerForExtension = function(ext) { return byExt[ext.replace(/^\./, "")]; }; // // Helpers // // Wraps function to ensure proper polymorphism. We could use a library // like "reorg", but we code manually given simplicity and desire for performance. // `context` refers to local variables while `options` referes to compiler options function createFunction(modules, syntax, options) { var fn = new Function("modules", "str", "context", "options", "next", syntax); options = options || {}; return function(str, context, next) { if ("function" === typeof context) { next = context; context = {}; } fn(modules, str, context, options, next); }; } // Ensure our configurations are properly formatted specs.forEach(parseSpecification); // Creates byName and byExt dictionaries, and ensures that specification is // in the correct format. function parseSpecification(spec) { // Create dictionary by name byName[spec.name] = spec; // Insert modules if missing spec.modules = spec.modules || []; // Expand extensions if (!Array.isArray(spec.ext)) spec.ext = [spec.ext]; // Create dictionary by extension spec.ext.forEach(function(ext) { if (!byExt[ext]) byExt[ext] = spec.name; }); } <filename>server.js const express = require('express') const bodyParser = require('body-parser') const multer = require('multer') const app = express() const path = require('path') app.use(bodyParser.urlencoded({extended:true})) //armazenando no disco const armazenamento = multer.diskStorage({ destination:(req,file,callBack)=>{ callBack(null, true) }, filename:(req,file,callBack)=>{ //Nome do arquivo + data agora + extensao let a = file.fieldname+'-'+Date.now()+path.extname(file.originalname) callBack(null,file.fieldname+'-'+Date.now()+path.extname(file.originalname)) console.log( a) } }) const upload = multer({armazenamento}) //rota padrao app.get('/',(req,res)=>{ res.sendFile(__dirname + "/index.html") }) //rota reposável pelo upload do arquivo app.post('/upload', upload.single('arquivo'),(req, res, next)=>{ const file = req.file res.send(file) if (!file) { const error = new Error('Favor selecionar um arquivo') error.httpStatusCode = 400 return next(error) }else{ console.log("Ok") } }) app.listen(3000,'127.0.0.1',()=>{ console.log('server running...') })"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var t = require("io-ts"); var NumberFromString_1 = require("./NumberFromString"); exports.IntegerFromString = t.refinement(NumberFromString_1.NumberFromString, t.Integer.predicate, 'IntegerFromString'); //# sourceMappingURL=IntegerFromString.js.map<gh_stars>10-100 #!/usr/bin/env node "use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); var fs = __importStar(require("fs")); var builders_1 = require("./builders"); var child_process_1 = require("child_process"); var logSymbols = require('log-symbols'); var validate = require("validate-npm-package-name"); var qoa = require('qoa'); var log = console.log; log('Welcome to the Discord Bot Creator !'); var questions = [ { type: 'input', query: 'What will be your bot\'s name ?', handle: 'botName' }, { type: 'secure', query: 'Enter your Discord\'s token (press enter for empty)', handle: 'token' } ]; qoa.prompt(questions).then(function (answer) { var validated = validate(answer.botName); if (validated.errors !== undefined) { validated.errors.forEach(function (error) { log(logSymbols.error + " " + error); }); return; } var dir = answer.botName; if (!fs.existsSync(dir)) { fs.mkdirSync(dir); log(logSymbols.info + " Creating new folder..."); fs.writeFile(dir + "/package.json", builders_1.getPackage(dir), function (err) { if (err) return log(logSymbols.error + " Error at creating package.json"); }); log(logSymbols.info + " Creating bot.js..."); fs.writeFile(dir + "/bot.js", builders_1.getScript(answer.token, dir), function (err) { if (err) return log(logSymbols.error + " Error at bot.js creation"); }); log(logSymbols.info + " Generating .gitignore..."); fs.writeFile(dir + "/.gitignore", builders_1.getGitignore(), function (err) { if (err) return log(logSymbols.error + " Error at .gitignore creation"); }); log(logSymbols.info + " Writing README.md..."); fs.writeFile(dir + "/README.md", builders_1.getReadme(dir), function (err) { if (err) return log(logSymbols.error + " Error at README creation"); }); log(logSymbols.info + " Installing dependencies..."); child_process_1.exec("cd " + dir + " && npm install", function (err, stdout, stderr) { log(logSymbols.success + " Done!"); }); } }); //# sourceMappingURL=cli.js.map<filename>src/lqc/generate/web_page/ui_tools/template.js // UI Tools - Javascript <filename>apis/conversion/src/helpers/__tests__/index.spec.js /* eslint-disable no-param-reassign */ import helpers from '../index'; describe('restoreChangedProperties', () => { it('should restore changed properties correctly', async () => { const properties = { prop1: 1, prop2: 222, qLayoutExclude: { changed: { prop1: { to: 1, from: 11, }, prop2: { to: 2, from: 22, }, prop3: { to: 3, from: 33, }, }, }, }; helpers.restoreChangedProperties(properties); expect(properties).to.deep.equal({ prop1: 11, prop2: 222, qLayoutExclude: { changed: { prop1: { to: 1, from: 11, }, prop2: { to: 2, from: 22, }, prop3: { to: 3, from: 33, }, }, }, }); }); }); describe('isMasterItemProperty', () => { it('should return true for qMetaDef', () => { expect(helpers.isMasterItemProperty('qMetaDef')).to.equal(true); }); it('should return true for descriptionExpression', () => { expect(helpers.isMasterItemProperty('descriptionExpression')).to.equal(true); }); it('should return true for labelExpression', () => { expect(helpers.isMasterItemProperty('labelExpression')).to.equal(true); }); it('should return false for everything else', () => { expect(helpers.isMasterItemProperty('qMetaDef1')).to.equal(false); expect(helpers.isMasterItemProperty('descriptionExpression1')).to.equal(false); expect(helpers.isMasterItemProperty('labelExpression1')).to.equal(false); expect(helpers.isMasterItemProperty('abc')).to.equal(false); }); }); describe('importCommonProperties', () => { let newProperties; let exportFormat; let initialProperties; describe('visualization', () => { beforeEach(() => { newProperties = {}; exportFormat = {}; initialProperties = { visualization: 'some visualization', }; }); it('should copy visualization correctly', () => { helpers.importCommonProperties(newProperties, exportFormat, initialProperties); expect(newProperties.visualization).to.equal('some visualization'); }); }); describe('qType', () => { beforeEach(() => { newProperties = {}; exportFormat = {}; initialProperties = { qInfo: { qType: 'some type' }, }; }); it('should set qType correctly if it is not a master object', () => { helpers.importCommonProperties(newProperties, exportFormat, initialProperties); expect(newProperties.qInfo.qType).to.equal('some type'); }); it('should set qType correctly if it is a master object', () => { exportFormat.properties = { qInfo: { qType: 'masterobject' } }; helpers.importCommonProperties(newProperties, exportFormat, initialProperties); expect(newProperties.qInfo.qType).to.equal('masterobject'); }); }); }); describe('copyPropertyIfExist', () => { let source; let target; beforeEach(() => { source = { prop1: 1, prop2: 2, prop3: undefined, }; target = { prop1: 10, prop3: 30, prop4: 40, }; }); it('should copy property if it exists in source to target', () => { helpers.copyPropertyIfExist('prop1', source, target); helpers.copyPropertyIfExist('prop2', source, target); helpers.copyPropertyIfExist('prop3', source, target); helpers.copyPropertyIfExist('prop4', source, target); helpers.copyPropertyIfExist('prop5', source, target); expect(target).to.deep.equal({ prop1: 1, prop2: 2, prop3: undefined, prop4: 40, }); }); }); describe('copyPropertyOrSetDefault', () => { let source; let target; beforeEach(() => { source = { prop1: 1, prop2: 2, prop3: undefined, }; target = { prop1: 10, prop3: 30, prop4: 40, }; }); it('should copy property if it exists in source to target, otherwise set to default', () => { helpers.copyPropertyOrSetDefault('prop1', source, target); helpers.copyPropertyOrSetDefault('prop2', source, target); helpers.copyPropertyOrSetDefault('prop3', source, target); helpers.copyPropertyOrSetDefault('prop4', source, target); helpers.copyPropertyOrSetDefault('prop5', source, target); helpers.copyPropertyOrSetDefault('prop6', source, target, 60); expect(target).to.deep.equal({ prop1: 1, prop2: 2, prop3: undefined, prop4: undefined, prop5: undefined, prop6: 60, }); }); }); describe('createDefaultDimension', () => { let dimensionDef; let dimensionProperties; beforeEach(() => { dimensionDef = { prop1: 1, prop2: 2, }; dimensionProperties = { prop1: 10, prop3: 30, }; }); it('should add default values if there is no qOtherTotalSpec and othersLabel', () => { const def = helpers.createDefaultDimension(dimensionDef, dimensionProperties); expect(def).to.deep.equal({ prop1: 1, prop2: 2, prop3: 30, qOtherTotalSpec: { qOtherCounted: { qv: '10' }, qOtherLimit: { qv: '0' }, }, othersLabel: 'Others', }); }); it('should keep othersLabel', () => { dimensionProperties.othersLabel = 'some label'; const def = helpers.createDefaultDimension(dimensionDef, dimensionProperties); expect(def).to.deep.equal({ prop1: 1, prop2: 2, prop3: 30, qOtherTotalSpec: { qOtherCounted: { qv: '10' }, qOtherLimit: { qv: '0' }, }, othersLabel: 'some label', }); }); it('should keep qOtherCounted', () => { dimensionProperties.qOtherTotalSpec = { qOtherCounted: { qv: '20' } }; const def = helpers.createDefaultDimension(dimensionDef, dimensionProperties); expect(def).to.deep.equal({ prop1: 1, prop2: 2, prop3: 30, qOtherTotalSpec: { qOtherCounted: { qv: '20' }, qOtherLimit: { qv: '0' }, }, othersLabel: 'Others', }); }); it('should keep qOtherLimit', () => { dimensionProperties.qOtherTotalSpec = { qOtherLimit: { qv: '30' } }; const def = helpers.createDefaultDimension(dimensionDef, dimensionProperties); expect(def).to.deep.equal({ prop1: 1, prop2: 2, prop3: 30, qOtherTotalSpec: { qOtherCounted: { qv: '10' }, qOtherLimit: { qv: '30' }, }, othersLabel: 'Others', }); }); it('should keep qOtherCounted, qOtherLimit, and othersLabel', () => { dimensionProperties.othersLabel = 'some label'; dimensionProperties.qOtherTotalSpec = { qOtherCounted: { qv: '20' }, qOtherLimit: { qv: '30' }, }; const def = helpers.createDefaultDimension(dimensionDef, dimensionProperties); expect(def).to.deep.equal({ prop1: 1, prop2: 2, prop3: 30, qOtherTotalSpec: { qOtherCounted: { qv: '20' }, qOtherLimit: { qv: '30' }, }, othersLabel: 'some label', }); }); }); describe('createDefaultMeasure', () => { let measureDef; let measureProperties; beforeEach(() => { measureDef = { prop1: 1, prop2: 2, }; measureProperties = { prop1: 10, prop3: 30, }; }); it('should create default measure correctly', () => { const def = helpers.createDefaultMeasure(measureDef, measureProperties); expect(def).to.deep.equal({ prop1: 1, prop2: 2, prop3: 30, }); }); }); describe('resolveValue', () => { let data; let input; beforeEach(() => { data = (a) => a * 2; input = 5; }); it('should resolve value correctly if data is a function', () => { expect(helpers.resolveValue(data, input)).to.equal(10); expect(helpers.resolveValue(data, input, 100)).to.equal(10); }); it('should resolve value correctly if data is a number', () => { data = 20; expect(helpers.resolveValue(data, input)).to.equal(20); expect(helpers.resolveValue(data, input, 100)).to.equal(20); }); it('should resolve value correctly if data is not a function or not a number', () => { expect(helpers.resolveValue(NaN, input)).to.equal(undefined); expect(helpers.resolveValue(NaN, input, 100)).to.equal(100); expect(helpers.resolveValue('a', input)).to.equal(undefined); expect(helpers.resolveValue('a', input, 100)).to.equal(100); }); }); describe('getHypercubePath', () => { let qae; beforeEach(() => { qae = { data: { targets: [{ propertyPath: '/qHyperCubeDef' }] }, }; }); it('should return to empty string if propertyPath = "/qHyperCubeDef"', () => { expect(helpers.getHypercubePath(qae)).to.equal(''); }); it('should return to the part before /qHyperCubeDef', () => { qae.data.targets[0].propertyPath = 'boxPlotDef/qHyperCubeDef'; expect(helpers.getHypercubePath(qae)).to.equal('boxPlotDef'); }); it('should return to the part before /qHyperCubeDef and replace / by .', () => { qae.data.targets[0].propertyPath = 'boxPlotDef/point/qHyperCubeDef'; expect(helpers.getHypercubePath(qae)).to.equal('boxPlotDef.point'); }); }); describe('getDefaultDimension', () => { it('should return correct default dimension', () => { expect(helpers.getDefaultDimension()).to.deep.equal({ qDef: { autoSort: true, cId: '', othersLabel: 'Others', }, qLibraryId: '', qNullSuppression: false, qOtherLabel: 'Others', qOtherTotalSpec: { qOtherLimitMode: 'OTHER_GE_LIMIT', qOtherMode: 'OTHER_OFF', qOtherSortMode: 'OTHER_SORT_DESCENDING', qSuppressOther: false, }, }); }); }); describe('getDefaultMeasure', () => { it('should return correct default measure', () => { expect(helpers.getDefaultMeasure()).to.deep.equal({ qDef: { autoSort: true, cId: '', numFormatFromTemplate: true, }, qLibraryId: '', qTrendLines: [], }); }); }); describe('setInterColumnSortOrder', () => { let exportFormat; let newHyperCubeDef; beforeEach(() => { exportFormat = { data: [ { interColumnSortOrder: [1, 0, 2], }, ], }; newHyperCubeDef = { qDimensions: [{}], qMeasures: [{}, {}], }; }); it('should set correct qInterColumnSortOrder when its size match the number of dimensions and measures', () => { helpers.setInterColumnSortOrder({ exportFormat, newHyperCubeDef }); expect(newHyperCubeDef).to.deep.equal({ qDimensions: [{}], qMeasures: [{}, {}], qInterColumnSortOrder: [1, 0, 2], }); }); it('should set correct qInterColumnSortOrder when its size is bigger than the number of dimensions and measures', () => { exportFormat.data[0].interColumnSortOrder = [0, 3, 2, 1]; helpers.setInterColumnSortOrder({ exportFormat, newHyperCubeDef }); expect(newHyperCubeDef).to.deep.equal({ qDimensions: [{}], qMeasures: [{}, {}], qInterColumnSortOrder: [0, 2, 1], }); }); it('should set correct qInterColumnSortOrder when its size is smaller than the number of dimensions and measures', () => { exportFormat.data[0].interColumnSortOrder = [0, 1]; helpers.setInterColumnSortOrder({ exportFormat, newHyperCubeDef }); expect(newHyperCubeDef).to.deep.equal({ qDimensions: [{}], qMeasures: [{}, {}], qInterColumnSortOrder: [0, 1, 2], }); }); it('should set correct qInterColumnSortOrder when its size is smaller than the number of dimensions and measures, and the interColumnSortOrder is not sorted', () => { exportFormat.data[0].interColumnSortOrder = [0, 2, 1]; newHyperCubeDef.qMeasures = [{}, {}, {}]; helpers.setInterColumnSortOrder({ exportFormat, newHyperCubeDef }); expect(newHyperCubeDef).to.deep.equal({ qDimensions: [{}], qMeasures: [{}, {}, {}], qInterColumnSortOrder: [0, 2, 1, 3], }); }); }); describe('createNewProperties', () => { let exportFormat; let initialProperties; describe('No hypercubePath', () => { describe('No exportFormat.properties', () => { describe('No initialProperties', () => { beforeEach(() => { exportFormat = { properties: {}, }; initialProperties = {}; }); it('should return correct outcome', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {} }, }); }); }); describe('Have initialProperties', () => { beforeEach(() => { exportFormat = { properties: {}, }; initialProperties = { prop1: 1, }; }); it('should return correct outcome if initialProperties have no components', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {} }, prop1: 1, }); }); it('should return correct outcome if initialProperties have components', () => { initialProperties.components = [1, 2]; const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {} }, prop1: 1, components: [1, 2], }); }); it('should return correct outcome if initialProperties have components as null', () => { initialProperties.components = null; const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {} }, prop1: 1, components: [], }); }); }); }); describe('Have exportFormat.properties', () => { describe('No initialProperties', () => { describe('qLayoutExclude', () => { beforeEach(() => { exportFormat = { properties: { qLayoutExclude: { prop1: 1, }, }, }; initialProperties = {}; }); it('should return correct outcome if there is no qLayoutExclude.quarantine', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {} }, }); }); it('should return correct outcome if there is qLayoutExclude.quarantine', () => { exportFormat.properties.qLayoutExclude.quarantine = { prop2: 2, prop3: 3 }; const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: { prop2: 2, prop3: 3 } }, }); }); }); describe('qHyperCubeDef', () => { beforeEach(() => { exportFormat = { properties: { qHyperCubeDef: { prop1: 1, }, }, }; initialProperties = {}; }); it('should return correct outcome', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: { qHyperCubeDef: { prop1: 1, }, }, quarantine: {}, }, }); }); }); describe('master item propperty', () => { beforeEach(() => { exportFormat = { properties: { qMetaDef: { prop1: 1, }, descriptionExpression: { prop2: 2, }, labelExpression: { prop3: 3, }, }, }; initialProperties = {}; }); it('should return correct outcome', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {}, }, qMetaDef: { prop1: 1, }, descriptionExpression: { prop2: 2, }, labelExpression: { prop3: 3, }, }); }); }); describe('other propperties', () => { beforeEach(() => { exportFormat = { properties: { prop1: { prop11: 11, }, }, }; initialProperties = {}; }); it('should return correct outcome', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: { prop1: { prop11: 11, }, }, quarantine: {}, }, }); }); }); }); describe('Have initialProperties', () => { describe('qLayoutExclude', () => { beforeEach(() => { exportFormat = { properties: { qLayoutExclude: { prop1: 1, }, }, }; initialProperties = { prop100: 100, }; }); it('should return correct outcome if there is no qLayoutExclude.quarantine', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {} }, prop100: 100, }); }); it('should return correct outcome if there is qLayoutExclude.quarantine', () => { exportFormat.properties.qLayoutExclude.quarantine = { prop2: 2, prop3: 3 }; const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: { prop2: 2, prop3: 3 } }, prop100: 100, }); }); }); describe('qHyperCubeDef', () => { beforeEach(() => { exportFormat = { properties: { qHyperCubeDef: { prop1: 1, }, }, }; initialProperties = { prop100: 100, }; }); it('should return correct outcome if there is no initialProperties.qHyperCubeDef', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: { qHyperCubeDef: { prop1: 1, }, }, quarantine: {}, }, prop100: 100, }); }); it('should return correct outcome if there is initialProperties.qHyperCubeDef', () => { initialProperties.qHyperCubeDef = { prop1: 10, prop2: 20 }; const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {}, }, qHyperCubeDef: { prop1: 1, prop2: 20, }, prop100: 100, }); }); }); describe('master item propperty', () => { beforeEach(() => { exportFormat = { properties: { qMetaDef: { prop1: 1, }, descriptionExpression: { prop2: 2, }, labelExpression: { prop3: 3, }, }, }; initialProperties = { prop100: 100, }; }); it('should return correct outcome', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {}, }, qMetaDef: { prop1: 1, }, descriptionExpression: { prop2: 2, }, labelExpression: { prop3: 3, }, prop100: 100, }); }); }); describe('other propperties', () => { beforeEach(() => { exportFormat = { properties: { prop1: { prop11: 11, }, prop2: { prop21: 11, }, }, }; initialProperties = { prop1: 1, prop3: 3, }; }); it('should return correct outcome', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: { prop2: { prop21: 11, }, }, quarantine: {}, }, prop1: { prop11: 11, }, prop3: 3, }); }); }); }); }); }); describe('Have 1-step hypercubePath', () => { let hypercubePath; describe('qHyperCubeDef', () => { beforeEach(() => { exportFormat = { properties: { qHyperCubeDef: { prop1: 1, }, }, }; initialProperties = {}; hypercubePath = 'boxplotDef'; }); it('should return correct outcome if there is no initialProperties.qHyperCubeDef', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties, hypercubePath }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {}, }, boxplotDef: { qHyperCubeDef: { prop1: 1, }, }, }); }); it('should return correct outcome if there is initialProperties.qHyperCubeDef', () => { initialProperties.qHyperCubeDef = { prop1: 10, prop2: 20 }; const newProperties = helpers.createNewProperties({ exportFormat, initialProperties, hypercubePath }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {}, }, qHyperCubeDef: { prop1: 10, prop2: 20, }, boxplotDef: { qHyperCubeDef: { prop1: 1, }, }, }); }); }); }); describe('Have 2-step hypercubePath', () => { let hypercubePath; describe('qHyperCubeDef', () => { beforeEach(() => { exportFormat = { properties: { qHyperCubeDef: { prop1: 1, }, }, }; initialProperties = {}; hypercubePath = 'somePath.boxplotDef'; }); it('should return correct outcome if there is no initialProperties.qHyperCubeDef', () => { const newProperties = helpers.createNewProperties({ exportFormat, initialProperties, hypercubePath }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {}, }, somePath: { boxplotDef: { qHyperCubeDef: { prop1: 1, }, }, }, }); }); it('should return correct outcome if there is initialProperties.qHyperCubeDef', () => { initialProperties.qHyperCubeDef = { prop1: 10, prop2: 20 }; const newProperties = helpers.createNewProperties({ exportFormat, initialProperties, hypercubePath }); expect(newProperties).to.deep.equal({ qLayoutExclude: { disabled: {}, quarantine: {}, }, qHyperCubeDef: { prop1: 10, prop2: 20, }, somePath: { boxplotDef: { qHyperCubeDef: { prop1: 1, }, }, }, }); }); }); }); }); describe('getMaxMinDimensionMeasure', () => { let exportFormat; let dataDefinition; beforeEach(() => { exportFormat = { data: [ { dimensions: [], }, ], }; dataDefinition = {}; }); it('should return correct values if there is no dataDefinition', () => { const result = helpers.getMaxMinDimensionMeasure({ exportFormat, dataDefinition }); expect(result).to.deep.equal({ maxDimensions: 0, minDimensions: 0, maxMeasures: 0, minMeasures: 0, }); }); it('should return correct values if there is max, min are numbers', () => { dataDefinition = { dimensions: { max: 2, min: 1 }, measures: { max: 10, min: 0 }, }; const result = helpers.getMaxMinDimensionMeasure({ exportFormat, dataDefinition }); expect(result).to.deep.equal({ maxDimensions: 2, minDimensions: 1, maxMeasures: 10, minMeasures: 0, }); }); it('should return correct values if there is max, min are functions without parameter', () => { dataDefinition = { dimensions: { max: () => 2, min: () => 1 }, measures: { max: () => 10, min: () => 0 }, }; const result = helpers.getMaxMinDimensionMeasure({ exportFormat, dataDefinition }); expect(result).to.deep.equal({ maxDimensions: 2, minDimensions: 1, maxMeasures: 10, minMeasures: 0, }); }); it('should return correct values if there is max, min are functions with parameter', () => { dataDefinition = { dimensions: { max: (x) => x + 4, min: (x) => x + 2 }, measures: { max: (x) => x + 3, min: (x) => x + 1 }, }; exportFormat.data[0].dimensions.length = 2; const result = helpers.getMaxMinDimensionMeasure({ exportFormat, dataDefinition }); expect(result).to.deep.equal({ maxDimensions: 9, minDimensions: 5, maxMeasures: 5, minMeasures: 3, }); }); }); describe('shouldInitLayoutExclude', () => { let exportFormat; let maxDimensions; let minDimensions; let maxMeasures; let minMeasures; beforeEach(() => { exportFormat = { data: [ { dimensions: [], measures: [], excludedDimensions: [], excludedMeasures: [], }, ], }; maxDimensions = 0; minDimensions = 0; maxMeasures = 0; minMeasures = 0; }); describe('maxDimensions = 0', () => { beforeEach(() => { maxDimensions = 0; }); it('should return false if dimensions.length = 0', () => { expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return true if dimensions.length > 0', () => { exportFormat.data[0].dimensions.length = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(true); }); }); describe('maxDimensions > 0', () => { beforeEach(() => { maxDimensions = 3; }); it('should return false if dimensions.length < maxDimensions', () => { exportFormat.data[0].dimensions.length = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if dimensions.length = maxDimensions', () => { exportFormat.data[0].dimensions.length = 3; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if dimensions.length > maxDimensions', () => { exportFormat.data[0].dimensions.length = 4; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(true); }); }); describe('maxMeasures = 0', () => { beforeEach(() => { maxMeasures = 0; }); it('should return false if measures.length = 0', () => { expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return true if measures.length > 0', () => { exportFormat.data[0].measures.length = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(true); }); }); describe('maxMeasures > 0', () => { beforeEach(() => { maxMeasures = 3; }); it('should return false if measures.length < maxMeasures', () => { exportFormat.data[0].measures.length = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if measures.length = maxMeasures', () => { exportFormat.data[0].measures.length = 3; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if measures.length > maxMeasures', () => { exportFormat.data[0].measures.length = 4; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(true); }); }); describe('dimensions.length <= maxDimensions and excludedDimensions.length = 0', () => { beforeEach(() => { maxDimensions = 4; minDimensions = 2; exportFormat.data[0].excludedDimensions.length = 0; }); it('should return false if dimensions.length < minDimensions', () => { exportFormat.data[0].dimensions.length = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if dimensions.length = minDimensions', () => { exportFormat.data[0].dimensions.length = 2; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if dimensions.length > minDimensions', () => { exportFormat.data[0].dimensions.length = 3; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if dimensions.length = maxDimensions and > minDimensions', () => { exportFormat.data[0].dimensions.length = 4; minDimensions = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); }); describe('dimensions.length <= maxDimensions and excludedDimensions.length > 0', () => { beforeEach(() => { maxDimensions = 5; minDimensions = 3; exportFormat.data[0].excludedDimensions.length = 1; }); it('should return false if dimensions.length + excludedDimensions.length < minDimensions', () => { exportFormat.data[0].dimensions.length = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if dimensions.length + excludedDimensions.length = minDimensions', () => { exportFormat.data[0].dimensions.length = 2; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if dimensions.length + excludedDimensions.length > minDimensions', () => { exportFormat.data[0].dimensions.length = 3; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(true); }); it('should return false if dimensions.length = maxDimensions and > minDimensions', () => { exportFormat.data[0].dimensions.length = 5; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(true); }); }); describe('measures.length <= maxMeasures and excludedMeasures.length = 0', () => { beforeEach(() => { maxMeasures = 4; minMeasures = 2; exportFormat.data[0].excludedMeasures.length = 0; }); it('should return false if measures.length < minMeasures', () => { exportFormat.data[0].measures.length = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if measures.length = minMeasures', () => { exportFormat.data[0].measures.length = 2; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if measures.length > minMeasures', () => { exportFormat.data[0].measures.length = 3; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if measures.length = maxMeasures and > minMeasures', () => { exportFormat.data[0].measures.length = 4; minMeasures = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); }); describe('measures.length <= maxMeasures and excludedMeasures.length > 0', () => { beforeEach(() => { maxMeasures = 5; minMeasures = 3; exportFormat.data[0].excludedMeasures.length = 1; }); it('should return false if measures.length + excludedMeasures.length < minMeasures', () => { exportFormat.data[0].measures.length = 1; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if measures.length + excludedMeasures.length = minMeasures', () => { exportFormat.data[0].measures.length = 2; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(false); }); it('should return false if measures.length + excludedMeasures.length > minMeasures', () => { exportFormat.data[0].measures.length = 3; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(true); }); it('should return false if measures.length = maxMeasures and > minMeasures', () => { exportFormat.data[0].measures.length = 5; expect( helpers.shouldInitLayoutExclude({ exportFormat, maxDimensions, minDimensions, maxMeasures, minMeasures }) ).to.equal(true); }); }); }); describe('updateDimensionsOnAdded', () => { let newProperties; let dataDefinition; let added; beforeEach(() => { newProperties = { qHyperCubeDef: { qDimensions: [ { qDef: {}, }, { qDef: {}, }, ], }, }; added = ({ qDef }, properties) => { qDef.xyz = properties.qHyperCubeDef.qDimensions.length * 10; }; dataDefinition = { dimensions: { added } }; }); it('should update dimensions correctly if there is added function', () => { helpers.updateDimensionsOnAdded({ newProperties, dataDefinition }); expect(newProperties.qHyperCubeDef.qDimensions).to.deep.equal([ { qDef: { xyz: 10 }, }, { qDef: { xyz: 20 }, }, ]); }); it('should do nothing if there is no added function', () => { dataDefinition.dimensions.added = undefined; helpers.updateDimensionsOnAdded({ newProperties, dataDefinition }); expect(newProperties.qHyperCubeDef.qDimensions).to.deep.equal([ { qDef: {}, }, { qDef: {}, }, ]); }); }); describe('updateMeasuresOnAdded', () => { let newProperties; let dataDefinition; let added; beforeEach(() => { newProperties = { qHyperCubeDef: { qMeasures: [ { qDef: {}, }, { qDef: {}, }, ], }, }; added = ({ qDef }, properties) => { qDef.xyz = properties.qHyperCubeDef.qMeasures.length * 10; }; dataDefinition = { measures: { added } }; }); it('should update measures correctly if there is added function', () => { helpers.updateMeasuresOnAdded({ newProperties, dataDefinition }); expect(newProperties.qHyperCubeDef.qMeasures).to.deep.equal([ { qDef: { xyz: 10 }, }, { qDef: { xyz: 20 }, }, ]); }); it('should do nothing if there is no added function', () => { dataDefinition.measures.added = undefined; helpers.updateMeasuresOnAdded({ newProperties, dataDefinition }); expect(newProperties.qHyperCubeDef.qMeasures).to.deep.equal([ { qDef: {}, }, { qDef: {}, }, ]); }); }); <gh_stars>0 exports.cmd = new Mage.Command("autogreen", async message => { if (!message.args[0]) return; if (message.args[0] == "true" || message.args[0] == "on") { Magic.autoGreen = true; message.channel.createMessage("AutoGreen has been enabled."); } else if (message.args[0] == "false" || message.args[0] == "off") { Magic.autoGreen = false; message.channel.createMessage("AutoGreen has been disabled."); } }, { guildOnly: true, type: "default", description: "Mage creates a greentext version of non-greentext'd text, if that makes sense.", args: [{ type: "string", label: "on/off", }] }); <filename>tests/useApi.test.js<gh_stars>1-10 import useApi from '@/composites/useApi.ts'; describe('useApi', () => { const unmockedFetch = global.fetch; beforeAll(() => { global.fetch = () => Promise.resolve({ json: () => Promise.resolve([]) }) }) afterAll(() => { global.fetch = unmockedFetch; }) it('should create correct url from params', () => { const fetchMock = jest .spyOn(global, 'fetch') .mockImplementation(() => Promise.resolve({ json: () => Promise.resolve([]) }) ) const props = { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ e: 'f' }) } const api = { url: 'http://testing.com', params: { a: 'b', c: 'd' }, ...props } useApi(api); expect(fetchMock).toHaveBeenCalledWith( 'http://testing.com?a=b&c=d', { ...props, method: 'GET' } ) global.fetch.mockClear(); delete global.fetch; }) }) <reponame>JaneHazen/TicTacToes<gh_stars>0 function startGame(){ for(var i = 1; i <= 9; i++){ clearBox(i); } document.turn = "X"; document.winner = null; document.message = changeMessage(document.turn + ", you start") } function newMove(square){ if(document.winner != null){ changeMessage("Stoppit! " + document.turn + " already won!") }else if (square.innerText == ""){ square.innerText = document.turn; switchPlayer(); } else { changeMessage("Find an empty space!") } } function switchPlayer(){ if(checkForWinner(document.turn)) { changeMessage("You're a Winner, " + document.turn + "!") document.winner = document.turn; } else if(document.turn == "X"){ document.turn = "O"; changeMessage("Now it's your turn, " + document.turn + "!") } else { document.turn = "X"; changeMessage("Now it's your turn, " + document.turn + "!") } } function changeMessage(msg){ document.getElementById("message").innerText = msg } function checkForWinner(move){ var gameOver = false; if (checkRow(1,2,3, move) || checkRow(4, 5, 6, move) || checkRow(7, 8, 9, move) || checkRow(1, 4, 7, move) || checkRow(2, 5, 8, move) || checkRow(3, 6, 9, move) || checkRow(1, 5, 9, move) || checkRow(3, 5, 7, move) ) { gameOver = true; } return gameOver } function checkRow(a, b, c, move){ var gameOver = false; if (getSquare(a) == move && getSquare(b) == move && getSquare(c) == move){ gameOver = true; } return gameOver; } function getSquare(number){ return document.getElementById("s" + number).innerText; } function clearBox(number){ document.getElementById("s" + number).innerText = ""; }const mongoose = require('mongoose'); const BusinessSeriviceSchema = mongoose.Schema({ createdAt : {type :Date, default : Date.now()}, title : {type : String, default : ""}, subtitle : {type : String, default : ""}, description : {type : String, default : ""}, imageUrl : {type : String, default : ""}, active : {type : Boolean, default : true}, removed : {type : Boolean, default : false}, }) const BusinessSchema = mongoose.Schema({ createdAt : {type : Date, default : Date.now()}, userId : {type : mongoose.Types.ObjectId, ref: "Users"}, name : {type : String, default : "", required : true, minLength : 3, maxLength : 255}, mobile : {type : String, default : "", min : 10, max :15}, mobileVerified : {type : Boolean, default : false}, email : {type : String, default : "", lowercase : true}, emailVerified : {type : Boolean, default : false}, website : {type : String, default : ""}, description : {type : String, default : ""}, yearStarted : {type : String, default : ""}, noOfEmployees : {type : String, default : ""}, licenceNo : {type : String, default : ""}, registrationNo : {type : String, default : ""}, hourlyRate : {type : String, default : ""}, businessHours : {type : String, default : ""}, categoryIds : {type : mongoose.Types.ObjectId, ref : "Categories"}, subcategoryIds : [{type : mongoose.Types.ObjectId, ref : "Subcategories"}], information : {type : String, default : ""}, address : {type : String, default : ""}, addressLine2 : {type : String, default : ""}, latitude : {type : String, default : ""}, longitude : {type : String, default : ""}, country : {type : String, default : ""}, state : {type : String, default : ""}, city : {type : String, default : ""}, pin : {type : String, default : ""}, workingRadius : {type : Number, default : ""}, showReimbursement : {type : Boolean, default : true}, lateFee : {type : Boolean, default : true}, moneyBack : {type : Boolean, default : true}, serviceInsured : {type : Boolean, default : false}, indentityDoc : [{url : {type : String, default : ""}, verified : {type : Boolean, default : false}}], addressDoc : [{url : {type : String, default : ""}, verified : {type : Boolean, default : false}}], registrationDoc : [{url : {type : String, default : ""}, verified : {type : Boolean, default : false}}], policeVerificationDoc : [{url : {type : String, default : ""}, verified : {type : Boolean, default : false}}], otherDoc : [{url : {type : String, default : ""}, verified : {type : Boolean, default : false}}], logoImg : {type : String, default : ""}, bannerImg : {type : String, default : ""}, workFiles : {type : Array, default : []}, businessType : {type : String, default : ""}, businessServices : [BusinessSeriviceSchema], profileStatus : {type : Number, default : 0}, profileStrength : {type : Number, default : 0}, profileStrengthData : {type : Array, default : []}, activePlan : {type : mongoose.Types.ObjectId, ref : "Plans"}, active : {type : Boolean, default : true}, adminVerified : {type : Boolean, default : false}, }); BusinessSchema.set('toObject', { virtuals: true }); BusinessSchema.set('toJSON', { virtuals: true }); const Businesses = mongoose.model("Businesses", BusinessSchema); module.exports = Businesses;<reponame>zboboan/PlasmaStationManagemen export default { route: { dashboard: 'Dashboard', fileOper:'档案管理Y', fileOperWeixi:'档案管理/包括微信绑定Y', releaseOperation:'发布管理Y', licenceOperation:'证照管理Y', recruitmentOperation:'招募人管理Y', registration:'登记管理Y', addArrivals:'进站登记Y', chartered:'包车管理Y', indexedRecord:'指标检查Y', health:'健康检查Y', consultation:'健康征询Y', physical:'体格检查Y', Xlight:'X光胸片Y', ecg:'心电图Y', noninvasive:'无创血红蛋白Y', specimen:'样本采集Y', collector:'样本采集Y', sampleHandover:'样本交接Y', handOver:'样本移交Y', receive:'样本接收Y', registrat:'样本登记Y', bloodTests:'血液检查Y', refuseInfo:'拒绝信息发布Y', bloodCheck:'血样检查Y', plasmaCheck:'浆样检查Y', plasmaRefused:'浆站拒绝Y', positiveFeed:'检疫期阳性反馈Y', plasmaManagement:'血浆管理Y', biometric:'生物识别/共性模块Y', plasmaCollect:'血浆采集Y', plasmaStorage:'血浆入库Y', weighing:'称重Y', frozen:'速冻Y', packing:'装箱Y', plasmaOutbound:'血浆出库Y', immuneManagement:'免疫管理Y', rulesSet:'规则设置Y', immuneRegister:'免疫登记Y', immunization:'免疫注射Y', feedback:'反馈/转类Y', adverseReactions:'不良反应Y', plasmaCollection:'血浆采集Y', immunization2:'免疫注射Y', moneyManagement:'费用管理Y', rulesSetMoney:'规则设置Y', feesPaid:'费用发放Y', specialFees:'特殊费用Y', giftManagement:'礼品管理Y', rulesSetGift:'规则设置Y', giftFor:'礼品申请Y', giftIssue:'礼品发放Y', reviewManagement:'回访管理Y', quarantinePeriod:'检疫期回访Y', employeesReview:'浆员回访Y', reviewQuery:'回访查询Y', suppliesManagement:'物资管理Y', warehouse:'入库管理Y', outbound:'出库管理Y', automatedOut:'自动出库Y', change:'调拔管理Y', inventoryQuery:'库存查询Y', points:'盘点管理Y', infrastructure:'基础设置Y', warehouseManag:'仓库管理Y', materialManag:'物料管理Y', bom:'物料清单Y', materialTemplate:'物料模板Y', unit:'单位管理Y', materialClass:'物料分类Y', warning:'预警管理Y', supplier:'供应商管理Y', manufacturer:'生产商管理Y', inventoryInit:'库存初始化Y', qualityManagement:'质控管理Y', sample:'样本Y', plasma:'血浆Y', material:'物料Y', scrap:'报废Y', instrumentTest:'仪器检验Y', enzymeLabeled:'酶标仪管理Y', biochemical:'生化仪管理Y', equipmentManagement:'设备管理Y', registrationEqu:'设备登记Y', queryEqu:'设备查询Y', inspectionReg:'巡检登记Y', integratedQuery:'综合查询Y', reportSet:'报表设置Y', queryInt:'查询Y', permission: '系统管理Y', role: '角色管理Y', user:'用户管理Y', department:'部门管理Y', position:'职务管理Y', permissions:'权限管理Y', parameterSetting:'业务参数设置Y', log:'日志管理Y', dictionary:'数据字典Y', credentials:'凭证管理Y', menu:'菜单管理Y', queued:'排队叫号配置Y', systemSettings:'系统设置Y', }, navbar: { dashboard: 'Dashboard', github: 'Github', logOut: 'Log Out', profile: 'Profile', screenfull:'screenfull', theme: 'Theme', size: 'Global Size', i18n: 'internationalization', }, login: { title: '精英天成单采血浆站标准化业务管理系统Y', logIn: 'Login', username: 'Username', password: 'Password', any: 'any', thirdparty: 'Or connect with', thirdpartyTips: 'Can not be simulated on local, so please combine you own business simulation! ! !' }, role:{ rolename:'Name', remakr:'Role Description', remakrJane:'Desc', operations:'Operations', menus:'Tree', edit:'Edit Role', new:'New Role', }, documentation: { documentation: 'Documentation', github: 'Github Repository' }, permission: { addRole: 'New Role', editPermission: 'Edit', roles: 'Your roles', switchRoles: 'Switch roles', tips: 'In some cases, using v-permission will have no effect. For example: Element-UI el-tab or el-table-column and other scenes that dynamically render dom. You can only do this with v-if.', delete: 'Delete', confirm: 'Confirm', cancel: 'Cancel' }, guide: { description: 'The guide page is useful for some people who entered the project for the first time. You can briefly introduce the features of the project. Demo is based on ', button: 'Show Guide' }, components: { documentation: 'Documentation', tinymceTips: 'Rich text is a core feature of the management backend, but at the same time it is a place with lots of pits. In the process of selecting rich texts, I also took a lot of detours. The common rich texts on the market have been basically used, and I finally chose Tinymce. See the more detailed rich text comparison and introduction.', dropzoneTips: 'Because my business has special needs, and has to upload images to qiniu, so instead of a third party, I chose encapsulate it by myself. It is very simple, you can see the detail code in @/components/Dropzone.', stickyTips: 'when the page is scrolled to the preset position will be sticky on the top.', backToTopTips1: 'When the page is scrolled to the specified position, the Back to Top button appears in the lower right corner', backToTopTips2: 'You can customize the style of the button, show / hide, height of appearance, height of the return. If you need a text prompt, you can use element-ui el-tooltip elements externally', imageUploadTips: 'Since I was using only the vue@1 version, and it is not compatible with mockjs at the moment, I modified it myself, and if you are going to use it, it is better to use official version.' }, table: { dynamicTips1: 'Fixed header, sorted by header order', dynamicTips2: 'Not fixed header, sorted by click order', dragTips1: 'The default order', dragTips2: 'The after dragging order', title: 'Title', importance: 'Imp', type: 'Type', remark: 'Remark', search: 'Search', add: 'Add', export: 'Export', reviewer: 'reviewer', id: 'ID', date: 'Date', author: 'Author', readings: 'Readings', status: 'Status', actions: 'Actions', edit: 'Edit', publish: 'Publish', draft: 'Draft', delete: 'Delete', cancel: 'Cancel', confirm: 'Confirm' }, example: { warning: 'Creating and editing pages cannot be cached by keep-alive because keep-alive include does not currently support caching based on routes, so it is currently cached based on component name. If you want to achieve a similar caching effect, you can use a browser caching scheme such as localStorage. Or do not use keep-alive include to cache all pages directly. See details' }, errorLog: { tips: 'Please click the bug icon in the upper right corner', description: 'Now the management system are basically the form of the spa, it enhances the user experience, but it also increases the possibility of page problems, a small negligence may lead to the entire page deadlock. Fortunately Vue provides a way to catch handling exceptions, where you can handle errors or report exceptions.', documentation: 'Document introduction' }, excel: { export: 'Export', selectedExport: 'Export Selected Items', placeholder: 'Please enter the file name (default excel-list)' }, zip: { export: 'Export', placeholder: 'Please enter the file name (default file)' }, pdf: { tips: 'Here we use window.print() to implement the feature of downloading PDF.' }, theme: { change: 'Change Theme', documentation: 'Theme documentation', tips: 'Tips: It is different from the theme-pick on the navbar is two different skinning methods, each with different application scenarios. Refer to the documentation for details.' }, tagsView: { refresh: 'Refresh', close: 'Close', closeOthers: 'Close Others', closeAll: 'Close All' }, settings: { title: 'Page style setting', theme: 'Theme Color', tagsView: 'Open Tags-View', fixedHeader: 'Fixed Header', sidebarLogo: 'Sidebar Logo' }, message:{ err1:'Please enter the correct user name', err2:'The password can not be less than 6 digits', err3:'The name cannot be empty', err4:'Role names can only be English characters', err5:'Menu tree must be selected', err6:"You can't have special notation", err7:'Department will choose', msg1:'You have been logged out, you can cancel to stay on this page, or log in again', msg2:'Confirm logout', msg3:'Verification failed, please Login again.', msg4:'Server timeout', msg5:'Switch Language Success', msg6:'Confirm the deletion?', msg7:'Delete succed!', msg8:'Warning', msg9:'Will any sub-departments be deleted together with the sub-departments?', msg10:'Modify the success', msg11:'Add a success', }, button:{ cancel:'Cancel', ReLogin:'Re-Login', confirm:'Confirm', } } 'use strict'; const config = require(__dirname + '/config.js'); const Twit = require('twit'); const request = require('request-promise-native'); const handleBlacklist = config['handle_blacklist'] || []; const twitter = new Twit({ consumer_key: config['twitter_consumer_key'], consumer_secret: config['twitter_consumer_secret'], access_token: config['twitter_access_token'], access_token_secret: config['twitter_access_token_secret'], timeout_ms: 60 * 1000 // optional HTTP request timeout to apply to all requests. }); const postMessage = tweet => { if (handleBlacklist.includes(tweet.user.screen_name)) { return; } request({ method: 'POST', uri: config['slack_webhook_url'], body: { text: `http://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}` }, json: true }) .catch(function (err) { console.log(err); }); }; // Listen to TEA twitter accounts const stream = twitter.stream('statuses/filter', {track: config['twitter_keywords']}); console.log('Listening to Twitter, tracking ' + config['twitter_keywords'].join(', ') + '.'); stream.on('tweet', postMessage); var Fonts = require('./fonts'); var Variables = require('./variables'); var Mixins = require('./mixins'); var Functions = require('./functions'); var Colors = require('./colors'); var Declarations = require('./declarations'); var Selectors = require('./selectors'); var get = require('lodash').get; function isDeclaration(type) { return function(obj) { return get(obj, 'type') === type; }; } var isVarDeclaration = isDeclaration('variable'); var isMixinDeclaration = isDeclaration('mixin'); var isFunctionDeclaration = isDeclaration('function'); function unusedRefsToStats(acc, nextVar) { var name = get(nextVar, 'name', ''); if (Functions.isNativeFunction(name)) { delete acc[name]; return acc; } acc[name] = 0; return acc; } function getVariableStats(astData) { var varStats = Variables.nodesToVariableUsages(astData); var unusedVars = Declarations.findUnusedDeclaration(astData) .filter(isVarDeclaration) .reduce(unusedRefsToStats, {}); return Object.assign({}, varStats, unusedVars); } function getMixinStats(astData) { var mixinStats = Mixins.nodesToMixinUsages(astData); var unusedMixins = Declarations.findUnusedDeclaration(astData) .filter(isMixinDeclaration) .reduce(unusedRefsToStats, {}); return Object.assign({}, mixinStats, unusedMixins); } function getFunctionStats(astData) { var functionStats = Functions.nodesToFunctionUsages(astData); var unusedfunctions = Declarations.findUnusedDeclaration(astData) .filter(isFunctionDeclaration) .reduce(unusedRefsToStats, {}); return Object.assign({}, functionStats, unusedfunctions); } function getSelectorStats(astData) { return Selectors.findSelectors(astData) .reduce(collectSelectorStats, {id: 0, class: 0, tag: 0}); } function collectSelectorStats(acc, selector) { if(/^#/.test(selector)) { acc.id++; return acc; } if(/^\./.test(selector)) { acc.class++; return acc; } acc.tag++; return acc; } module.exports = function(astData) { return { variables: getVariableStats(astData), mixins: getMixinStats(astData), functions: getFunctionStats(astData), colors: Colors.nodesToColorUsages(astData), fonts: Fonts.nodesToFontUsages(astData), selectors: getSelectorStats(astData) }; }; import Component from '@ember/component'; import {inject as injectService} from '@ember/service'; export default Component.extend({ ui: injectService(), tagName: 'nav', classNames: ['gh-mobile-nav-bar'] }); AOS.init({ duration: 800, easing: 'slide', once: false }); jQuery(document).ready(function($) { "use strict"; var siteMenuClone = function() { $('.js-clone-nav').each(function() { var $this = $(this); $this.clone().attr('class', 'site-nav-wrap').appendTo('.site-mobile-menu-body'); }); setTimeout(function() { var counter = 0; $('.site-mobile-menu .has-children').each(function(){ var $this = $(this); $this.prepend('<span class="arrow-collapse collapsed">'); $this.find('.arrow-collapse').attr({ 'data-toggle' : 'collapse', 'data-target' : '#collapseItem' + counter, }); $this.find('> ul').attr({ 'class' : 'collapse', 'id' : 'collapseItem' + counter, }); counter++; }); }, 1000); $('body').on('click', '.arrow-collapse', function(e) { var $this = $(this); if ( $this.closest('li').find('.collapse').hasClass('show') ) { $this.removeClass('active'); } else { $this.addClass('active'); } e.preventDefault(); }); $(window).resize(function() { var $this = $(this), w = $this.width(); if ( w > 768 ) { if ( $('body').hasClass('offcanvas-menu') ) { $('body').removeClass('offcanvas-menu'); } } }) $('body').on('click', '.js-menu-toggle', function(e) { var $this = $(this); e.preventDefault(); if ( $('body').hasClass('offcanvas-menu') ) { $('body').removeClass('offcanvas-menu'); $this.removeClass('active'); } else { $('body').addClass('offcanvas-menu'); $this.addClass('active'); } }) // click outisde offcanvas $(document).mouseup(function(e) { var container = $(".site-mobile-menu"); if (!container.is(e.target) && container.has(e.target).length === 0) { if ( $('body').hasClass('offcanvas-menu') ) { $('body').removeClass('offcanvas-menu'); } } }); }; siteMenuClone(); var sitePlusMinus = function() { $('.js-btn-minus').on('click', function(e){ e.preventDefault(); if ( $(this).closest('.input-group').find('.form-control').val() != 0 ) { $(this).closest('.input-group').find('.form-control').val(parseInt($(this).closest('.input-group').find('.form-control').val()) - 1); } else { $(this).closest('.input-group').find('.form-control').val(parseInt(0)); } }); $('.js-btn-plus').on('click', function(e){ e.preventDefault(); $(this).closest('.input-group').find('.form-control').val(parseInt($(this).closest('.input-group').find('.form-control').val()) + 1); }); }; // sitePlusMinus(); var siteSliderRange = function() { $( "#slider-range" ).slider({ range: true, min: 0, max: 500, values: [ 75, 300 ], slide: function( event, ui ) { $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); } }); $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) + " - $" + $( "#slider-range" ).slider( "values", 1 ) ); }; // siteSliderRange(); var siteCarousel = function () { if ( $('.nonloop-block-13').length > 0 ) { $('.nonloop-block-13').owlCarousel({ center: false, items: 1, loop: true, stagePadding: 0, margin: 0, autoplay: true, nav: true, navText: ['<span class="icon-arrow_back">', '<span class="icon-arrow_forward">'], responsive:{ 600:{ margin: 0, nav: true, items: 2 }, 1000:{ margin: 0, stagePadding: 0, nav: true, items: 3 }, 1200:{ margin: 0, stagePadding: 0, nav: true, items: 4 } } }); } $('.slide-one-item').owlCarousel({ center: false, items: 1, loop: true, stagePadding: 0, margin: 0, autoplay: true, pauseOnHover: false, nav: true, navText: ['<span class="icon-keyboard_arrow_left">', '<span class="icon-keyboard_arrow_right">'] }); // $('.slide-one-item-alt').owlCarousel({ // center: false, // items: 1, // loop: true, // stagePadding: 0, // smartSpeed: 700, // margin: 0, // autoplay: true, // pauseOnHover: false, // }); // $('.slide-one-item-alt-text').owlCarousel({ // center: false, // items: 1, // loop: true, // stagePadding: 0, // smartSpeed: 700, // margin: 0, // autoplay: true, // pauseOnHover: false, // }); $('.slide-one-item-alt').owlCarousel({ center: false, items: 1, loop: true, stagePadding: 0, margin: 0, smartSpeed: 1000, autoplay: true, pauseOnHover: true, onDragged: function(event) { console.log('event : ',event.relatedTarget['_drag']['direction']) if ( event.relatedTarget['_drag']['direction'] == 'left') { $('.slide-one-item-alt-text').trigger('next.owl.carousel'); } else { $('.slide-one-item-alt-text').trigger('prev.owl.carousel'); } } }); $('.slide-one-item-alt-text').owlCarousel({ center: false, items: 1, loop: true, stagePadding: 0, margin: 0, smartSpeed: 1000, autoplay: true, pauseOnHover: true, onDragged: function(event) { console.log('event : ',event.relatedTarget['_drag']['direction']) if ( event.relatedTarget['_drag']['direction'] == 'left') { $('.slide-one-item-alt').trigger('next.owl.carousel'); } else { $('.slide-one-item-alt').trigger('prev.owl.carousel'); } } }); $('.custom-next').click(function(e) { e.preventDefault(); $('.slide-one-item-alt').trigger('next.owl.carousel'); $('.slide-one-item-alt-text').trigger('next.owl.carousel'); }); $('.custom-prev').click(function(e) { e.preventDefault(); $('.slide-one-item-alt').trigger('prev.owl.carousel'); $('.slide-one-item-alt-text').trigger('prev.owl.carousel'); }); }; siteCarousel(); var siteStellar = function() { $(window).stellar({ responsive: false, parallaxBackgrounds: true, parallaxElements: true, horizontalScrolling: false, hideDistantElements: false, scrollProperty: 'scroll' }); }; // siteStellar(); var siteCountDown = function() { $('#date-countdown').countdown('2020/10/10', function(event) { var $this = $(this).html(event.strftime('' + '<span class="countdown-block"><span class="label">%w</span> weeks </span>' + '<span class="countdown-block"><span class="label">%d</span> days </span>' + '<span class="countdown-block"><span class="label">%H</span> hr </span>' + '<span class="countdown-block"><span class="label">%M</span> min </span>' + '<span class="countdown-block"><span class="label">%S</span> sec</span>')); }); }; siteCountDown(); var siteDatePicker = function() { if ( $('.datepicker').length > 0 ) { $('.datepicker').datepicker(); } }; siteDatePicker(); var siteSticky = function() { $(".js-sticky-header").sticky({topSpacing:0}); }; siteSticky(); // navigation var OnePageNavigation = function() { var navToggler = $('.site-menu-toggle'); $("body").on("click", ".main-menu li a[href^='#'], .smoothscroll[href^='#'], .site-mobile-menu .site-nav-wrap li a", function(e) { e.preventDefault(); var hash = this.hash; $('html, body').animate({ 'scrollTop': $(hash).offset().top }, 600, 'easeInOutExpo', function(){ window.location.hash = hash; }); }); }; OnePageNavigation(); var siteScroll = function() { $(window).scroll(function() { var st = $(this).scrollTop(); if (st > 100) { $('.js-sticky-header').addClass('shrink'); } else { $('.js-sticky-header').removeClass('shrink'); } }) }; siteScroll(); var siteIstotope = function() { /* activate jquery isotope */ var $container = $('#posts').isotope({ itemSelector : '.item', isFitWidth: true }); $(window).resize(function(){ $container.isotope({ columnWidth: '.col-sm-3' }); }); $container.isotope({ filter: '*' }); // filter items on button click $('#filters').on( 'click', 'button', function() { var filterValue = $(this).attr('data-filter'); $container.isotope({ filter: filterValue }); $('#filters button').removeClass('active'); $(this).addClass('active'); }); } siteIstotope(); $('.fancybox').on('click', function() { var visibleLinks = $('.fancybox'); $.fancybox.open( visibleLinks, {}, visibleLinks.index( this ) ); return false; }); }); // var slideIndex = 1; // showSlides(slideIndex); // function plusSlides(n) { // showSlides(slideIndex += n); // } // function currentSlide(n) { // showSlides(slideIndex = n); // } // function showSlides(n) { // var i; // var slides = document.getElementsByClassName("mySlides"); // var dots = document.getElementsByClassName("dot"); // if (n > slides.length) {slideIndex = 1} // if (n < 1) {slideIndex = slides.length} // for (i = 0; i < slides.length; i++) { // slides[i].style.display = "none"; // } // for (i = 0; i < dots.length; i++) { // dots[i].className = dots[i].className.replace(" active", ""); // } // slides[slideIndex-1].style.display = "block"; // dots[slideIndex-1].className += " active"; // } var slideIndex = 0; showSlides(); function showSlides() { var i; var slides = document.getElementsByClassName("mySlides"); for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } slideIndex++; if (slideIndex > slides.length) {slideIndex = 1} slides[slideIndex-1].style.display = "block"; setTimeout(showSlides, 2000); // Change image every 2 seconds } // jssor_1_slider_init(); // window.jssor_1_slider_init = function() { // var jssor_1_SlideshowTransitions = [ // {$Duration:800,x:-0.3,$During:{$Left:[0.3,0.7]},$Easing:{$Left:$Jease$.$InCubic,$Opacity:$Jease$.$Linear},$Opacity:2}, // {$Duration:800,x:0.3,$SlideOut:true,$Easing:{$Left:$Jease$.$InCubic,$Opacity:$Jease$.$Linear},$Opacity:2} // ]; // var jssor_1_options = { // $AutoPlay: 1, // $SlideshowOptions: { // $Class: $JssorSlideshowRunner$, // $Transitions: jssor_1_SlideshowTransitions, // $TransitionsOrder: 1 // }, // $ArrowNavigatorOptions: { // $Class: $JssorArrowNavigator$ // }, // $ThumbnailNavigatorOptions: { // $Class: $JssorThumbnailNavigator$, // $Orientation: 2, // $NoDrag: true // } // }; // var jssor_1_slider = new $JssorSlider$("jssor_1", jssor_1_options); // /*#region responsive code begin*/ // var MAX_WIDTH = 980; // function ScaleSlider() { // var containerElement = jssor_1_slider.$Elmt.parentNode; // var containerWidth = containerElement.clientWidth; // if (containerWidth) { // var expectedWidth = Math.min(MAX_WIDTH || containerWidth, containerWidth); // jssor_1_slider.$ScaleWidth(expectedWidth); // } // else { // window.setTimeout(ScaleSlider, 30); // } // } // ScaleSlider(); // $Jssor$.$AddEvent(window, "load", ScaleSlider); // $Jssor$.$AddEvent(window, "resize", ScaleSlider); // $Jssor$.$AddEvent(window, "orientationchange", ScaleSlider); // /*#endregion responsive code end*/ // };<reponame>kamekame0712/laravel_od<filename>public/js/front.top.js jQuery( function($) { $('.btn-show > i').removeClass('fa-chevron-up'); $('.btn-show > i').addClass('fa-chevron-down'); $('.example-unit').css('display', 'none'); var current_url = location.href; if( current_url.indexOf('#') != -1 ) { scrollBy(0, -50); } }); $('.btn-show').click( function() { var obj = $(this).next('div'); if( obj.css('display') == 'none' ) { $(this).html('<選択単元例>を隠す <i class="fas fa-chevron-up"></i>'); obj.slideDown(); } else { $(this).html('<選択単元例>を見る <i class="fas fa-chevron-down"></i>'); obj.slideUp(); } });<filename>src/Cache.js<gh_stars>10-100 export default async function cachedFetch(url, processData) { if (localStorage[url]) { processData(JSON.parse(localStorage[url])); } else { await fetch(url) .then(response => response.json()) .then(data => { try { localStorage[url] = JSON.stringify(data); } catch (error) { try { // local storage cache full, delete random elements for (let i = 0; i < 100; i++) { const randomStoredUrl = Object.keys(localStorage)[ Math.floor(Math.random() * Object.keys(localStorage).length) ]; localStorage.removeItem(randomStoredUrl); } localStorage[url] = JSON.stringify(data); } catch (error2) { console.error( `Unable to cache information for request "${url}" in local storage: ${error2}` ); } } processData(data); }) .catch(function(error) { console.error(`Failed to fetch and process "${url}": ${error}`); }); } }<reponame>dave325/wordpress-nginx-docker<filename>wordpress/wp-content/plugins/newstatpress/includes/js/nsp_variables_alltotalvisits.js<gh_stars>100-1000 jQuery.post( nsp_variablesAjax_alltotalvisits.ajaxurl, { // here we declare the parameters to send along with the request // this means the following action hooks will be fired: // wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit action : 'nsp_variables', // other parameters can be added along with "action" VAR : nsp_variablesAjax_alltotalvisits.VAR, URL : nsp_variablesAjax_alltotalvisits.URL, LIMIT : nsp_variablesAjax_alltotalvisits.LIMIT, FLAG : nsp_variablesAjax_alltotalvisits.FLAG, // send the nonce along with the request postCommentNonce : nsp_variablesAjax_alltotalvisits.postCommentNonce }, function( response ) { document.getElementById(nsp_variablesAjax_alltotalvisits.VAR).innerHTML=response; } ); /* eslint-env node */ // Override translation-reducer to not tell us about missing 'none' keys // var TranslationReducer = require('ember-intl/lib/broccoli/translation-reducer'); // function propKeys(object) { // var result = []; // var escaped; // for (var key in object) { // escaped = key.replace(/\./g, '\\.'); // if (object.hasOwnProperty(key)) { // if (typeof object[key] === 'object') { // result = result.concat(propKeys(object[key]).map(function (_key) { // return escaped + '.' + _key; // })); // } else { // result.push(escaped); // } // } // } // return result; // } // TranslationReducer.prototype.findMissingKeys = function(target, defaultTranslationKeys, locale) { // var targetProps = propKeys(target); // var log = this.options.log; // var total = defaultTranslationKeys.length; // var missing = {}; // defaultTranslationKeys.forEach(function (property) { // if (targetProps.indexOf(property) === -1 && locale !== 'none') { // missing[locale] = (missing[locale]||0) + 1; // //log(property + '\' missing from ' + locale); // } // }); // Object.keys(missing).forEach(function(locale) { // log(missing[locale] + ' keys missing in ' + locale); // }); // }; module.exports = function(/* environment */) { return { /** * The locales that the application needs to support. * * NOTE: this is optional and is automatically set *if* you store translations * within the `inputPath` defined below. * * If you side load translations, you must then explicitly * list out the locales. i.e: ['en-us', 'en-gb', 'fr-fr'] * * @property locales * @type {Array?} * @default "null" */ locales: ['en-us', 'de-de'], /** * Merges the fallback l=ocale's translations into all other locales as a * build-time fallback strategy. * * NOTE: a side effect of this option could result in missing translation warnings to be masked. * * @property fallbackLocale * @type {String?} * @default "null" */ fallbackLocale: 'en-us', /** * Path where translations are kept. This is relative to the project root. * For example, if your translations are an npm dependency, set this to: *`'./node_modules/path/to/translations'` * * @property inputPath * @type {String} * @default "'translations'" */ inputPath: 'translations', /** * Automatically inject the Intl.JS polyfill into index.html * * @property autoPolyfill * @type {Boolean} * @default "false" */ autoPolyfill: false, /** * Prevents the polyfill from being bundled in the asset folder of the build * * @property disablePolyfill * @type {Boolean} * @default "false" */ disablePolyfill: false, /** * Prevents the translations from being bundled with the application code. * This enables asynchronously loading the translations for the active locale * by fetching them from the asset folder of the build. * * See: https://ember-intl.github.io/ember-intl/docs/guide/asynchronously-loading-translations * * @property publicOnly * @type {Boolean} * @default "false" */ publicOnly: true, /** * Cause a build error if ICU argument mismatches are detected. * * @property errorOnNamedArgumentMismatch * @type {Boolean} * @default "false" */ errorOnNamedArgumentMismatch: false, /** * Cause a build error if missing translations are detected. * * See https://ember-intl.github.io/ember-intl/docs/guide/missing-translations#throwing-a-build-error-on-missing-required-translation * * @property errorOnMissingTranslations * @type {Boolean} * @default "false" */ errorOnMissingTranslations: false, /** * removes empty translations from the build output. * * @property stripEmptyTranslations * @type {Boolean} * @default false */ stripEmptyTranslations: false, /** * Add the subdirectories of the translations as a namespace for all keys. * * @property wrapTranslationsWithNamespace * @type {Boolean} * @default false */ wrapTranslationsWithNamespace: false, /** * Filter missing translations to ignore expected missing translations. * * See https://ember-intl.github.io/ember-intl/docs/guide/missing-translations#requiring-translations * * @property requiresTranslation * @type {Function} * @default "function(key,locale){return true}" */ requiresTranslation(/* key, locale */) { return false; } }; }; /** * Copyright 2020 Phenix Real Time Solutions, 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. */ define([ 'phenix-web-lodash-light', 'phenix-web-assert', 'phenix-web-observable', '../AdminApiProxyClient', '../userMedia/UserMediaResolver', '../PCast', 'phenix-rtc', '../streaming/shaka.json' ], function(_, assert, observable, AdminApiProxyClient, UserMediaResolver, PCast, rtc, shakaEnums) { 'use strict'; var instanceCounter = 0; var unauthorizedStatus = 'unauthorized'; var capacityBackoffTimeout = 1000; var defaultPrerollSkipDuration = 500; var defaultUserActionOnlineTimeout = 20000; var defaultReconnectOptions = { maxOfflineTime: 3 * 60 * 1000, maxReconnectFrequency: 60 * 1000 }; function PCastExpress(options) { assert.isObject(options, 'options'); if (options.authToken) { assert.isStringNotEmpty(options.authToken, 'options.authToken'); } if (options.authToken && options.adminApiProxyClient) { throw new Error('Do not pass "options.adminApiProxyClient" if you are using "options.authToken"'); } if (options.onError) { assert.isFunction(options.onError, 'options.onError'); } if (!_.isNullOrUndefined(options.onlineTimeout)) { assert.isNumber(options.onlineTimeout, 'options.onlineTimeout'); if (options.onlineTimeout < 0) { throw new Error('"options.onlineTimeout" must be a positive number'); } } if (options.reconnectOptions) { assert.isObject(options.reconnectOptions, 'options.reconnectOptions'); assert.isNumber(options.reconnectOptions.maxOfflineTime, 'options.reconnectOptions.maxOfflineTime'); assert.isNumber(options.reconnectOptions.maxReconnectFrequency, 'options.reconnectOptions.maxReconnectFrequency'); } if (options.adminApiProxyClient) { assert.isObject(options.adminApiProxyClient, 'options.adminApiProxyClient'); assert.isFunction(options.adminApiProxyClient.createAuthenticationToken, 'options.adminApiProxyClient.createAuthenticationToken'); } this._instanceId = ++instanceCounter; this._pcastObservable = new observable.Observable(null).extend({rateLimit: 0}); this._sessionIdObservable = new observable.Observable(null).extend({rateLimit: 0}); this._publishers = {}; this._adminApiProxyClient = options.adminApiProxyClient; this._isInstantiated = false; this._reconnectCount = 0; this._reauthCount = 0; this._disposed = false; this._authToken = options.authToken; this._onError = options.onError; this._options = options; this._onlineTimeout = _.isNumber(options.onlineTimeout) ? options.onlineTimeout : defaultUserActionOnlineTimeout; this._reconnectOptions = options.reconnectOptions || defaultReconnectOptions; this._logger = null; this._ignoredStreamEnds = {}; instantiatePCast.call(this); // After logger is instantiated if (!options.adminApiProxyClient) { if (options.backendUri || _.isString(options.backendUri)) { this._logger.warn('Passing options.backendUri is deprecated. Please create an instance of the sdk.net.AdminApiProxyClient and pass that instead'); } if (options.authenticationData) { this._logger.warn('Passing options.authenticationData is deprecated. Please create an instance of the sdk.net.AdminApiProxyClient and pass that instead'); } } } PCastExpress.prototype.toString = function toString() { return 'PCastExpress[' + this._instanceId + ']'; }; PCastExpress.prototype.dispose = function dispose() { if (this._listedForCriticalNetworkRecoveryDisposable) { this._listedForCriticalNetworkRecoveryDisposable.dispose(); this._listedForCriticalNetworkRecoveryDisposable = null; } if (this._pcastObservable.getValue()) { this._pcastObservable.getValue().stop(); this._pcastObservable.setValue(null); } if (this._sessionIdObservable.getValue()) { this._sessionIdObservable.setValue(null); } if (_.isNumber(this._instantiatePCastTimeoutId)) { clearTimeout(this._instantiatePCastTimeoutId); this._instantiatePCastTimeoutId = null; } if (this._adminApiProxyClient) { this._adminApiProxyClient.dispose(); } if (this.sessionIdSubscription) { this.sessionIdSubscription.dispose(); } if (this._sessionIdObservable && this._sessionIdObservable.dispose) { this._sessionIdObservable.dispose(); } this._reconnectCount = 0; this._reauthCount = 0; this._disposed = true; this._logger.info('[%s] Disposed PCast Express instance', this); }; PCastExpress.prototype.getPCast = function getPCast() { return this._pcastObservable.getValue(); }; PCastExpress.prototype.getPCastObservable = function() { return this._pcastObservable; }; PCastExpress.prototype.getSessionIdObservable = function() { return this._sessionIdObservable; }; PCastExpress.prototype.getAdminAPI = function getAdminAPI() { return this._adminApiProxyClient; }; PCastExpress.prototype.getUserMedia = function(options, callback) { var that = this; assert.isObject(options.mediaConstraints, 'options.mediaConstraints'); assert.isFunction(callback, 'callback'); if (options.resolution) { assert.isNumber(options.resolution, 'options.resolution'); } if (options.frameRate) { assert.isNumber(options.frameRate, 'options.frameRate'); } if (options.aspectRatio) { assert.isStringNotEmpty(options.aspectRatio, 'options.aspectRatio'); } if (options.onResolveMedia) { assert.isFunction(options.onResolveMedia, 'options.onResolveMedia'); } if (options.onScreenShare) { assert.isFunction(options.onScreenShare, 'options.onScreenShare'); } if (that._pcastObservable.getValue()) { return resolveUserMedia.call(that, that._pcastObservable.getValue(), options, callback); } var pcastSubscription = that._pcastObservable.subscribe(function(pcast) { if (!pcast) { return; } pcastSubscription.dispose(); resolveUserMedia.call(that, pcast, options, callback); }); }; PCastExpress.prototype.publish = function publish(options, callback) { assert.isObject(options, 'options'); assert.isFunction(callback, 'callback'); if (options.capabilities) { assert.isArray(options.capabilities, 'options.capabilities'); } if (options.connectOptions) { assert.isArray(options.connectOptions, 'options.connectOptions'); } if (options.mediaConstraints) { assert.isObject(options.mediaConstraints, 'options.mediaConstraints'); } else { assert.isObject(options.userMediaStream, 'options.userMediaStream'); } if (options.videoElement) { assert.isObject(options.videoElement, 'options.videoElement'); } if (options.monitor) { assert.isObject(options.monitor, 'options.monitor'); assert.isFunction(options.monitor.callback, 'options.monitor.callback'); if (options.monitor.options) { assert.isObject(options.monitor.options, 'options.monitor.options'); } } if (options.publishToken) { assert.isStringNotEmpty(options.publishToken, 'options.publishToken'); } if (options.streamToken) { assert.isStringNotEmpty(options.streamToken, 'options.streamToken'); } if (options.publishToken && options.streamToken) { throw new Error('Do not pass streamToken with publishToken. Please use publishToken.'); } var that = this; this.waitForOnline(function(error) { if (error) { return callback(error); } if (options.userMediaStream) { return getStreamingTokenAndPublish.call(that, options.userMediaStream, options, false, callback); } that.getUserMedia(options, function(error, response) { if (error) { return callback(error); } if (response.status !== 'ok') { return callback(null, response); } getStreamingTokenAndPublish.call(that, response.userMedia, options, true, callback); }); }, options.isContinuation); }; var connectOptionCapabilities = ['streaming', 'low-latency', 'on-demand', 'uld', 'vvld', 'vld', 'ld', 'sd', 'hd', 'fhd', 'uhd']; PCastExpress.prototype.publishRemote = function publishRemote(options, callback) { assert.isObject(options, 'options'); assert.isFunction(callback, 'callback'); assert.isStringNotEmpty(options.streamUri, 'options.streamUri'); if (options.capabilities) { assert.isArray(options.capabilities, 'options.capabilities'); } if (options.connectOptions) { assert.isArray(options.connectOptions, 'options.connectOptions'); } if (options.mediaConstraints) { throw new Error('Invalid argument: mediaConstraints, passed on publishRemote. Local media not allowed when publishing remote content.'); } if (options.videoElement) { throw new Error('May not preview remote stream. Please subscribe to view.'); } if (options.prerollSkipDuration) { assert.isNumber(options.prerollSkipDuration, 'options.prerollSkipDuration'); } if (options.monitor) { assert.isObject(options.monitor, 'options.monitor'); assert.isFunction(options.monitor.callback, 'options.monitor.callback'); if (options.monitor.options) { assert.isObject(options.monitor.options, 'options.monitor.options'); } } if (options.frameRate) { assert.isObject(options.frameRate, 'options.frameRate'); if (options.frameRate.exact) { assert.isNumber(options.frameRate.exact, 'options.frameRate.exact'); } if (options.frameRate.max) { assert.isNumber(options.frameRate.max, 'options.frameRate.max'); } } if (options.publishToken) { assert.isStringNotEmpty(options.publishToken, 'options.publishToken'); } if (options.streamToken) { assert.isStringNotEmpty(options.streamToken, 'options.streamToken'); } if (options.publishToken && options.streamToken) { throw new Error('Do not pass streamToken with publishToken. Please use publishToken.'); } var that = this; this.waitForOnline(function(error) { if (error) { return callback(error); } var remoteOptions = _.assign({ connectOptions: [], capabilities: [] }, options); if (!_.includes(remoteOptions.capabilities, 'publish-uri')) { remoteOptions.capabilities.push('publish-uri'); } _.forEach(connectOptionCapabilities, function(capability) { if (_.includes(remoteOptions.capabilities, capability)) { remoteOptions.connectOptions.push('publisher-capability=' + capability); } }); if (options.frameRate && options.frameRate.exact) { remoteOptions.connectOptions.push('source-uri-video-fps=' + options.frameRate.exact); } if (options.frameRate && options.frameRate.max) { remoteOptions.connectOptions.push('source-uri-video-fps-max=' + options.frameRate.max); } remoteOptions.connectOptions.push('source-uri-preroll-skip-duration=' + (_.isNumber(options.prerollSkipDuration) ? options.prerollSkipDuration : defaultPrerollSkipDuration).toString()); getStreamingTokenAndPublish.call(that, remoteOptions.streamUri, remoteOptions, false, callback); }); }; PCastExpress.prototype.publishStreamToExternal = function publishStreamToExternal(options, callback) { assert.isObject(options, 'options'); assert.isFunction(callback, 'callback'); assert.isStringNotEmpty(options.streamId, 'options.streamId'); assert.isStringNotEmpty(options.externalUri, 'options.externalUri'); if (options.capabilities) { assert.isArray(options.capabilities, 'options.capabilities'); } if (options.connectOptions) { assert.isArray(options.connectOptions, 'options.connectOptions'); } if (options.mediaConstraints) { throw new Error('Invalid argument: mediaConstraints, passed on publishStreamToExternal. Local media not allowed when publishing remote content.'); } if (options.videoElement) { throw new Error('May not preview external stream. Please subscribe to view.'); } if (options.monitor) { assert.isObject(options.monitor, 'options.monitor'); assert.isFunction(options.monitor.callback, 'options.monitor.callback'); if (options.monitor.options) { assert.isObject(options.monitor.options, 'options.monitor.options'); } } if (options.streamToken) { assert.isStringNotEmpty(options.streamToken, 'options.streamToken'); } var that = this; this.waitForOnline(function(error) { if (error) { return callback(error); } var remoteOptions = _.assign({ connectOptions: [], capabilities: [] }, options); if (!_.includes(remoteOptions.capabilities, 'egress')) { remoteOptions.capabilities.push('egress'); } if (!_.includes(remoteOptions.capabilities, 'egress-own-stream')) { remoteOptions.capabilities.push('egress-own-stream'); } getStreamingTokenAndPublish.call(that, remoteOptions.externalUri, remoteOptions, false, callback); }); }; PCastExpress.prototype.publishScreen = function publishScreen(options, callback) { var publishScreenOptions = _.assign({mediaConstraints: {screen: true}}, options); _.set(publishScreenOptions, ['monitor', 'options'], _.assign({}, { monitorFrameRate: false, videoBitRateThreshold: 100, conditionCountForNotificationThreshold: 8 }, _.get(publishScreenOptions, ['monitor', 'options'], {}))); return this.publish(publishScreenOptions, callback); }; PCastExpress.prototype.subscribe = function subscribe(options, callback) { assert.isObject(options, 'options'); assert.isFunction(callback, 'callback'); assert.isStringNotEmpty(options.streamId, 'options.streamId'); if (options.videoElement) { assert.isObject(options.videoElement, 'options.videoElement'); } if (options.monitor) { assert.isObject(options.monitor, 'options.monitor'); assert.isFunction(options.monitor.callback, 'options.monitor.callback'); if (options.monitor.options) { assert.isObject(options.monitor.options, 'options.monitor.options'); } } if (options.streamToken) { assert.isStringNotEmpty(options.streamToken, 'options.streamToken'); } else { assert.isObject(options.capabilities, 'options.capabilities'); } if (options.subscriberOptions) { assert.isObject(options.subscriberOptions, 'options.subscriberOptions'); } var that = this; this.waitForOnline(function(error) { if (error) { that._logger.error('[%s] Failed to subscribe after error waiting for online status', this, error); return callback(error); } if (options.streamToken) { return subscribeToStream.call(that, options.streamToken, options, callback); } if (!options.streamToken && !that._adminApiProxyClient) { throw new Error('Use stream token, or set adminApiProxyClient'); } that._logger.info('[%s] [%s] Generating stream token for subscribing to origin [%s]', this, that._pcastObservable.getValue().getProtocol().getSessionId(), options.streamId); that._adminApiProxyClient.createStreamTokenForSubscribing(that._pcastObservable.getValue().getProtocol().getSessionId(), options.capabilities, options.streamId, null, function(error, response) { if (error) { that._logger.error('[%s] Failed to create stream token for subscribing', this, error); return callback(error); } if (response.status !== 'ok') { that._logger.warn('[%s] Failed to create stream token for subscribing with status [%s]', this, response.status); return callback(null, response); } subscribeToStream.call(that, response.streamToken, options, callback); }); }, options.isContinuation); }; PCastExpress.prototype.subscribeToScreen = function subscribeToScreen(options, callback) { var subscribeToScreenOptions = _.assign({}, options); _.set(subscribeToScreenOptions, ['monitor', 'options'], _.assign({}, { monitorFrameRate: false, videoBitRateThreshold: 100, conditionCountForNotificationThreshold: 8 }, _.get(subscribeToScreenOptions, ['monitor', 'options'], {}))); return this.subscribe(subscribeToScreenOptions, callback); }; PCastExpress.prototype.waitForOnline = function waitForOnline(callback, isNotUserAction) { assert.isFunction(callback, 'callback'); if (this._pcastObservable.getValue() && this._pcastObservable.getValue().getStatus() === 'online') { return callback(); } var that = this; var disposeOfWaitTimeout = isNotUserAction ? _.get(that._reconnectOptions, ['maxOfflineTime']) : this._onlineTimeout; var pcastSubscription = null; var statusSubscription = null; var onlineTimeoutId = setTimeout(function() { that._logger.info('[%s] Disposing of online listener after [%s] ms', this, disposeOfWaitTimeout); if (pcastSubscription) { pcastSubscription.dispose(); } if (statusSubscription) { statusSubscription.dispose(); } if (that._disposed) { that._logger.info('[%s] Instance was disposed while waiting for online, ignoring callback', this); return; } callback(new Error('timeout')); }, disposeOfWaitTimeout); this._logger.info('[%s] Waiting for online status before continuing. Timeout set to [%s]', this, disposeOfWaitTimeout); var subscribeToStatusChange = function(pcast) { if (statusSubscription) { statusSubscription.dispose(); } if (!pcast) { return; } statusSubscription = pcast.getObservableStatus().subscribe(function(status) { if (that._disposed) { that._logger.info('[%s] Instance was disposed while waiting for online, canceling waiting and skip triggering callback', this); clearTimeout(onlineTimeoutId); statusSubscription.dispose(); pcastSubscription.dispose(); return; } if (status !== 'online') { that._logger.info('[%s] Still waiting for online status before continuing. Current status is [%s]', this, status); return; } clearTimeout(onlineTimeoutId); statusSubscription.dispose(); pcastSubscription.dispose(); return callback(); }, {initial: 'notify'}); }; pcastSubscription = this._pcastObservable.subscribe(subscribeToStatusChange, {initial: 'notify'}); }; PCastExpress.prototype.parseCapabilitiesFromToken = function parseCapabilitiesFromToken(streamToken) { var pcast = this._pcastObservable.getValue(); return pcast.parseCapabilitiesFromToken(streamToken); }; PCastExpress.prototype.parseRoomOrChannelIdFromToken = function parseRoomOrChannelIdFromToken(streamToken) { var pcast = this._pcastObservable.getValue(); return pcast.parseRoomOrChannelIdFromToken(streamToken); }; PCastExpress.prototype.parseRoomOrChannelAliasFromToken = function parseRoomOrChannelAliasFromToken(streamToken) { var pcast = this._pcastObservable.getValue(); return pcast.parseRoomOrChannelAliasFromToken(streamToken); }; function instantiatePCast() { var that = this; var authenticationCallback = function(_, status) { if (status === 'critical-network-issue') { return onPCastStatusChange.call(that, status); } }; if (!this._pcastObservable.getValue()) { var pcastOptions = _.assign({logger: this._logger}, this._options); this._pcastObservable.setValue(new PCast(pcastOptions)); } if (!this._logger) { this._logger = this._pcastObservable.getValue().getLogger(); } if (!this._pcastStatusSubscription) { this._pcastStatusSubscription = this._pcastObservable.getValue().getObservableStatus().subscribe(_.bind(onPCastStatusChange, this)); } if (this.sessionIdSubscription) { this.sessionIdSubscription.dispose(); } var handleSessionIdChange = function(sessionId) { this._sessionIdObservable.setValue(sessionId); }; this.sessionIdSubscription = this._pcastObservable.getValue().getObservableSessionId().subscribe(_.bind(handleSessionIdChange, this)); if (this._authToken) { return this._pcastObservable.getValue().start(this._authToken, authenticationCallback, _.noop, _.noop); } if (!this._authToken && !that._adminApiProxyClient) { throw new Error('Use auth token, or set adminApiProxyClient'); } this._adminApiProxyClient.createAuthenticationToken(function(error, response) { if (error && error.message === 'timeout') { return onPCastStatusChange.call(that, error.message); } if (error) { return handleError.call(that, error); } if (response.status !== 'ok') { return onPCastStatusChange.call(that, response.status); } if (!that._pcastObservable.getValue()) { that._logger.warn('[%s] Unable to authenticate. PCast not instantiated.', this); return; } that._pcastObservable.getValue().start(response.authenticationToken, _.noop, _.noop, _.noop); }); } function onPCastStatusChange(status) { switch (status) { case 'timeout': case 'critical-network-issue': if (this._pcastObservable.getValue()) { this._pcastObservable.getValue().stop('recovery'); this._pcastObservable.setValue(null); } if (this._sessionIdObservable.getValue()) { this._sessionIdObservable.setValue(null); } if (this._pcastStatusSubscription) { this._pcastStatusSubscription.dispose(); this._pcastStatusSubscription = null; } this._reconnectCount++; return instantiateWithBackoff.call(this); case 'reconnect-failed': case 'unauthorized': delete this._authToken; if (!this._adminApiProxyClient) { return handleError.call(this, new Error(status)); } this._reauthCount++; if (this._reauthCount > 1) { return handleError.call(this, new Error(status)); } this._logger.info('[%s] Attempting to create new authToken and re-connect after [%s] response', this, unauthorizedStatus); return getAuthTokenAndReAuthenticate.call(this); case 'capacity': case 'network-unavailable': this._reconnectCount++; return instantiateWithBackoff.call(this); case 'online': if (!this._isInstantiated) { this._logger.info('[%s] Successfully instantiated', this); } else { this._logger.info('[%s] Successfully reconnected (reconnectCount=[%s],reauthCount=[%s])', this, this._reconnectCount, this._reauthCount); } this._reauthCount = 0; this._reconnectCount = 0; this._isInstantiated = true; return; case 'reconnecting': case 'reconnected': case 'connecting': break; // Everything ok case 'offline': return; case 'failed': default: return handleError.call(this, new Error(status)); } } function instantiateWithBackoff() { var that = this; var staticTimeout = Math.min(capacityBackoffTimeout * that._reconnectCount * that._reconnectCount, this._reconnectOptions.maxReconnectFrequency); var maxOffsetInSeconds = Math.min(staticTimeout / 10000, 5); var randomLinearOffset = Math.random() * maxOffsetInSeconds * 1000; var timeoutWithRandomOffset = staticTimeout + randomLinearOffset; this._logger.info('[%s] Waiting for [%s] ms before continuing to attempt to reconnect to PCast', this, timeoutWithRandomOffset); this._instantiatePCastTimeoutId = setTimeout(function() { if (!that._pcastObservable.getValue() || !that._pcastObservable.getValue().isStarted()) { return instantiatePCast.call(that); } return getAuthTokenAndReAuthenticate.call(that); }, timeoutWithRandomOffset); } function getAuthTokenAndReAuthenticate() { var that = this; this._adminApiProxyClient.createAuthenticationToken(function(error, response) { if (error && error.message === 'timeout') { return onPCastStatusChange.call(that, error.message); } if (error) { return handleError.call(that, error); } if (response.status !== 'ok') { return onPCastStatusChange.call(that, response.status); } if (!that._pcastObservable.getValue()) { that._logger.warn('[%s] Unable to authenticate. PCast not instantiated.', this); return; } that._pcastObservable.getValue().reAuthenticate(response.authenticationToken); }); } function handleError(e) { if (!this._onError) { throw e; } this._onError(e); } function resolveUserMedia(pcast, options, callback) { var userMediaResolver = new UserMediaResolver(pcast, { aspectRatio: options.aspectRatio, resolution: options.resolution, frameRate: options.frameRate, resolutionSelectionStrategy: options.resolutionSelectionStrategy, onScreenShare: function(screenOptions) { screenOptions = options.onScreenShare ? options.onScreenShare(screenOptions) : screenOptions; if (screenOptions.resolution) { assert.isNumber(screenOptions.resolution, 'clientOptions.resolution'); } if (screenOptions.frameRate) { assert.isNumber(screenOptions.frameRate, 'screenOptions.frameRate'); } if (screenOptions.aspectRatio) { assert.isStringNotEmpty(screenOptions.aspectRatio, 'screenOptions.aspectRatio'); } return _.assign({resolution: screenOptions.resolution}, screenOptions); } }); userMediaResolver.getUserMedia(options.mediaConstraints, function(error, response) { if (error) { return callback(error); } if (options.onResolveMedia) { options.onResolveMedia(response.options); } callback(null, _.assign({status: 'ok'}, response)); }); } function getStreamingTokenAndPublish(userMediaOrUri, options, cleanUpUserMediaOnStop, callback) { var that = this; if (options.publishToken) { try { var capabilitiesFromPublishToken = that.parseCapabilitiesFromToken(options.publishToken); options.capabilities = capabilitiesFromPublishToken; } catch (e) { return callback(new Error('Bad `publishToken`', e), {status: 'bad-token'}); } return publishUserMediaOrUri.call(that, options.publishToken, userMediaOrUri, options, cleanUpUserMediaOnStop, callback); } if (options.streamToken) { try { var capabilitiesFromStreamToken = that.parseCapabilitiesFromToken(options.streamToken); options.capabilities = capabilitiesFromStreamToken; } catch (e) { return callback(new Error('Bad `streamToken`', e), {status: 'bad-token'}); } return publishUserMediaOrUri.call(that, options.streamToken, userMediaOrUri, options, cleanUpUserMediaOnStop, callback); } if (options.capabilities) { assert.isArray(options.capabilities, 'options.capabilities'); } that.waitForOnline(function(error) { if (error) { that._logger.error('[%s] Failed to create stream token for publishing after waiting for online status', this, error); return callback(error); } var sessionId = that._pcastObservable.getValue().getProtocol().getSessionId(); var isEgress = _.includes(options.capabilities, 'egress'); var generateStreamToken = _.bind(that._adminApiProxyClient.createStreamTokenForPublishing, that._adminApiProxyClient, sessionId, options.capabilities); if (isEgress) { generateStreamToken = _.bind(that._adminApiProxyClient.createStreamTokenForPublishingToExternal, that._adminApiProxyClient, sessionId, options.capabilities, options.streamId); } that._logger.info('[%s] [%s] Creating stream token for publishing', this, sessionId); generateStreamToken(function(error, response) { if (error) { that._logger.error('[%s] [%s] Failed to create stream token for publishing', this, sessionId, error); return callback(error); } if (response.status !== 'ok') { that._logger.warn('[%s] [%s] Failed to create stream token for publishing with status [%s]', this, sessionId, response.status); return callback(null, response); } publishUserMediaOrUri.call(that, response.streamToken, userMediaOrUri, options, cleanUpUserMediaOnStop, callback); }); }, options.isContinuation); } function publishUserMediaOrUri(streamToken, userMediaOrUri, options, cleanUpUserMediaOnStop, callback) { var that = this; var hasAlreadyAttachedMedia = false; var cachedPublisher = null; if (options.tags) { assert.isArray(options.tags, 'options.tags'); } if (options.connectOptions) { assert.isArray(options.connectOptions, 'options.connectOptions'); } var publishCallback = function publishCallback(pcast, status, publisher) { var retryPublisher = function retryPublisher(reason) { var optionsWithToken = _.assign({ streamToken: streamToken, isContinuation: true }, options); that._logger.warn('[%s] Retrying publisher after failure with reason [%s]', this, reason); that._ignoredStreamEnds[publisher.getStreamId()] = true; if (reason === 'camera-track-failure') { publisher.stop(reason, false); that.publish(options, callback); } else { publisher.stop(reason, true); getStreamingTokenAndPublish.call(that, userMediaOrUri, optionsWithToken, cleanUpUserMediaOnStop, callback); } }; if ((status === unauthorizedStatus && ((options.streamToken || options.publishToken) || !options.authFailure)) || status === 'timeout') { that._logger.info('[%s] Attempting to create new streamToken and re-publish after [%s] response', this, unauthorizedStatus); var reAuthOptions = _.assign({ isContinuation: true, authFailure: true }, options); delete reAuthOptions.streamToken; delete reAuthOptions.publishToken; return getStreamingTokenAndPublish.call(that, userMediaOrUri, reAuthOptions, cleanUpUserMediaOnStop, callback); } if (status !== 'ok') { that._logger.warn('[%s] Failure to publish with status [%s]', this, status); if (cachedPublisher) { that._ignoredStreamEnds[cachedPublisher.getStreamId()] = true; } return callback(null, {status: status}); } delete options.authFailure; that._publishers[publisher.getStreamId()] = publisher; cachedPublisher = publisher; var isPublisher = true; var noopCallback = function() {}; var publisherEndedCallback = _.bind(onPublisherOrStreamEnd, that, noopCallback, retryPublisher, isPublisher); if (options.monitor) { var monitorCallback = _.bind(onMonitorCallback, that, options.monitor.callback, retryPublisher); publisher.monitor(options.monitor.options || {}, monitorCallback); publisherEndedCallback = _.bind(onPublisherOrStreamEnd, that, options.monitor.callback, retryPublisher, isPublisher); } publisher.setPublisherEndedCallback(publisherEndedCallback); var expressPublisher = createExpressPublisher.call(that, publisher, options.videoElement, cleanUpUserMediaOnStop); if (options.videoElement && !hasAlreadyAttachedMedia) { rtc.attachMediaStream(options.videoElement, userMediaOrUri, function(e) { if (e) { that._logger.warn('[%s] [%s] Failed to attach publish media stream to video element.', this, publisher.getStreamId(), e); return; } }); hasAlreadyAttachedMedia = true; } callback(null, { status: 'ok', publisher: expressPublisher }); }; that.waitForOnline(function(error) { if (error) { return callback(error); } that._pcastObservable.getValue().publish(streamToken, userMediaOrUri, publishCallback, options.tags, {connectOptions: options.connectOptions}); }, options.isContinuation); } function subscribeToStream(streamToken, options, callback) { var that = this; var cachedSubsciber = null; var handleSubscribe = function(pcast, status, subscriber) { var retrySubscriber = function retrySubscriber(reason) { var retryOptions = _.assign({isContinuation: true}, options); that._ignoredStreamEnds[subscriber.getStreamId()] = true; subscriber.stop(reason); that._logger.warn('[%s] [%s] Stream failure occurred with reason [%s]. Attempting to recover from failure.', this, options.streamId, reason); subscribeToStream.call(that, streamToken, retryOptions, callback); }; if (((!options.skipRetryOnUnauthorized && status === unauthorizedStatus && (options.streamToken || !options.authFailure)) || status === 'timeout') && that._adminApiProxyClient) { that._logger.info('[%s] [%s] Attempting to create new streamToken and re-subscribe after [%s] response', this, options.streamId, unauthorizedStatus); var reAuthOptions = _.assign({ isContinuation: true, authFailure: true }, options); delete reAuthOptions.streamToken; return that.subscribe(reAuthOptions, callback); } if (status === 'streaming-not-ready') { that._logger.warn('[%s] Failure to subscribe with status [%s]. Try again in a few seconds.', this, status); return callback(null, { status: status, retry: _.bind(retrySubscriber, that, status) }); } if (status !== 'ok') { that._logger.warn('[%s] Failure to subscribe with status [%s]', this, status); if (cachedSubsciber) { that._ignoredStreamEnds[cachedSubsciber.getStreamId()] = true; } return callback(null, {status: status}); } delete options.authFailure; var renderer; cachedSubsciber = subscriber; if (options.videoElement) { renderer = subscriber.createRenderer(); renderer.start(options.videoElement); } var isPublisher = false; var noopCallback = _.noop; var subscriberEndedCallback = _.bind(onPublisherOrStreamEnd, that, noopCallback, retrySubscriber, isPublisher); if (options.monitor) { var monitorCallback = _.bind(onMonitorCallback, that, options.monitor.callback, retrySubscriber); subscriber.monitor(options.monitor.options || {}, monitorCallback); subscriberEndedCallback = _.bind(onPublisherOrStreamEnd, that, options.monitor.callback, retrySubscriber, isPublisher); } subscriber.setStreamEndedCallback(subscriberEndedCallback); var expressSubscriber = createExpressSubscriber.call(that, subscriber, renderer); var subscribeResponse = { status: 'ok', mediaStream: expressSubscriber }; subscriber.setStreamErrorCallback(function(playerRenderer, errorType, error) { if (errorType === 'real-time' && error.message === 'connection-timeout') { return retrySubscriber.call(that, error.message); } if (errorType === 'shaka' && error.severity !== shakaEnums.errorSeverity.critical.id) { return; // Ignore error } var RECOVERABLE = 1; if (errorType === 'phenix-player' && error.severity === RECOVERABLE) { that._logger.warn('[%s] [%s] Recoverable error occurred while playing stream with Express API. Attempting to subscribe again.', this, expressSubscriber.getStreamId(), error); var reAuthOptions = _.assign({isContinuation: true}, options); delete reAuthOptions.streamToken; return that.subscribe(reAuthOptions, callback); } that._logger.warn('[%s] [%s] Error occurred while playing stream with Express API. Stopping stream.', this, expressSubscriber.getStreamId(), error); expressSubscriber.stop(); return callback(error); }); if (renderer) { subscribeResponse.renderer = renderer; } callback(null, subscribeResponse); }; that.waitForOnline(function(error) { if (error) { return callback(error); } var subscriberOptions = _.clone(options.subscriberOptions || {}); if (options.streamId) { subscriberOptions.originStreamId = options.streamId; } that._pcastObservable.getValue().subscribe(streamToken, handleSubscribe, subscriberOptions); }, options.isContinuation); } function createExpressPublisher(publisher, videoElement, cleanUpUserMediaOnStop) { var that = this; var publisherStop = _.bind(publisher.stop, publisher); publisher.stop = function(reason, isInternal) { that._logger.info('[%s] [%s] Stopping publisher with reason [%s]', that, publisher.getStreamId(), reason); publisherStop(reason); if (videoElement) { videoElement.src = ''; videoElement.srcObject = null; } if (cleanUpUserMediaOnStop && publisher.getStream() && !isInternal) { var nativeMediaStream = publisher.getStream(); if (nativeMediaStream) { nativeMediaStream.getTracks().forEach(function(track) { track.stop(); }); } } }; publisher.enableAudio = function() { return setStreamAudioTracksState.call(that, publisher, true); }; publisher.disableAudio = function() { return setStreamAudioTracksState.call(that, publisher, false); }; publisher.enableVideo = function() { return setStreamVideoTracksState.call(that, publisher, true); }; publisher.disableVideo = function() { return setStreamVideoTracksState.call(that, publisher, false); }; // Publisher Ended Callback handled with normal callback route for express publisher.setPublisherEndedCallback = function() {}; return publisher; } function createExpressSubscriber(subscriber, renderer) { var that = this; var subscriberStop = _.bind(subscriber.stop, subscriber); subscriber.stop = function(reason) { that._logger.info('[%s] [%s] Stopping subscriber with reason [%s]', that, subscriber, reason); if (renderer) { renderer.stop(reason); } subscriberStop(reason); }; subscriber.enableAudio = function() { return setStreamAudioTracksState(subscriber.getStream(), true); }; subscriber.disableAudio = function() { return setStreamAudioTracksState(subscriber.getStream(), false); }; subscriber.enableVideo = function() { return setStreamVideoTracksState(subscriber.getStream(), true); }; subscriber.disableVideo = function() { return setStreamVideoTracksState(subscriber.getStream(), false); }; // Stream Ended Callback handled with normal callback route for express subscriber.setStreamEndedCallback = function() {}; return subscriber; } function setStreamAudioTracksState(publisher, newState) { var pcast = this.getPCast(); if (!pcast) { return; } var streamId = publisher.getStreamId(); var peerConnectionDescription = pcast.getRemoteDescriptionSdp(streamId); if (!peerConnectionDescription) { return; } var stream = publisher.getStream(); var audioIndex = peerConnectionDescription.lastIndexOf('m=audio'); if (audioIndex < 0) { return; } var endIndex = peerConnectionDescription.lastIndexOf('m=video'); if (endIndex < audioIndex) { endIndex = peerConnectionDescription.length; } var trackConfiguration = peerConnectionDescription.substring( audioIndex, endIndex ); if (trackConfiguration.includes('a=inactive')) { return; } if (!stream) { return; } setTracksEnabled(stream.getAudioTracks(), newState); return newState; } function setStreamVideoTracksState(publisher, newState) { var pcast = this.getPCast(); if (!pcast) { return; } var streamId = publisher.getStreamId(); var peerConnectionDescription = pcast.getRemoteDescriptionSdp(streamId); if (!peerConnectionDescription) { return; } var stream = publisher.getStream(); var videoIndex = peerConnectionDescription.lastIndexOf('m=video'); if (videoIndex < 0) { return; } var endIndex = peerConnectionDescription.lastIndexOf('m=audio'); if (endIndex < videoIndex) { endIndex = peerConnectionDescription.length; } var trackConfiguration = peerConnectionDescription.substring( videoIndex, endIndex ); if (trackConfiguration.includes('a=inactive')) { return; } if (!stream) { return; } setTracksEnabled(stream.getVideoTracks(), newState); return newState; } function setTracksEnabled(tracks, enabled) { assert.isArray(tracks, 'tracks'); _.forEach(tracks, function(track) { track.updateState(enabled); }); } function onMonitorCallback(callback, retry, stream, reason, monitorEvent) { // eslint-disable-line no-unused-vars switch (reason) { case 'camera-track-failure': case 'client-side-failure': callback(null, _.assign({ status: reason, retry: _.bind(retry, null, reason) }, monitorEvent)); // Handle failure event, redo stream break; default: // No failure has occurred, handle monitor event break; } } function onPublisherOrStreamEnd(monitorCallback, retry, isPublisher, publisherOrStream, reason, description) { var response = { status: 'stream-ended', reason: reason, description: description }; if (this._ignoredStreamEnds[publisherOrStream.getStreamId()]) { this._logger.info('[%s] Ignoring stream end due to recovery in progress [%s]', this, publisherOrStream.getStreamId()); return; } switch (reason) { case 'egress-setup-failed': // Bad input params case 'ended': // Normal operation case 'censored': // Forced to stop var endedResponse = { status: reason, reason: reason, description: description }; if (isPublisher) { endedResponse.publisher = publisherOrStream; } else { endedResponse.mediaStream = publisherOrStream; } return monitorCallback(null, endedResponse); case 'custom': // Client ended publisher, do nothing return monitorCallback(null, response); case 'egress-failed': case 'capacity': // Don't inform the client, attempt to re-publish automatically after backoff setTimeout(function() { if (this._disposed) { return; } return retry(reason); }, capacityBackoffTimeout); return; case 'failed': case 'maintenance': case 'overload': // Don't inform the client, attempt to re-publish automatically return retry(reason); case 'app-background': default: // Give client option to re-publish response.retry = retry; return monitorCallback(null, response); } } return PCastExpress; });<reponame>kevingatera/kgatewebapp<gh_stars>1-10 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ShellMessageManager = undefined; var _ws; function _load_ws() { return _ws = _interopRequireDefault(require('ws')); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const EXECUTOR_PORT = 8081; /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. * * * @format */ const WS_URL = `ws://localhost:${EXECUTOR_PORT}/message?role=interface&name=Nuclide`; class ShellMessageManager { constructor() { this._url = WS_URL; } send(message) { if (this._ws == null) { // Currently, use cases only require a simple fire-and-forget interaction const ws = new (_ws || _load_ws()).default(this._url); this._ws = ws; ws.onopen = () => { ws.send(JSON.stringify(message)); ws.close(); }; ws.onerror = () => { atom.notifications.addWarning('Error connecting to React Native shell.'); }; ws.onclose = () => { this._ws = null; }; } } } exports.ShellMessageManager = ShellMessageManager;const StringTrimmer = require("string-trimmer"); module.exports = (app) => { app.use((req, res, next) => { if (req.headers["accept-language"]) { var langs = req.headers["accept-language"].split(","); langs = langs.map(lang => { return StringTrimmer.trim(lang.split(";")[0]); }); req.lang = langs[0]; req.langs = langs; } next(); }); };// const sinon = require("sinon") // const { expect, assert } = require("chai"); // // const mocks = require("../mocks/blogPosts"); // const CreatePost = require("../../lib/posts/createPost"); // const GetPost = require("../../lib/posts/getPost"); // const UpdatePost = require("../../lib/posts/updatePost"); // // describe("Post::", () => { // describe("Should create post from mock", () => { // it("Should create the post", (done) => { // let mockPost = mocks.post[0]; // let createPost = new CreatePost({post: mockPost}); // // createPost.savePostToDatabase((err) => { // assert(!err, "Error inserting data to database"); // return done(); // }); // }); // it("Should get the post", (done) => { // let mockPost = mocks.post[0]; // let getPost = new GetPost({title: mocks.post[0].title}); // // getPost.getPostByField((err, post) => { // assert(!err, "Error inserting data to database"); // expect(post.title).to.equal(mocks.post[0].title); // expect(post.link).to.equal(mocks.post[0].link); // return done(); // }); // }); // it("Should update the post", (done) => { // let mockPost = mocks.post[0]; // let updatePost = new GetPost({title: mocks.post[0].title}); // // updatePost.updatePostFields((err, post) => { // assert(!err, "Error inserting data to database"); // expect(post.title).to.equal(mocks.post[0].title); // expect(post.link).to.equal(mocks.post[0].link); // return done(); // }); // }); // it("Should get the post", (done) => { // let mockPost = mocks.post[0]; // let createPost = new CreatePost({post: mockPost}); // // createPost.savePostToDatabase() // expect().to.equal(mockPost.title); // return done(); // }); // it("Should delete the post", (done) => { // let mockPost = mocks.post[0]; // let createPost = new CreatePost({post: mockPost}); // // createPost.savePostToDatabase() // expect().to.equal(mockPost.title); // return done(); // }); // it("Should handle not getting the post", (done) => { // let mockPost = mocks.post[0]; // let createPost = new CreatePost({post: mockPost}); // // createPost.savePostToDatabase() // expect().to.equal(mockPost.title); // return done(); // }); // }); // }); import { configureStore } from '@reduxjs/toolkit'; import rootReducer from '../app/rootReducer'; import createSagaMiddleware from 'redux-saga'; import { watchfetchRandomPost } from './sagas'; import { persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; const persistConfig = { key: 'root', version: 1, storage } const persistedReducer = persistReducer(persistConfig, rootReducer); const sagaMiddleware = createSagaMiddleware(); const store = configureStore({ reducer: persistedReducer, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: { ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER] } }).concat(sagaMiddleware), }); sagaMiddleware.run(watchfetchRandomPost); export default store;import React, { Component } from 'react'; /** * Component for Flag Icon . * * @component * @example * return ( * <Icon name="flag" /> * ) */ class Icon extends Component { constructor(props) { super(props); } /** * Render the component */ render() { const { name, size = 20, className = '' } = this.props; return ( <svg className={`fill-current ${className}`} width={size.toString() + 'px'} height={size.toString() + 'px'}> <use xlinkHref={`/icons/solid.svg#${name}`} /> </svg> ); } } export default Icon; global.assert = require('core-assert') <filename>extras/apidoc/html/search/all_a.js var searchData= [ ['param_235',['param',['../group__group01.html#a5da2dcc72ae3a6f0ced1aad7594362d5',1,'si47x_bandwidth_config::param()'],['../group__group01.html#affb467645fbaf299d351c3fc7c0ed3bb',1,'si47x_ssb_mode::param()']]], ['patchpowerup_236',['patchPowerUp',['../group__group17.html#gafaabd6c73b7ad7c20ae959d5b75c1e71',1,'SI4735']]], ['patchpowerupnbfm_237',['patchPowerUpNBFM',['../group__group20.html#gabed83f2c503dc3b35ca115ef6b08d552',1,'SI4735']]], ['power_5fdown_238',['POWER_DOWN',['../_s_i4735_8h.html#aad04e0c9afdeec307d5b9cb2062d784d',1,'SI4735.h']]], ['power_5fpatch_239',['POWER_PATCH',['../_s_i4735_8h.html#a2e49c8fada1fbb8a01ad5a0adad2b559',1,'SI4735.h']]], ['power_5fup_240',['POWER_UP',['../_s_i4735_8h.html#abf6b929a6f72c48fdb78218394541db2',1,'SI4735.h']]], ['power_5fup_5fam_241',['POWER_UP_AM',['../_s_i4735_8h.html#a1c63dbfe18d80af288cc79a5da666993',1,'SI4735.h']]], ['power_5fup_5ffm_242',['POWER_UP_FM',['../_s_i4735_8h.html#a3d0f9d1b446b57f1f425654b6030fe02',1,'SI4735.h']]], ['power_5fup_5fwb_243',['POWER_UP_WB',['../_s_i4735_8h.html#a3adae4f49b7284531f4a9f74e64aae1d',1,'SI4735.h']]], ['powerdown_244',['powerDown',['../group__group07.html#gaa554b3390fb6c5a4d6661b96afae73ae',1,'SI4735']]], ['powerup_245',['powerUp',['../class_s_i4735.html#a1331b701088bda20bf0844e2e38be142',1,'SI4735']]] ]; <reponame>kirillDanshin/cerebral<filename>packages/node_modules/cerebral/src/Controller.js<gh_stars>0 import DependencyStore from './DependencyStore' import BaseController from './BaseController' import Model from './Model' import { Reaction } from './Reaction' import { Tag } from 'function-tree' import { ensureStrictPath, extractModuleProp, isComputedValue } from './utils' import { Compute } from './Compute' /* The controller is where everything is attached. The devtools is attached directly. Also a top level module is created. The controller creates the function tree that will run all sequences, based on top level providers and providers defined in modules */ class Controller extends BaseController { constructor(rootModule, options) { super( rootModule, Object.assign( { Model, }, options ) ) this.dependencyStore = new DependencyStore() this.flush = this.flush.bind(this) this.on('asyncFunction', (execution, funcDetails) => { if (!funcDetails.isParallel) { this.flush() } }) this.on('parallelStart', () => this.flush()) this.on( 'parallelProgress', (execution, currentPayload, functionsResolving) => { if (functionsResolving === 1) { this.flush() } } ) this.on('mutation', (mutation) => this.updateComputed(mutation)) this.on('end', () => this.flush()) extractModuleProp(this.module, 'reactions', (reactions, currentModule) => { if (reactions) { Object.keys(reactions) .filter((key) => reactions[key] instanceof Reaction) .forEach((key) => reactions[key].initialize()) } return reactions }) this.getState = this.getState.bind(this) this.getSequence = this.getSequence.bind(this) this.getSequences = this.getSequences.bind(this) } /* Whenever components needs to be updated, this method can be called */ flush(force) { const changes = this.model.flush() if (!force && !changes.length) { return } this.updateWatchers(changes, force) this.emit('flush', changes, Boolean(force)) } /* Flags computed as dirty related to mutations */ updateComputed(change) { const entities = this.dependencyStore.getUniqueEntities([change]) entities.forEach((entity) => { if (entity instanceof Compute) { entity.isDirty = true } }) } updateWatchers(changes, force) { let watchToUpdate = [] if (force) { watchToUpdate = this.dependencyStore.getAllUniqueEntities() } else { watchToUpdate = this.dependencyStore.getUniqueEntities(changes) } const startDateTime = Date.now() const start = typeof performance === 'undefined' ? Date.now() : performance.now() watchToUpdate.forEach((watch) => { // We skip computed as they have already been flagged if (watch instanceof Compute) { return } watch.onUpdate(changes, force) }) const end = typeof performance === 'undefined' ? Date.now() : performance.now() if (this.devtools && watchToUpdate.length) { this.devtools.sendWatchMap( watchToUpdate, changes, startDateTime, end - start ) } } /* Returns stuff based on tags/proxy */ get(tag, overrideProps = {}) { const context = this.createContext(overrideProps) const value = tag.getValue(context) if (isComputedValue(value)) { return value.getValue(overrideProps) } return value } /* Create an object used to grab data from tags */ createContext(props = {}, modulePath = []) { const modulePathString = modulePath.length ? modulePath.join('.') + '.' : '' return { props, controller: this, execution: { name: modulePathString, }, } } /* Creates a dependency map to be used with the store */ createDependencyMap(dependencies, props, modulePath) { const getters = this.createContext(props, modulePath) return dependencies.reduce((currentDepsMap, dependency) => { if (dependency instanceof Tag) { return dependency .getTags(getters) .reduce((updatedCurrentDepsMap, tag) => { if (tag.type === 'state' || tag.type === 'moduleState') { const value = tag.getValue(getters) if (isComputedValue(value)) { // We have to trigger the value to get the dependencyMap value.getValue(props) return Object.assign( updatedCurrentDepsMap, value.getDependencyMap() ) } const path = tag.getPath(getters) const strictPath = ensureStrictPath(path, this.getState(path)) updatedCurrentDepsMap[strictPath] = true } return updatedCurrentDepsMap }, currentDepsMap) } return currentDepsMap }, {}) } } export default Controller require('./helper'); var urlMap = strata.urlMap; describe('urlMap', function () { describe('by default', function () { beforeEach(function (callback) { call(urlMap(), '/', callback); }); it('returns 404', function () { assert.equal(status, 404); }); }); describe('with path-based definitions', function () { var innerApp = function (env, callback) { callback(200, { 'X-Script-Name': env.scriptName, 'X-Path-Info': env.pathInfo, 'Content-Type': 'text/plain' }, ''); }; var app = makeMap({ 'http://example.org/static': innerApp, '/path': innerApp, '/some/path': innerApp }); describe('GET /', function () { beforeEach(function (callback) { call(app, '/', callback); }); checkStatus(404); }); describe('GET /miss', function () { beforeEach(function (callback) { call(app, '/miss', callback); }); checkStatus(404); }); describe('GET /path', function () { beforeEach(function (callback) { call(app, '/path', callback); }); checkLocation(200, '/path', ''); }); describe('GET /path/', function () { beforeEach(function (callback) { call(app, '/path/', callback); }); checkLocation(200, '/path', '/'); }); describe('GET /some/path', function () { beforeEach(function (callback) { call(app, '/some/path', callback); }); checkLocation(200, '/some/path', ''); }); describe('GET /some/path/', function () { beforeEach(function (callback) { call(app, '/some/path/', callback); }); checkLocation(200, '/some/path', '/'); }); describe('GET /some///path//name', function () { beforeEach(function (callback) { call(app, '/some///path//name', callback); }); checkLocation(200, '/some/path', '//name'); }); describe('when scriptName is /elsewhere and pathInfo is /path/name', function () { beforeEach(function (callback) { call(app, mock.env({ scriptName: '/elsewhere', pathInfo: '/path/name' }), callback); }); checkLocation(200, '/elsewhere/path', '/name'); }); describe('when pathInfo is /static and Host is example.org', function () { beforeEach(function (callback) { call(app, mock.env({ pathInfo: '/static', headers: { 'Host': 'example.org' } }), callback); }); checkLocation(200, '/static', ''); }); describe('when pathInfo is /static/ and Host is example.org', function () { beforeEach(function (callback) { call(app, mock.env({ pathInfo: '/static/', headers: { 'Host': 'example.org' } }), callback); }); checkLocation(200, '/static', '/'); }); }); describe('with host-based definitions', function () { var app = makeMap({ '/': function (env, callback) { callback(200, { 'Content-Type': 'text/plain', 'X-Position': 'example.com', 'X-Host': env.headers['host'] || env.serverName }, ''); }, 'http://example.org/': function (env, callback) { callback(200, { 'Content-Type': 'text/plain', 'X-Position': 'example.org', 'X-Host': env.headers['host'] || env.serverName }, ''); }, 'http://subdomain.example.org/': function (env, callback) { callback(200, { 'Content-Type': 'text/plain', 'X-Position': 'subdomain.example.org', 'X-Host': env.headers['host'] || env.serverName }, ''); }, 'http://example.net/': function (env, callback) { callback(200, { 'Content-Type': 'text/plain', 'X-Position': 'example.net', 'X-Host': env.headers['host'] || env.serverName }, ''); } }); describe('GET /', function () { beforeEach(function (callback) { call(app, '/', callback); }); checkPosition(200, 'example.com'); }); describe('when pathInfo is / and Host is example.org', function () { beforeEach(function (callback) { call(app, mock.env({ pathInfo: '/', headers: { 'Host': 'example.org' } }), callback); }); checkPosition(200, 'example.org'); }); describe('when pathInfo is / and Host is example.net', function () { beforeEach(function (callback) { call(app, mock.env({ pathInfo: '/', headers: { 'Host': 'example.net' } }), callback); }); checkPosition(200, 'example.net'); }); describe('when serverName is example.org, pathInfo is /, and Host is subdomain.example.org', function () { beforeEach(function (callback) { call(app, mock.env({ serverName: 'example.org', pathInfo: '/', headers: { 'Host': 'subdomain.example.org' } }), callback); }); checkPosition(200, 'subdomain.example.org'); }); describe('GET / on Host example.org', function () { beforeEach(function (callback) { call(app, 'http://example.org/', callback); }); checkPosition(200, 'example.org'); }); describe('when serverName is example.info, pathInfo is /, and Host is example.info', function () { beforeEach(function (callback) { call(app, mock.env({ serverName: 'example.info', pathInfo: '/', headers: { 'Host': 'example.info' } }), callback); }); checkPosition(200, 'example.com'); }); describe('when serverName is example.info, serverPort is 9292, pathInfo is /, and Host is example.info:9292', function () { beforeEach(function (callback) { call(app, mock.env({ serverName: 'example.info', serverPort: '9292', pathInfo: '/', headers: { 'Host': 'example.info:9292' } }), callback); }); checkPosition(200, 'example.com'); }); }); describe('with nested urlMaps', function () { var app = makeMap({ '/some': makeMap({ '/path': makeMap({ '/name': function (env, callback) { callback(200, { 'Content-Type': 'text/plain', 'X-Position': '/some/path/name', 'X-Script-Name': env.scriptName, 'X-Path-Info': env.pathInfo }, ''); } }) }) }); describe('GET /some/path', function () { beforeEach(function (callback) { call(app, '/some/path', callback); }); checkStatus(404); }); describe('GET /some/path/name', function () { beforeEach(function (callback) { call(app, '/some/path/name', callback); }); checkPosition(200, '/some/path/name'); checkLocation(200, '/some/path/name', ''); }); }); describe('with multiple root apps', function () { var app = makeMap({ '/': function (env, callback) { callback(200, { 'Content-Type': 'text/plain', 'X-Position': 'root', 'X-Script-Name': env.scriptName, 'X-Path-Info': env.pathInfo }, ''); }, '/path': function (env, callback) { callback(200, { 'Content-Type': 'text/plain', 'X-Position': 'path', 'X-Script-Name': env.scriptName, 'X-Path-Info': env.pathInfo }, ''); } }); describe('GET /path', function () { beforeEach(function (callback) { call(app, '/path', callback); }); checkPosition(200, 'path'); checkLocation(200, '/path', ''); }); describe('GET /path/name', function () { beforeEach(function (callback) { call(app, '/path/name', callback); }); checkPosition(200, 'path'); checkLocation(200, '/path', '/name'); }); describe('GET /', function () { beforeEach(function (callback) { call(app, '/', callback); }); checkPosition(200, 'root'); checkLocation(200, '', '/'); }); describe('GET /name', function () { beforeEach(function (callback) { call(app, '/name', callback); }); checkPosition(200, 'root'); checkLocation(200, '', '/name'); }); describe('GET /http://example.org/another', function () { beforeEach(function (callback) { call(app, '/http://example.org/another', callback); }); checkPosition(200, 'root'); checkLocation(200, '', '/http://example.org/another'); }); }); }); // Creates a new urlMap from the location/app pairs in locationsMap. function makeMap(locationsMap) { var map = urlMap(); for (var location in locationsMap) { map.map(location, locationsMap[location]); } return map; } // Checks the last response for the given variables. function checkLocation(code, scriptName, pathInfo) { checkStatus(code); checkHeader('X-Script-Name', scriptName); checkHeader('X-Path-Info', pathInfo); } // Checks the last response for the given variables. function checkPosition(code, position) { checkStatus(code); checkHeader('X-Position', position); } /* ************************************************************************* * The contents of this file are subject to the Openbravo Public License * Version 1.1 (the "License"), being the Mozilla Public License * Version 1.1 with a permitted attribution clause; you may not use this * file except in compliance with the License. You may obtain a copy of * the License at http://www.openbravo.com/legal/license.html * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * The Original Code is Openbravo ERP. * The Initial Developer of the Original Code is Openbravo SLU * All portions are Copyright (C) 2010-2014 Openbravo SLU * All Rights Reserved. * Contributor(s): ______________________________________. ************************************************************************ */ // = OB Classic Window = // // Implements the view which shows a classic OB window in a Smartclient HTMLFlow component. The // classic OB window is shown in a tab in the multi-tab interface. // isc.defineClass('OBClassicWindow', isc.HTMLPane).addProperties({ showsItself: false, contentsType: 'page', windowId: '', tabId: '', recordId: '', // tab title is the title in the MDI tab, it is set in the view-manager // and updated below tabTitle: null, processId: null, formId: null, mappingName: null, command: 'DEFAULT', showEdges: false, styleName: 'obClassicWindow', appURL: OB.Application.contextUrl + 'security/Menu.html', obManualURL: '', padding: 0, margin: 0, height: '100%', width: '100%', // ignore the tab info update for one time, to prevent double history entries ignoreTabInfoUpdate: true, hasBeenDrawnOnce: false, appFrameWindow: null, // forcing this this tab to be in the bottom in order to make context menu of // other tabs work in chrome, see https://issues.openbravo.com/view.php?id=27959 zIndex: 1 }); isc.OBClassicWindow.addMethods({ // ** {{{ updateTabInformation }}} ** // // Is called to update the tab information of an opened classic window. updateTabInformation: function (windowId, tabId, recordId, command, obManualURL, title) { // ignore the first time if (this.ignoreTabInfoUpdate) { this.ignoreTabInfoUpdate = false; return; } this.windowId = windowId || ''; this.tabId = tabId || ''; this.recordId = recordId || ''; this.command = (command ? command.toUpperCase() : '') || 'DEFAULT'; this.obManualURL = obManualURL || ''; this.tabTitle = null; OB.Layout.HistoryManager.updateHistory(); }, // ** {{{ refreshTab }}} ** // // Is used to handle the refresh keyboard shortcut, clicks the refresh button // of a classic window. refreshTab: function () { if (this.getAppFrameWindow()) { this.getAppFrameWindow().document.getElementById('buttonRefresh').onclick(); } }, // ** {{{ tabSelected }}} ** // // Is used to place the focus in a tab after one of the flyouts is closed. tabSelected: function () { var appFrameWindow = this.getAppFrameWindow(); if (appFrameWindow && appFrameWindow.putFocusOnWindow && !appFrameWindow.OB_NoRefocusAfterTabSelection) { appFrameWindow.putFocusOnWindow(); } }, initWidget: function (args) { var urlCharacter = '?'; if (this.appURL.indexOf('?') !== -1) { urlCharacter = '&'; } if (this.keyParameter) { this.contentsURL = this.appURL + urlCharacter + 'url=' + this.mappingName + '&' + this.keyParameter + '=' + this.recordId + '&noprefs=true&Command=DIRECT&hideMenu=true'; } else if (this.obManualURL && this.obManualURL !== '') { this.obManualURL = this.obManualURL.replace('?', '&'); this.contentsURL = this.appURL + urlCharacter + 'url=' + this.obManualURL + '&noprefs=true&hideMenu=true'; if (this.obManualURL.indexOf('Command=') === -1) { // Add command in case it is not already set in the obManualURL this.contentsURL = this.contentsURL + '&Command=' + this.command; } } else { this.contentsURL = this.appURL + urlCharacter + 'Command=' + this.command + '&noprefs=true'; if (this.recordId !== '') { this.contentsURL = this.contentsURL + '&windowId=' + this.windowId; } this.contentsURL = this.contentsURL + '&tabId=' + this.tabId; if (this.recordId !== '') { this.contentsURL = this.contentsURL + '&recordId=' + this.recordId; } this.contentsURL = this.contentsURL + '&hideMenu=true'; } this.setAsActiveIFrame(); this.Super('initWidget', args); }, // ** {{{ getIframeWindow }}} ** // // Returns the contentWindow object of the iframe implementing the classic // window. getIframeWindow: function () { var container, iframes; container = this.getHandle(); if (container && container.getElementsByTagName) { iframes = container.getElementsByTagName('iframe'); if (iframes.length > 0) { return (iframes[0].contentWindow ? iframes[0].contentWindow : null); } } return null; }, // ** {{{ getAppFrameWindow }}} ** // // Returns the appFrame object of the contentWindow of the iframe implementing // the classic window. getAppFrameWindow: function () { var iframe; if (this.appFrameWindow !== null) { return this.appFrameWindow; } iframe = this.getIframeWindow(); try { this.appFrameWindow = (iframe && iframe.appFrame ? iframe.appFrame : null); // caching reference } catch (e) { //To avoid cross-domain JS error (in case it exists) this.appFrameWindow = null; } return this.appFrameWindow; }, // The following methods are related to history management, i.e. that a // specific window is only opened once. getBookMarkParams: function () { var result = {}; if (this.recordId) { result.recordId = this.recordId; } if (this.windowId) { result.windowId = this.windowId; } if (this.obManualURL) { result.obManualURL = this.obManualURL; } if (this.command) { result.command = this.command; } if (this.tabId) { result.tabId = this.tabId; } if (this.processId) { result.processId = this.processId; } if (this.formId) { result.formId = this.formId; } if (this.keyParameter) { result.keyParameter = this.keyParameter; } if (this.mappingName) { result.mappingName = this.mappingName; } return result; }, isEqualParams: function (params) { if (params && (this.recordId || params.recordId) && params.recordId !== this.recordId) { return false; } if (params && (this.command || params.command) && params.command !== this.command) { return false; } if (params && (this.tabId || params.tabId) && params.tabId !== this.tabId) { return false; } if (params && (this.formId || params.formId) && params.formId !== this.formId) { return false; } if (params && (this.windowId || params.windowId) && params.windowId !== this.windowId) { return false; } if (params && (this.processId || params.processId) && params.processId !== this.processId) { return false; } return true; }, isSameTab: function (viewName, params) { if (viewName !== 'OBClassicWindow') { return false; } if (params && (params.obManualURL || this.obManualURL) && params.obManualURL === this.obManualURL) { return true; } if (params && (this.windowId || params.windowId) && params.windowId === this.windowId) { return true; } if (params && (this.processId || params.processId) && params.processId === this.processId) { return true; } if (params && (this.formId || params.formId) && params.formId === this.formId) { return true; } if ((!params || params.tabId === '') && this.tabId === '') { return true; } return params.tabId === this.tabId; }, // ** {{{ getHelpView }}} ** // // Returns the view definition of the help window for this classic window. getHelpView: function () { if (this.windowId) { // tabTitle is set in the viewManager return { viewId: 'ClassicOBHelp', tabTitle: this.tabTitle + ' - ' + OB.I18N.getLabel('UINAVBA_Help'), windowId: this.windowId, windowType: 'W', windowName: this.tabTitle }; } if (this.processId) { return { viewId: 'ClassicOBHelp', windowId: null, tabTitle: this.tabTitle + ' - ' + OB.I18N.getLabel('UINAVBA_Help'), windowType: 'R', windowName: this.processId }; } if (this.formId) { return { viewId: 'ClassicOBHelp', windowId: null, tabTitle: this.tabTitle + ' - ' + OB.I18N.getLabel('UINAVBA_Help'), windowType: 'X', windowName: this.formId }; } return null; }, // ** {{{ saveRecord }}} ** // // Is used for supporting autosave, saves the specific tab of the window. // Calls the server to do the actual save, the response calls the callback // method. saveRecord: function ( /* String */ tabID, /* Function */ callback) { var postData, reqObj, appFrame = this.appFrameWindow || this.getAppFrameWindow(), saveCallback = callback || this.ID + '.saveCallback(rpcResponse, data, rpcRequest)', tabid = tabID || ''; postData = {}; OB.Utilities.addFormInputsToCriteria(postData, appFrame); postData.Command = 'SAVE_XHR'; postData.tabID = tabid; reqObj = { params: postData, callback: saveCallback, evalResult: false, httpMethod: 'POST', useSimpleHttp: true, actionURL: OB.Application.contextUrl + postData.mappingName }; isc.RPCManager.sendRequest(reqObj); }, // ** {{{ saveCallback }}} ** // // If the save is successfull closes the tab. saveCallback: function (rpcResponse, data, rpcRequest) { var result = eval('(' + data + ')'), appFrame = this.appFrameWindow || this.getAppFrameWindow(); if (result && result.oberror) { if (result.oberror.type === 'Success') { appFrame.isUserChanges = false; OB.MainView.TabSet.removeTab(OB.MainView.TabSet.getTab(result.tabid)); } else { appFrame.location.href = result.redirect; } } }, // Waits until the iFrame has been loaded, and sets it as activeFrame // See issue https://issues.openbravo.com/view.php?id=25558 setAsActiveIFrame: function (nCalls) { var iFrame, me = this, parentFrame; if (!nCalls) { nCalls = 0; } else if (nCalls > 20) { // Prevent infinite recursion return; } iFrame = this.getAppFrameWindow(); if (!iFrame) { setTimeout(function () { me.setAsActiveIFrame(nCalls++); }, 500); } else { parentFrame = iFrame.parent; while (parentFrame.name !== '') { parentFrame = parentFrame.parent; } if (parentFrame.parent) { parentFrame.parent.activeFrame = iFrame; } } } }); // Maintained to support recent items which use the old name // NOTE: can be removed when the user interface is released in production in Q1 2011 // at that time the recent items should have been cleaned up isc.defineClass('ClassicOBWindow', isc.OBClassicWindow);import { delay } from 'redux-saga'; import { takeEvery, all, put } from 'redux-saga/effects'; import actions from '#actions'; import { NOTIFICATION_TYPE_ERROR, NOTIFICATION_TYPE_WARNING, NOTIFICATION_TYPE_SUCCESS, } from '~shared/data/constants'; import isObject from '~shared/utils/isObject'; import { IS_TESTING } from '~shared/config'; let counter = 0; function* handleAction({ payload }) { if (payload && isObject(payload)) { const { errorMessage, warningMessage, successMessage } = payload; let nextPayload; if (errorMessage) { nextPayload = { text: errorMessage, type: NOTIFICATION_TYPE_ERROR, }; } if (warningMessage) { nextPayload = { text: warningMessage, type: NOTIFICATION_TYPE_WARNING, }; } if (successMessage) { nextPayload = { text: successMessage, type: NOTIFICATION_TYPE_SUCCESS, }; } if (nextPayload) { counter += 1; nextPayload.id = counter; yield put(actions.systemNotificationRecieved(nextPayload)); if (!IS_TESTING) { yield delay(3000); yield put(actions.systemNotificationExpired(counter)); } } } } function* startNotificationsService() { yield all([ takeEvery('*', handleAction), ]); } export default startNotificationsService; import "./app.jsx"; const watch = require('gulp-watch'); const jshint = require('gulp-jshint'); const gulp = require('gulp'); const pkg = require('./package'); const jshintCfg = pkg.jshintConfig; jshintCfg.lookup = false; gulp.task('default', () => { // code goes here }); gulp.task('lint', () => { return gulp.watch([ './*.js', './lib/*.js' ], () => { gulp.src([ './lib/*.js', './*.js' ]) .pipe(jshint(jshintCfg)) .pipe(jshint.reporter('unix')); }); }); <reponame>jessemillar/Lorina var moonCount = 10; var starCount = 2000; var dustCount = 1000; var earthSpeed = 0.5; var earthFriction = earthSpeed / 15; var starSpeed = 0.4; var starFriction = 0.035; var lorina = new l.lorina(); lorina.setTitle('SPACE!') .setColor('#111111') .makeFullscreen() .setRoomSize(l.globals.dom.width * 2, l.globals.dom.height * 2) .appendCanvas(); var typewriter = new l.typewriter(); typewriter.setFont('Wendy').setColor('#FFFFFF').setAlignment('center').setSize(35); var moons = new l.group(); var stars = new l.group(); var dusties = new l.group(); var earth = new l.entity(); earth.setSprite('images/earth.png') .setPosition(l.globals.room.width / 2, l.globals.room.height / 2) .setSize(125, 125) .setAnchor(125 / 2, 125 / 2) .setBound(-125 / 2, -125 / 2, 125, 125) .setFriction(earthFriction); var earth2 = new l.entity(); earth2.setSprite('images/earth.png') .setPosition(l.globals.room.width / 2 + 200, l.globals.room.height / 2 + 200) .setAnchor(125 / 2, 125 / 2); var tool = new l.tool(); var i = moonCount; while (i--) { var entity = 'moon' + i; var moon = new l.entity(); moon.setSprite('images/moon.png') .setPosition(tool.random(0, l.globals.room.width), tool.random(0, l.globals.room.height)) .setSize(100, 100) .setAnchor(100 / 2, 100 / 2) .setBound(-100 / 2, -100 / 2, 100, 100) .setFriction(starFriction); moons.add(moon); } var i = starCount; while (i--) { var entity = 'star' + i; var entity = new l.entity(); entity.setSprite('images/star.png') .setAnchor(4, 4) .setPosition(tool.random(0, l.globals.room.width), tool.random(0, l.globals.room.height)) .setFriction(starFriction); stars.add(entity); } var i = dustCount; while (i--) { var entity = 'dust' + i; var entity = new l.entity(); entity.setSprite('images/dust.png') .setAnchor(2, 2) .setPosition(tool.random(0, l.globals.room.width), tool.random(0, l.globals.room.height)); dusties.add(entity); } var keyboard = new l.keyboard(); var camera = new l.camera(); // I would recommend that you keep the data for your room functions in an external file and reference it here var main = function() { if (keyboard.up || keyboard.w) { earth.pushVertical(-earthSpeed); } else if (keyboard.down || keyboard.s) { earth.pushVertical(earthSpeed); } if (keyboard.left || keyboard.a) { earth.pushHorizontal(-earthSpeed); } else if (keyboard.right || keyboard.d) { earth.pushHorizontal(earthSpeed); } stars.pullToward(earth, starSpeed).applyPhysics(); earth.bounce().applyPhysics(); var j = tool.checkCollision(earth, moons); if (j) { j.delete(); camera.shake(2, 35, 250); } camera.follow(earth); lorina.blank(); typewriter.setPosition(l.globals.room.width / 2, l.globals.room.height / 2 - 200).write('Hello, World. Move with the arrow keys.'); earth.buffer(); // earth2.buffer() moons.buffer(); stars.buffer(); dusties.buffer(); lorina.draw(); }; lorina.start(main); // Only call once the room functions are defined<gh_stars>1000+ const t = require('../test-lib/test.js'); const assert = require('assert'); const _ = require('lodash'); let apos; describe('Docs', function() { this.timeout(t.timeout); after(function() { return t.destroy(apos); }); // EXISTENCE it('should be a property of the apos object', async function() { apos = await t.create({ root: module, modules: { 'test-people': { extend: '@apostrophecms/piece-type', fields: { add: { _friends: { type: 'relationship', max: 1, withType: 'test-people', label: 'Friends' } } } }, '@apostrophecms/page': { options: { park: [], types: [ { name: 'test-page', label: 'Test Page' } ] } }, 'test-page': { extend: '@apostrophecms/page-type' } } }); assert(apos.doc); }); it('should have a db property', function() { assert(apos.doc.db); }); /// /// // SETUP /// /// it('should make sure all of the expected indexes are configured', async function() { const expectedIndexes = [ 'type', 'slug', 'titleSortified' ]; const actualIndexes = []; const info = await apos.doc.db.indexInformation(); // Extract the actual index info we care about. _.forEach(info, function(index) { actualIndexes.push(index[0][0]); }); // Now make sure everything in expectedIndexes is in actualIndexes. _.forEach(expectedIndexes, function(index) { assert(_.includes(actualIndexes, index)); }); // Lastly, make sure there is a text index present assert(info.highSearchText_text_lowSearchText_text_title_text_searchBoost_text[0][1] === 'text'); }); it('should make sure there is no test data hanging around from last time', async function() { // Attempt to purge the entire aposDocs collection await apos.doc.db.deleteMany({}); // Make sure it went away const docs = await apos.doc.db.find({ slug: 'larry' }).toArray(); assert(docs.length === 0); }); it('should be able to use db to insert documents', async function() { const testItems = [ { _id: 'lori:en:published', aposDocId: 'lori', aposLocale: 'en:published', slug: 'lori', visibility: 'public', type: 'test-people', firstName: 'Lori', lastName: 'Pizzaroni', age: 32, alive: true }, { _id: 'larry:en:published', aposDocId: 'larry', aposLocale: 'en:published', slug: 'larry', visibility: 'public', type: 'test-people', firstName: 'Larry', lastName: 'Cherber', age: 28, alive: true }, { _id: 'carl:en:published', aposDocId: 'carl', aposLocale: 'en:published', slug: 'carl', visibility: 'public', type: 'test-people', firstName: 'Carl', lastName: 'Sagan', age: 62, alive: false, friendsIds: [ 'larry' ] } ]; const response = await apos.doc.db.insertMany(testItems); assert(response.result.ok === 1); assert(response.insertedCount === 3); }); it('should be able to fetch schema relationships', async function() { const manager = apos.doc.getManager('test-people'); const req = apos.task.getAnonReq(); assert(manager); assert(manager.find); assert(manager.schema); const cursor = await manager.find(req, { slug: 'carl' }); assert(cursor); const person = await cursor.toObject(); assert(person); assert(person.slug === 'carl'); assert(person._friends); assert(person._friends[0].slug === 'larry'); }); it('should support custom context menu (required only)', async function() { const operation = { context: 'update', action: 'test', label: 'Menu Label', modal: 'SomeModalComponent' }; assert.strictEqual(apos.doc.contextOperations.length, 0); apos.doc.addContextOperation('test-people', operation); assert.strictEqual(apos.doc.contextOperations.length, 1); assert.deepStrictEqual(apos.doc.contextOperations[0], { ...operation, moduleName: 'test-people' }); }); it('should support custom context menu (with optional)', async function() { apos.doc.contextOperations = []; const operation = { context: 'update', action: 'test', label: 'Menu Label', modal: 'SomeModalComponent', manuallyPublished: true, modifiers: [ 'danger' ] }; assert.strictEqual(apos.doc.contextOperations.length, 0); apos.doc.addContextOperation('test-people', operation); assert.strictEqual(apos.doc.contextOperations.length, 1); assert.deepStrictEqual(apos.doc.contextOperations[0], { ...operation, moduleName: 'test-people' }); }); it('should override custom context menu', async function() { apos.doc.contextOperations = []; const operation1 = { context: 'update', action: 'test', label: 'Op1', modal: 'SomeModalComponent' }; const operation2 = { context: 'update', action: 'test', label: 'Op2', modal: 'SomeModalComponent' }; assert.strictEqual(apos.doc.contextOperations.length, 0); apos.doc.addContextOperation('test-people', operation1); apos.doc.addContextOperation('test-people', operation2); assert.strictEqual(apos.doc.contextOperations.length, 1); assert.deepStrictEqual(apos.doc.contextOperations[0], { ...operation2, moduleName: 'test-people' }); }); /// /// // UNIQUENESS /// /// it('should fail if you try to insert a document with the same unique key twice', async function() { try { await apos.doc.db.insertMany([ { _id: 'peter:en:published', aposDocId: 'peter', aposLocale: 'en:published', type: 'test-people', visibility: 'loginRequired', age: 70, slug: 'peter' }, // ids will not conflict, but slug will { _id: 'peter2:en:published', aposDocId: 'peter2', aposLocale: 'en:published', type: 'test-people', visibility: 'loginRequired', age: 70, slug: 'peter' } ]); assert(false); } catch (e) { assert(e); assert(e.code === 11000); } }); /// /// // FINDING /// /// it('should have a find method on docs that returns a query', function() { const query = apos.doc.find(apos.task.getAnonReq()); assert(query); assert(query.toArray); }); it('should be able to find all test documents and output them as an array', async function () { const cursor = apos.doc.find(apos.task.getAnonReq(), { type: 'test-people' }); const docs = await cursor.toArray(); // There should be only 3 results. assert(docs.length === 3); // They should all have a type of test-people assert(docs[0].type === 'test-people'); }); /// /// // PROJECTIONS /// /// it('should be able to specify which fields to get by passing a projection object', async function() { const cursor = apos.doc.find(apos.task.getAnonReq(), { type: 'test-people' }, { project: { age: 1 } }); const docs = await cursor.toArray(); // There SHOULD be an age assert(docs[0].age); // There SHOULD NOT be a firstName assert(!docs[0].firstName); }); /// /// // SORTING /// /// it('should be able to sort', async function () { const cursor = apos.doc.find(apos.task.getAnonReq(), { type: 'test-people' }).sort({ age: 1 }); const docs = await cursor.toArray(); assert(docs[0].slug === 'larry'); }); it('should be able to sort by multiple keys', async function () { const cursor = apos.doc.find(apos.task.getAnonReq(), { type: 'test-people' }).sort({ firstName: 1, age: 1 }); const docs = await cursor.toArray(); assert(docs[0].slug === 'carl'); assert(docs[1].slug === 'larry'); }); /// /// // INSERTING /// /// it('should have an "insert" method that returns a new database object', async function() { const object = { slug: 'one', visibility: 'public', type: 'test-people', firstName: 'Lori', lastName: 'Ferber', age: 15, alive: true }; const response = await apos.doc.insert(apos.task.getReq(), object); assert(response); assert(response._id); assert(response._id.endsWith(':en:published')); assert(response._id === `${response.aposDocId}:${response.aposLocale}`); // Direct insertion in published locale should autocreate // a corresponding draft for internal consistency const draft = await apos.doc.db.findOne({ _id: `${response.aposDocId}:en:draft` }); assert(draft); // Unique index allows for duplicates across locales assert(object.slug === draft.slug); // Content properties coming through assert(draft.firstName === response.firstName); }); it('should be able to insert a new object into the docs collection in the database', async function() { const cursor = apos.doc.find(apos.task.getReq(), { type: 'test-people', slug: 'one' }); const docs = await cursor.toArray(); assert(docs[0].slug === 'one'); }); it('should append the slug property with a numeral if inserting an object whose slug already exists in the database', async function() { const object = { slug: 'one', visibility: 'public', type: 'test-people', firstName: 'Harry', lastName: 'Gerber', age: 29, alive: true }; const doc = await apos.doc.insert(apos.task.getReq(), object); assert(doc); assert(doc.slug.match(/^one\d+$/)); }); it('should add the aposDocId to the related documents\' relatedReverseIds field and update their `cacheInvalidatedAt` field', async function() { const object = { aposDocId: 'paul', aposLocale: 'en:published', slug: 'paul', visibility: 'public', type: 'test-people', firstName: 'Paul', lastName: 'McCartney', age: 24, alive: false, friendsIds: [ 'carl', 'larry' ], _friends: [ { _id: 'carl:en:published' }, { _id: 'larry:en:published' } ] }; const response = await apos.doc.insert(apos.task.getReq(), object); const carlDoc = await apos.doc.db.findOne({ slug: 'carl', aposLocale: 'en:published' }); const larryDoc = await apos.doc.db.findOne({ slug: 'larry', aposLocale: 'en:published' }); assert(carlDoc.relatedReverseIds.length === 1); assert(carlDoc.relatedReverseIds[0] === 'paul'); assert(carlDoc.cacheInvalidatedAt.getTime() === response.updatedAt.getTime()); assert(larryDoc.relatedReverseIds.length === 1); assert(larryDoc.relatedReverseIds[0] === 'paul'); assert(larryDoc.cacheInvalidatedAt.getTime() === response.updatedAt.getTime()); }); it('should not allow you to call the insert method if you are not an admin', async function() { const object = { slug: 'not-for-you', visibility: 'loginRequired', type: 'test-people', firstName: 'Darry', lastName: 'Derrber', age: 5, alive: true }; try { await apos.doc.insert(apos.task.getAnonReq(), object); assert(false); } catch (e) { assert(e); } }); /// /// // UPDATING /// /// it('should have an "update" method on docs that updates an existing database object', async function() { const req = apos.task.getReq(); const docs = await apos.doc.find(req, { slug: 'one' }).toArray(); // We should have one document in our results. assert(docs); assert(docs.length === 1); // Grab the object and update the `alive` property. const object = docs[0]; object.alive = false; const updated = await apos.doc.update(apos.task.getReq(), object); // Has the property been updated? assert(updated); assert(updated.alive === false); }); it('should append an updated slug with a numeral if the updated slug already exists', async function() { const req = apos.task.getReq(); const cursor = apos.doc.find(req, { type: 'test-people', slug: 'one' }); const doc = await cursor.toObject(); assert(doc); doc.slug = 'peter'; const updated = await apos.doc.update(req, doc); assert(updated); // Has the updated slug been appended? assert(updated.slug.match(/^peter\d+$/)); }); it('should be able to fetch all unique firstNames with toDistinct', async function() { const firstNames = await apos.doc.find(apos.task.getReq(), { type: 'test-people' }).toDistinct('firstName'); assert(Array.isArray(firstNames)); assert(firstNames.length === 5); assert(_.includes(firstNames, 'Larry')); }); it('should be able to fetch all unique firstNames and their counts with toDistinct and distinctCounts', async function() { const req = apos.task.getReq(); const cursor = apos.doc.find(req, { type: 'test-people' }).distinctCounts(true); const firstNames = await cursor.toDistinct('firstName'); assert(Array.isArray(firstNames)); assert(firstNames.length === 5); assert(_.includes(firstNames, 'Larry')); const counts = await cursor.get('distinctCounts'); assert(counts.Larry === 1); assert(counts.Lori === 2); }); it('should remove the aposDocId from the related documents\' relatedReverseIds field and update their `cacheInvalidatedAt` field', async function() { const paulDoc = await apos.doc.db.findOne({ slug: 'paul', aposLocale: 'en:published' }); // carl removed from paul's related friends, only larry remains const object = { ...paulDoc, friendsIds: [ 'larry' ], _friends: [ { _id: 'larry:en:published' } ] }; const response = await apos.doc.update(apos.task.getReq(), object); const carlDoc = await apos.doc.db.findOne({ slug: 'carl', aposLocale: 'en:published' }); const larryDoc = await apos.doc.db.findOne({ slug: 'larry', aposLocale: 'en:published' }); assert(carlDoc.relatedReverseIds.length === 0); assert(carlDoc.cacheInvalidatedAt.getTime() === response.updatedAt.getTime()); assert(larryDoc.relatedReverseIds.length === 1); assert(larryDoc.relatedReverseIds[0] === 'paul'); assert(larryDoc.cacheInvalidatedAt.getTime() === response.updatedAt.getTime()); }); it('should update the related reverse documents\' `cacheInvalidatedAt` field', async function() { const object = { aposDocId: 'john', aposLocale: 'en:published', slug: 'john', visibility: 'public', type: 'test-people', firstName: 'John', lastName: 'McClane', age: 40, alive: true, friendsIds: [ 'carl' ], _friends: [ { _id: 'carl:en:published' } ] }; await apos.doc.insert(apos.task.getReq(), object); const carlDoc = await apos.doc.db.findOne({ slug: 'carl', aposLocale: 'en:published' }); // update carl, now john (related reverse friend) should have its `cacheInvalidatedAt` field updated as well const response = await apos.doc.update(apos.task.getReq(), { ...carlDoc, alive: false }); const johnDoc = await apos.doc.db.findOne({ slug: 'john', aposLocale: 'en:published' }); assert(johnDoc.cacheInvalidatedAt.getTime() === response.updatedAt.getTime()); }); it('should update the pieces parent page\'s `cacheInvalidatedAt` field', async function() { const page = { slug: '/parent/new-page', visibility: 'public', type: 'test-page', title: 'New Page' }; const object = { aposDocId: 'bruce', aposLocale: 'en:published', slug: 'bruce', visibility: 'public', type: 'test-people', firstName: 'Bruce', lastName: 'Lee', age: 30, alive: false, _parentSlug: '/parent/new-page' }; await apos.doc.insert(apos.task.getReq(), page); const response = await apos.doc.insert(apos.task.getReq(), object); const pageDoc = await apos.doc.db.findOne({ slug: '/parent/new-page', aposLocale: 'en:published' }); assert(pageDoc.cacheInvalidatedAt.getTime() === response.updatedAt.getTime()); }); it('should not allow you to call the update method if you are not an admin', async function() { const cursor = apos.doc.find(apos.task.getAnonReq(), { type: 'test-people', slug: 'lori' }); const doc = cursor.toObject(); assert(doc); doc.slug = 'laurie'; try { await apos.doc.update(apos.task.getAnonReq(), doc); assert(false); } catch (e) { assert(e); } }); /// /// // ARCHIVE /// /// it('should archive docs by updating them', async function() { const req = apos.task.getReq(); const doc = await apos.doc.find(req, { type: 'test-people', slug: 'carl' }).toObject(); const archived = await apos.doc.update(req, { ...doc, archived: true }); assert(archived.archived === true); }); it('should not be able to find the archived object', async function() { const req = apos.task.getReq(); const doc = await apos.doc.find(req, { slug: 'carl' }).toObject(); assert(!doc); }); it('should not allow you to call the archive method if you are not an admin', async function() { try { await apos.doc.archived(apos.task.getAnonReq(), { slug: 'lori' }); assert(false); } catch (e) { assert(e); } }); it('should be able to find the archived object when using the "archived" method on find()', async function() { // Look for the archived doc with the `deduplicate-` + its `_id` + its `name` properties. const doc = await apos.doc.find(apos.task.getReq(), { slug: 'deduplicate-carl-carl' }).archived(true).toObject(); assert(doc); assert(doc.archived); }); /// /// // RESCUE /// /// it('should rescue a doc by updating the "archived" property from an object', async function() { const req = apos.task.getReq(); const doc = await apos.doc.find(req, { slug: 'deduplicate-carl-carl' }).archived(null).toObject(); await apos.doc.update(req, { ...doc, archived: false }); const newDoc = await apos.doc.find(req, { slug: 'carl' }).toObject(); // We should have a document. assert(newDoc); assert(newDoc.slug === 'carl'); assert(newDoc.archived === false); }); it('should not allow you to call the restore method if you are not an admin', async function() { try { await apos.doc.restore(apos.task.getAnonReq(), { slug: 'carl' }); assert(false); } catch (e) { assert(e); } }); it('should throw an exception on find() if you fail to pass req as the first argument', async function() { try { await apos.doc.find({ slug: 'larry' }); assert(false); } catch (e) { assert(e); } }); it('should respect _ids()', async function() { const testItems = []; let i; for (i = 0; (i < 100); i++) { testItems.push({ _id: `i${i}:en:published`, aposDocId: `i${i}`, aposLocale: 'en:published', slug: `i${i}`, visibility: 'public', type: 'test', title: 'title: ' + i }); } await apos.doc.db.insertMany(testItems); const docs = await apos.doc.find(apos.task.getAnonReq(), {}) ._ids([ 'i7:en:published', 'i3:en:published', 'i27:en:published', 'i9:en:published' ]).toArray(); assert(docs[0]._id === 'i7:en:published'); assert(docs[0].aposDocId === 'i7'); assert(docs[0].aposLocale === 'en:published'); assert(docs[1]._id === 'i3:en:published'); assert(docs[2]._id === 'i27:en:published'); assert(docs[3]._id === 'i9:en:published'); assert(!docs[4]); }); it('should respect _ids with skip and limit', async function() { // Relies on test data of previous test const docs = await apos.doc.find(apos.task.getAnonReq(), {}) ._ids([ 'i7:en:published', 'i3:en:published', 'i27:en:published', 'i9:en:published' ]).skip(2).limit(2).toArray(); assert(docs[0]._id === 'i27:en:published'); assert(docs[1]._id === 'i9:en:published'); assert(!docs[2]); }); it('should be able to lock a document', async function() { const req = apos.task.getReq(); const doc = await apos.doc.db.findOne({ _id: 'i27:en:published' }); try { await apos.doc.lock(req, doc, 'abc'); } catch (e) { assert(!e); } }); it('should not be able to lock a document with a different tabId', async function() { const req = apos.task.getReq(); const doc = await apos.doc.db.findOne({ _id: 'i27:en:published' }); try { await apos.doc.lock(req, doc, 'def'); } catch (e) { assert(e); assert(e.name === 'locked'); } }); it('should be able to refresh the lock with the same tabId', async function() { const req = apos.task.getReq(); const doc = await apos.doc.db.findOne({ _id: 'i27:en:published' }); try { await apos.doc.lock(req, doc, 'abc'); } catch (e) { assert(!e); } }); it('should be able to unlock a document', async function() { const req = apos.task.getReq(); const doc = await apos.doc.db.findOne({ _id: 'i27:en:published' }); try { await apos.doc.unlock(req, doc, 'abc'); } catch (e) { assert(false); } }); it('should be able to re-lock an unlocked document', async function() { const req = apos.task.getReq(); const doc = await apos.doc.db.findOne({ _id: 'i27:en:published' }); try { await apos.doc.lock(req, doc, 'def'); } catch (e) { assert(false); } }); it('should be able to lock a locked document with force: true', async function() { const req = apos.task.getReq(); const doc = await apos.doc.db.findOne({ _id: 'i27:en:published' }); try { await apos.doc.lock(req, doc, 'abc', { force: true }); } catch (e) { assert(false); } }); it('should be able to recover if the text index weights are mysteriously wrong at startup', async function() { await apos.doc.db.dropIndex('highSearchText_text_lowSearchText_text_title_text_searchBoost_text'); await apos.doc.db.createIndex({ highSearchText: 'text', lowSearchText: 'text', title: 'text', searchBoost: 'text' }, { default_language: 'none', weights: { // These are the weird weights we've seen when this // mystery bug crops up, flunking createIndex on a // later startup title: 1, searchBoost: 1, highSearchText: 1, lowSearchText: 1 } }); await apos.doc.createTextIndex(); }); /// /// // MIGRATIONS /// /// it('should add via a migration the `cacheInvalidatedAt` field to any doc and set it to equal the doc\'s `updatedAt` field', async function() { const objects = [ { slug: 'test-for-cacheInvalidatedAt-field-migration1', visibility: 'public', type: 'test-people', firstName: 'Kurt', lastName: 'Cobain', age: 27, alive: false, updatedAt: '2022-03-28T12:57:03.685Z' }, { slug: 'test-for-cacheInvalidatedAt-field-migration2', visibility: 'public', type: 'test-people', firstName: 'Jim', lastName: 'Morrison', age: 27, alive: false, updatedAt: '2020-08-29T12:57:03.685Z' } ]; await apos.doc.db.insertMany(objects); await apos.doc.setCacheField(); const docs = await apos.doc.db.find({ slug: /test-for-cacheInvalidatedAt-field-migration/ }).toArray(); docs.forEach((doc, index) => { const timestamps = { doc: new Date(doc.cacheInvalidatedAt).toString(), expected: new Date(objects[index].updatedAt).toString() }; assert(timestamps.doc === timestamps.expected); }); }); it('should not add via a migration the `cacheInvalidatedAt` field to docs that already have it', async function() { const object = { slug: 'test-for-cacheInvalidatedAt-field-migration3', visibility: 'public', type: 'test-people', firstName: 'Janis', lastName: 'Joplin', age: 27, alive: false, updatedAt: '2018-08-29T12:57:03.685Z', cacheInvalidatedAt: '2019-08-29T12:57:03.685Z' }; await apos.doc.db.insert(object); await apos.doc.setCacheField(); const doc = await apos.doc.db.findOne({ slug: 'test-for-cacheInvalidatedAt-field-migration3' }); const timestamps = { doc: new Date(doc.cacheInvalidatedAt).toString(), expected: new Date(object.cacheInvalidatedAt).toString() }; assert(timestamps.doc === timestamps.expected); }); /// /// // CACHING /// /// it('should add a `cacheInvalidatedAt` field and set it to equal `updatedAt` field when saving a doc', async function() { const object = { slug: 'test-for-cacheInvalidatedAt-field', visibility: 'public', type: 'test-people', firstName: 'Michael', lastName: 'Jackson', age: 64, alive: true }; const response = await apos.doc.insert(apos.task.getReq(), object); const draft = await apos.doc.db.findOne({ _id: `${response.aposDocId}:en:draft` }); assert(response.cacheInvalidatedAt.getTime() === response.updatedAt.getTime()); assert(draft.cacheInvalidatedAt.getTime() === draft.updatedAt.getTime()); }); }); <gh_stars>0 import React from "react" import Toolbar from "../components/toolbar" import FooterNav from "../components/footerNav" import Jumbotron from "../components/jumbotron" import EventPreview from "../components/events/event-preview" import EventNavigation from "../components/events/event-nav" import ReactHelmet from "../components/head"; export default ({location})=>( <div> <ReactHelmet tabTitle={"Upcoming | CBCOC"} /> <Toolbar isSolid={false} /> <Jumbotron desc="" image="upcoming.png" title="Upcoming Events" title2="" /> <EventPreview name="Cheesey Party" date="December 8-9, 2018" loc="CBCOC" img="bible" desc="Squirty cheese cheesy feet chalk and cheese. Macaroni cheese halloumi airedale cheddar boursin stinking bishop red leicester camembert de normandie. Croque monsieur who moved my cheese who moved my cheese airedale emmental cheese strings queso cheese on toast. Roquefort cow goat brie blue castello fromage frais brie brie. Dolcelatte." id="N/A" /> <EventPreview name="Event Name" date="December 8-9, 2018" loc="CBCOC" img="bible" desc="Squirty cheese cheesy feet chalk and cheese. Macaroni cheese halloumi airedale cheddar boursin stinking bishop red leicester camembert de normandie. Croque monsieur who moved my cheese who moved my cheese airedale emmental cheese strings queso cheese on toast. Roquefort cow goat brie blue castello fromage frais brie brie. Dolcelatte." id="N/A" /> <EventPreview name="Event Name" date="December 8-9, 2018" loc="CBCOC" img="bible" desc="Squirty cheese cheesy feet chalk and cheese. Macaroni cheese halloumi airedale cheddar boursin stinking bishop red leicester camembert de normandie. Croque monsieur who moved my cheese who moved my cheese airedale emmental cheese strings queso cheese on toast. Roquefort cow goat brie blue castello fromage frais brie brie. Dolcelatte." id="N/A" /> <EventNavigation/> <FooterNav/> </div> );const mongoose = require('mongoose'); let Store = mongoose.model('Store'); exports.list = function(req, res){ Store.find({}, function(stores, err){ if(err) return res.send(err); return res.json(stores); }); }; exports.detail = function(req, res){ Store.findById(req.params.id, function(store, err){ if(err) return res.send(err); else if(!store) return res.json({message: `Store ${req.params.id} not found!`}); return res.json(store); }); } exports.create = function(req, res){ Store.create(req.body, function(store, err){ if(err) return res.send(err); return res.json(store); }); } exports.update = function(req, res){ Store.findByIdAndUpdate({_id: req.params.id}, req.body, {new: true}, function(store, err){ if(err) return res.send(err); else if(!store) return res.json({message: `Store ${req.params.id} not found!`}); return res.json(store); }); } exports.delete = function(req, res){ Store.findByIdAndRemove(req.params.id, {}, function(store, err){ if(err) return res.send(err); else if(!store) return res.json({message: `Store ${req.params.id} not found!`}); return res.json({message: `Store ${req.params.id} is deleted successfully!`}); }); }import * as React from "react"; function SvgSushiOutlined(props) { return ( <svg width={24} height={24} fill="none" xmlns="http://www.w3.org/2000/svg" {...props} > <path fillRule="evenodd" clipRule="evenodd" d="M1 7.5C1 3.9 5.9 1 12 1s11 2.9 11 6.5v9c0 3.6-4.9 6.5-11 6.5S1 20.1 1 16.5v-9zm19 0C20 6 16.4 4 12 4 9 4 4 5.4 4 7.5 4 9 7.6 11 12 11c3 0 8-1.4 8-3.5zM12 20c2.4 0 4.7-.6 6.3-1.5 1-.6 1.7-1.4 1.7-2V12c-2 1.2-4.8 2-8 2s-6-.7-8-2v4.5c0 .6.6 1.4 1.7 2 1.6 1 3.9 1.5 6.3 1.5zm2.5-12.5c0 .828-1.12 1.5-2.5 1.5s-2.5-.672-2.5-1.5S10.62 6 12 6s2.5.672 2.5 1.5z" fill="currentColor" /> </svg> ); } export default SvgSushiOutlined; <reponame>suganth-cppl/react-base import React, { useState } from "react"; import { CopyToClipboard } from "react-copy-to-clipboard"; import { BiCopyAlt } from "react-icons/bi"; import { OverlayTrigger, Tooltip } from "react-bootstrap"; import { useTranslation } from "react-multi-lang"; const CopyToClipboardComponent = ({ copyText }) => { const t = useTranslation(); const [copyStatus, setCopyStatus] = useState(false); const renderTooltip = (props) => ( <Tooltip id="button-tooltip" {...props}> {copyStatus ? t("copied") : t("copytoclipboard")} </Tooltip> ); return ( <div className="d-flex justify-content-between align-items-center bg-light p-2"> <label className="text-secondary">{copyText}</label> <OverlayTrigger placement="left" overlay={renderTooltip}> <CopyToClipboard text={copyText} onCopy={() => { setCopyStatus(true); setTimeout(async () => { setCopyStatus(false); }, 5000); }} > <button className="btn btn-secondary"> <BiCopyAlt size={20} /> </button> </CopyToClipboard> </OverlayTrigger> </div> ); }; export default CopyToClipboardComponent; // using shadowRoot & template const template = document.createElement('template'); template.innerHTML = ` <style type="text/css"> .window { font-weight: bold; background: #434783; padding: 10px 30px 10px 10px; position: fixed; width: 200px; bottom: 0px; right: 0px; z-index: 2; color: red; word-break: break-all; transition: width 2s; } .button { border-radius: 5px; cursor: pointer; margin-right: 5px; margin-top: 5px; padding: 1px 5px; border: 1px solid white; color: white; position: absolute; top: 0px; right: 0px; } </style> <div class="window"> <div class="text"></div> <div class="button">X</div> </div> `; export default class ErrorWindow extends HTMLElement { constructor() { super(); this.attachShadow({mode: "open"}); } render(error, color) { const temp = template.content.cloneNode(true); temp.querySelector('.text').innerHTML = error; // для зеленой окраски if (color == 'lightgreen') temp.querySelector('.text').style.color = 'lightgreen'; temp.querySelector('.button').addEventListener('click', () => document.querySelector('error-window').remove()); this.shadowRoot.append(temp); setTimeout(() => document.querySelector('error-window').remove(), 3000); } }// Generated by CoffeeScript 2.6.1 var utils; utils = require('@nikitajs/core/lib/utils'); module.exports = function(err, stderr) { stderr = stderr.trim(); if (utils.string.lines(stderr).length === 1) { return err.message = stderr; } }; /* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */ /*global define, brackets, $, window */ define(function (require, exports, module) { 'use strict'; // Brackets modules var ExtensionLoader = brackets.getModule("utils/ExtensionLoader"); // Our modules var client = require("client"); // The extensions folder var extensionDir = ExtensionLoader.getUserExtensionPath() + "/"; var moduleName = "extension-manager"; // Monkey-patch the extension loader ExtensionLoader.unloadExtension = function (name, config, entryPoint) { console.log("[Extension] Unloading " + name + " (in " + config.baseUrl + ")"); var result = new $.Deferred(); // Hack: Get the loaded module var module = brackets.libRequire.s.contexts[name].defined.main; function moduleUnloaded(err) { // Hack: Make require.js forget it ever loaded this extension delete brackets.libRequire.s.contexts[name]; if (err) { console.log("[Extension] Error while unloading " + name + ": " + err.message); result.reject(err); } else { console.log("[Extension] Successfully unloaded " + name); result.resolve(); } } if (module && module.unload) { console.log("[Extension] Unloading " + name + " with its module's unload method"); try { if (module.unload.length > 0) { console.log("[Extension] Waiting for callback to be called"); module.unload(moduleUnloaded); } else { console.log("[Extension] Unloading sequentially"); module.unload(); moduleUnloaded(); } } catch (err) { moduleUnloaded(err); } } else { moduleUnloaded(new Error("Module did not provide an unload() method")); } return result.promise(); }; // load an extension function _load(name) { ExtensionLoader.loadExtension(name, { baseUrl: extensionDir + name }, "main"); } // unload an extension function _unload(name) { return ExtensionLoader.unloadExtension(name, { baseUrl: extensionDir + name }, "unload"); } // list extensions function list(callback) { client.send(moduleName, "list", callback); } // install an extension function install(name, callback) { client.send(moduleName, "install", name, function (res) { _load(name); if (callback) { callback(); } }); } // uninstall an extension function uninstall(name, callback) { client.send(moduleName, "uninstall", name, function (res) { if (callback) { callback(); } }); } // enable an extension function enable(name, callback) { client.send(moduleName, "enable", name, function (res) { _load(name); if (callback) { callback(); } }); } // disable an extension function disable(name, callback) { var fn = function () { client.send(moduleName, "disable", name, callback); }; // Wait for unload to complete or fail before disabling _unload(name).done(fn).fail(fn); } // update an extension function update(name, callback) { client.send(moduleName, "update", name, function (res) { if (callback) { callback(); } }); } // update all extensions function updateAll(callback) { client.send(moduleName, "updateAll", function (res) { if (callback) { callback(); } }); } // open a URL function openUrl(url) { client.send(moduleName, "openUrl", url); } // init the extension client function init(callback) { client.connect(callback); } exports.list = list; exports.install = install; exports.uninstall = uninstall; exports.enable = enable; exports.disable = disable; exports.update = update; exports.updateAll = updateAll; exports.openUrl = openUrl; exports.init = init; }); "use strict"; jQuery(document).ready(function($){ //your custom js code here });<gh_stars>10-100 // CodeInput // by WebCoder49 // Based on a CSS-Tricks Post var codeInput = { usedTemplates: { }, defaultTemplate: undefined, CodeInput: class extends HTMLElement { // Create code input element constructor() { super(); // Element } /* Syntax-highlighting functions */ update(text) { if(this.value != text) this.value = text; // Change value attribute if necessary. if(this.querySelector("textarea").value != text) this.querySelector("textarea").value = text; let result_element = this.querySelector("pre code"); // Handle final newlines (see article) if (text[text.length - 1] == "\n") { text += " "; } // Update code result_element.innerHTML = this.escape_html(text); // Syntax Highlight if(this.template.includeCodeInputInHighlightFunc) this.template.highlight(result_element, this); else this.template.highlight(result_element); } sync_scroll() { /* Scroll result to scroll coords of event - sync with textarea */ let input_element = this.querySelector("textarea"); let result_element = this.template.preElementStyled ? this.querySelector("pre") : this.querySelector("pre code"); // Get and set x and y result_element.scrollTop = input_element.scrollTop; result_element.scrollLeft = input_element.scrollLeft; } check_tab(event) { if(this.template.isCode) { let input_element = this.querySelector("textarea"); let code = input_element.value; if (event.key == "Tab") { /* Tab key pressed */ event.preventDefault(); // stop normal if(input_element.selectionStart == input_element.selectionEnd) { let before_selection = code.slice(0, input_element.selectionStart); // text before tab let after_selection = code.slice(input_element.selectionEnd, input_element.value.length); // text after tab let cursor_pos = input_element.selectionEnd + 1; // where cursor moves after tab - moving forward by 1 char to after tab input_element.value = before_selection + "\t" + after_selection; // add tab char // move cursor input_element.selectionStart = cursor_pos; input_element.selectionEnd = cursor_pos; } else { let lines = input_element.value.split("\n"); let letter_i = 0; let selection_start = input_element.selectionStart; // where cursor moves after tab - moving forward by 1 indent let selection_end = input_element.selectionEnd; // where cursor moves after tab - moving forward by 1 indent let number_indents = 0; let first_line_indents = 0; for (let i = 0; i < lines.length; i++) { letter_i += lines[i].length; if(input_element.selectionStart < letter_i && input_element.selectionEnd > letter_i - lines[i].length) { if(event.shiftKey) { if(lines[i][0] == "\t") { lines[i] = lines[i].slice(1); if(number_indents == 0) first_line_indents--; number_indents--; } } else { lines[i] = "\t" + lines[i]; if(number_indents == 0) first_line_indents++; number_indents++; } } } input_element.value = lines.join("\n"); // move cursor input_element.selectionStart = selection_start + first_line_indents; input_element.selectionEnd = selection_end + number_indents; } this.update(input_element.value); } } } escape_html(text) { return text.replace(new RegExp("&", "g"), "&").replace(new RegExp("<", "g"), "<"); /* Global RegExp */ } /* Callbacks */ connectedCallback() { // Added to document this.template = codeInput.usedTemplates[this.getAttribute("template") || codeInput.defaultTemplate]; if(this.template.preElementStyled) this.classList.add("code-input_pre-element-styled"); /* Defaults */ let lang = this.getAttribute("lang"); let placeholder = this.getAttribute("placeholder") || this.getAttribute("lang") || ""; let value = this.value || this.innerHTML || ""; this.innerHTML = ""; // Clear Content /* Create Textarea */ let textarea = document.createElement("textarea"); textarea.placeholder = placeholder; textarea.value = value; textarea.setAttribute("spellcheck", "false"); if (this.getAttribute("name")) { textarea.setAttribute("name", this.getAttribute("name")); // for use in forms this.removeAttribute("name"); } textarea.setAttribute("oninput", "this.parentElement.update(this.value); this.parentElement.sync_scroll();"); textarea.setAttribute("onscroll", "this.parentElement.sync_scroll();"); textarea.setAttribute("onkeydown", "this.parentElement.check_tab(event);"); this.append(textarea); /* Create pre code */ let code = document.createElement("code"); if(this.template.isCode && lang != null) code.classList.add("language-" + lang); code.innerText = value; let pre = document.createElement("pre"); pre.setAttribute("aria-hidden", "true"); // Hide for screen readers pre.append(code); this.append(pre); /* Add code from value attribute - useful for loading from backend */ this.update(value, this); } static get observedAttributes() { return ["value", "placeholder", "lang", "template"]; // Attributes to monitor } attributeChangedCallback(name, oldValue, newValue) { if(this.isConnected) { // This will sometimes be called before the element has been created, so trying to update an attribute causes an error. // Thanks to <NAME> for pointing this out. switch (name) { case "value": // Update code this.update(newValue); break; case "placeholder": this.querySelector("textarea").placeholder = newValue; break; case "template": this.template = codeInput.usedTemplates[newValue || codeInput.defaultTemplate]; if(this.template.preElementStyled) this.classList.add("code-input_pre-element-styled"); else this.classList.remove("code-input_pre-element-styled"); // Syntax Highlight this.update(this.value); case "lang": let code = this.querySelector("pre code"); let textarea = this.querySelector("textarea"); if(newValue != null) code.className = ("language-" + newValue); else code.className = ""; if(textarea.placeholder == oldValue) textarea.placeholder = newValue this.update(this.value); } } } /* Value attribute */ get value() { return this.getAttribute("value"); } set value(val) { return this.setAttribute("value", val); } /* Placeholder attribute */ get placeholder() { return this.getAttribute("placeholder"); } set placeholder(val) { return this.setAttribute("placeholder", val); } }, registerTemplate: function(template_name, template) { // Set default class codeInput.usedTemplates[template_name] = template; codeInput.defaultTemplate = template_name; }, templates: { custom(highlight=function() {}, preElementStyled=true, isCode=true, includeCodeInputInHighlightFunc=false) { return { highlight: highlight, includeCodeInputInHighlightFunc: includeCodeInputInHighlightFunc, preElementStyled: preElementStyled, isCode: isCode, }; }, prism(prism) { // Dependency: Prism.js (https://prismjs.com/) return { includeCodeInputInHighlightFunc: false, highlight: prism.highlightElement, preElementStyled: true, isCode: true }; }, hljs(hljs) { // Dependency: Highlight.js (https://highlightjs.org/) return { includeCodeInputInHighlightFunc: false, highlight: hljs.highlightElement, preElementStyled: false, isCode: true }; }, characterLimit() { return { highlight: function(result_element, code_input) { let character_limit = Number(code_input.getAttribute("data-character-limit")); let normal_characters = code_input.escape_html(code_input.value.slice(0, character_limit)); let overflow_characters = code_input.escape_html(code_input.value.slice(character_limit)); result_element.innerHTML = `${normal_characters}<mark class="overflow">${overflow_characters}</mark>`; if(overflow_characters.length > 0) { result_element.innerHTML += ` <mark class="overflow-msg">${code_input.getAttribute("data-overflow-msg") || "(Character limit reached)"}</mark>`; } }, includeCodeInputInHighlightFunc: true, preElementStyled: true, isCode: false } }, rainbowText(rainbow_colors=["red", "orangered", "orange", "goldenrod", "gold", "green", "darkgreen", "navy", "blue", "magenta"], delimiter="") { return { highlight: function(result_element, code_input) { let html_result = []; let sections = code_input.value.split(code_input.template.delimiter); for (let i = 0; i < sections.length; i++) { html_result.push(`<span style="color: ${code_input.template.rainbow_colors[i % code_input.template.rainbow_colors.length]}">${code_input.escape_html(sections[i])}</span>`); } result_element.innerHTML = html_result.join(code_input.template.delimiter); }, includeCodeInputInHighlightFunc: true, preElementStyled: true, isCode: false, rainbow_colors: rainbow_colors, delimiter: delimiter } } } } customElements.define("code-input", codeInput.CodeInput); // Set tagjQuery(document).ready(function($){ // $('.nav__item--dropdown .nav__link').click(function(e) { // e.preventDefault(); // $(this).closest('.header').find('.menu-services').show(); // }); $('.main-gallery__slider').slick({ dots: false, arrows: true, infinite: true, slidesToShow: 1, slidesToScroll: 1, centerMode: true, centerPadding: '0', appendArrows: $('.main-gallery__controls') }); $('.up').click(function () { $('html, body').animate({ scrollTop: 0 }, 600); return false; }); $('.hamburger').click(function(e) { e.preventDefault(); $('.nav__list').slideToggle(); }); $(window).scroll(function () { // if ($(window).width() >= 768) { if ($(this).scrollTop() > 0 ) { $('.header').addClass('header--sticky'); } else { $('.header').removeClass('header--sticky'); } // } }); }); const http = require('http'); const httpProxy = require('http-proxy'); const initRequestLog = require('./utils/requestLog'); const initResponseLog = require('./utils/responseLog'); module.exports = ({ config, app, logger, sdc }) => { // Proxy to API server const proxyLog = logger.child({ subsystem: 'app:proxy' }); const server = new http.Server(app); const targetUrl = `http://${config.api.host}:${config.api.port}`; const proxy = httpProxy.createProxyServer({ target: targetUrl, ws: false }); app.use('/api', (req, res) => { proxy.web(req, res, { target: targetUrl }); }); app.use('/ws', (req, res) => { proxy.web(req, res, { target: `${targetUrl}/ws` }); }); server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head); }); proxy.on('proxyReq', (proxyReq, req, res, options) => { const requestLog = initRequestLog(sdc, proxyLog); proxyReq.setHeader('Content-Type', 'application/json'); proxyReq.setHeader('Access-Control-Allow-Origin', targetUrl); req._isProxy = true; return requestLog(req, res); }); proxy.on('proxyRes', (proxyRes, req, res, options) => { const responseLog = initResponseLog(); // forward cookie set from proxy if (proxyRes.headers['set-cookie']) { res.header['Set-Cookie'] = proxyRes.headers['set-cookie']; } const responseTime = proxyRes.headers['x-response-time']; return responseLog(req, res, responseTime); }); proxy.on('error', (err, req, res) => { const json = { title: 'API Proxy Error', name: 'proxy_error', message: err.message }; proxyLog.error({ err }, `${err.code}: ${err.message} trying to process: ${req.method} ${req.url}`); if (!res.headersSent) { res.writeHead(500, { 'content-type': 'application/json' }); } res.end(JSON.stringify(json)); }); }; // this validates if the number passed in is a US telephone number function telephoneCheck(str) { // Good luck! var regex = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$/; return regex.test(str); } telephoneCheck("555-555-5555");import React from 'react'; import '../App.css'; import $ from "jquery" function Header() { $(document).ready(function(){ $(window).scroll(function(){ $('.Intro').css("opacity", 1 - $(window).scrollTop() / 800) }) }) return ( <header> <div className= "Intro-Body"> <div className="Intro"> <div id="Intro"></div> <div className="Header-Text"> <h1><NAME></h1> <h2>Game & Web designer and/or programmer</h2> </div> <div className="Intro-Text"> <h4>I learned how to use and/or made projects with the following subjects:</h4><br/> <div className="Intro-Text-TAB"> <h5>♦. Web development</h5><p>(♦ React and PHP ♦)</p><br/> <h5>♦ ♦ . Game development</h5><p>(♦ Godot ♦)</p><br/> <h5>♦ ♦ ♦ . Database Design</h5><p>(♦ MySQL ♦)</p><br/> <div id="About"></div> </div> </div> </div> </div> </header> ); } export default Header;<filename>examples/example_3.js var example_3 = switcher.items({backClickTurnOff: true}); example_3.addTabs('#tab_2 span', function () { this.classList.add('tab_active'); this.style.color = "black"; }, function () { this.classList.remove('tab_active'); this.style.color = "white"; }); example_3.addBlocks('#block_2 span'); example_3.turnOn(0); <filename>website/sidebars.js module.exports = { mainSidebar: [ { collapsed: false, type: 'category', label: 'Getting Started', items: [ 'Home', 'What-Is-Premake', 'Building-Premake', 'Getting-Premake', 'Using-Premake', 'Getting-Help', 'Who-Uses-Premake' ] }, { collapsed: true, type: 'category', label: 'Guides', items: [ 'Sharing-Configuration-Settings' ] }, { collapsed: true, type: 'category', label: 'Reference', items: [ 'basedir', { collapsed: false, type: 'category', label: 'os', items: [ 'os.chdir', 'os.mkdir', 'os.rmdir' ] }, { collapsed: false, type: 'category', label: 'path', items: [ 'path.getabsolute', 'path.getbasename', 'path.getdirectory', 'path.getdrive', 'path.getextension', 'path.getname' ] } ], } ], }; require('./bootstrap'); require('cleave.js'); require('cleave.js/dist/addons/cleave-phone.cm'); import Alpine from 'alpinejs'; window.Alpine = Alpine; Alpine.start(); <filename>Final Project/CS6314_Web_FinalProject/test/test_hash.js var express = require('express'); var router = express.Router(); let db = require('../modules/database'); var h = require('../modules/hash'); const unhashedPwds = [ "test", "Test1234", "Ad123450", "Wid678934", "Uyh123456", "Pjg341152" ] const lastResult = { "test":"$2b$10$OevNVIaABJZn/n9FNolEiu681PDnwfsGsCGXzhlwHU91Ma4N7FkR.", "Test1234":"$2b$10$Ruzvn/MRrVPKLcLb5zBgT.g6d5d9x3Vyt4jyzE2JBxrQHQReN5l7e", "Ad123450":"$2b$10$OevNVIaABJZn/n9FNolEiurdtfyHnti/KKmuV6X488uXiIsBrDGgu", "Wid678934":"$2b$10$OevNVIaABJZn/n9FNolEiu.Urct5C5OsuBjai1sx4GMHVnUnQ1IZC", "Uyh123456":"$2b$10$OevNVIaABJZn/n9FNolEiufPFRtMIMll4ntHan9H9C2XbhkbSn/Yu", "Pjg341152":"$2b$10$OevNVIaABJZn/n9FNolEiue80xxPcdZtpN2zv7QwUTjZA3apuXy.K" } var getHashed = function() { return new Promise((resolve, reject) => { let results = {}; for (let pwd of unhashedPwds) { h.hash(pwd, (hashed) => { results[pwd] = hashed; }) } resolve(results); }); }; // sign in router.get('/', function(req, res) { getHashed().then((results) => { res.send(results); }) }); module.exports = router;<gh_stars>0 var app = angular.module('ngApp', []); app.controller('ctrlNgApp', ['$scope', '$http', '$location', function($scope, $http, $location){ var matterId = location.search.match(/matterId=([^&]*)/)[1], matterType = location.search.match(/matterType=([^&]*)/)[1], siteId = location.search.match(/site=([^&]*)/)[1], uid = location.search.match(/uid=([^&]*)/)[1]; function findnum(num) { if(num >= 10000) { return Math.round(num / 10000 * 100) / 100 + 'w'; }else if(num >= 1000) { return Math.round(num / 1000 * 100 ) / 100+ 'k'; }else { return num; } }; $scope.page = { at: 1, size: 10, j: function() { return '&page=' + this.at + '&size=' + this.size; } }; $scope.order = function(item, append, at) { $scope.filter = item; if(!at) { at = 1; } $scope.page.at = at; var url = '/rest/site/fe/user/share/getMyShareLog'; url += '?userid=' + uid + '&matterType=' + matterType + '&matterId=' + matterId; url += '&orderBy=' + item + $scope.page.j(); $http.get(url).success(function(rsp) { if(rsp.data.users.length > 0) { angular.element('.note').css('display','none'); rsp.data.users.forEach(function(user) { user.num = findnum(user.num); }); if(append) { $scope.users = $scope.users.concat(rsp.data.users); }else{ $scope.users = rsp.data.users; } $scope.page.total = rsp.data.total; }else { $scope.users = []; $scope.page.total = rsp.data.total; angular.element('.note').css('display','block'); } }); }; $scope.more = function() { $scope.page.at++; $scope.order($scope.filter, true, $scope.page.at); }; $http.get('/rest/site/fe/get?site=' + siteId).success(function(rsp) { $scope.site = rsp.data; $scope.order('read'); }); }]); const teacher6 = new MapObject(52), desk601 = new MapObject(2), desk602 = new MapObject(2), desk603 = new MapObject(2), desk604 = new MapObject(2), desk606 = new MapObject(2), desk607 = new MapObject(2), desk608 = new MapObject(2), desk609 = new MapObject(2), desk611 = new MapObject(2), desk612 = new MapObject(2), desk613 = new MapObject(2), desk614 = new MapObject(2), desk616 = new MapObject(2), desk617 = new MapObject(2), desk618 = new MapObject(2), desk619 = new MapObject(2), stud6_1 = new MapObject(24), stud6_2 = new MapObject(27), stud6_3 = new MapObject(31), stud6_4 = new MapObject(43), stud6_5 = new MapObject(42), stud6_6 = new MapObject(40), stud6_7 = new MapObject(38); function objectsMap6() { teacher6.placeAt(2, 12, 6); desk601.placeAt(1, 4, 6); desk602.placeAt(1, 6, 6); desk603.placeAt(1, 8, 6); desk604.placeAt(1, 10, 6); desk606.placeAt(4, 4, 6); desk607.placeAt(4, 6, 6); desk608.placeAt(4, 8, 6); desk609.placeAt(4, 10, 6); desk611.placeAt(6, 4, 6); desk612.placeAt(6, 6, 6); desk613.placeAt(6, 8, 6); desk614.placeAt(6, 10, 6); desk616.placeAt(9, 4, 6); desk617.placeAt(9, 6, 6); desk618.placeAt(9, 8, 6); desk619.placeAt(9, 10, 6); } function npcsMap6() { stud6_1.placeAt(5, 5, 6); stud6_2.placeAt(6, 5, 6); stud6_3.placeAt(9, 7, 6); stud6_4.placeAt(7, 9, 6); stud6_5.placeAt(2, 7, 6); stud6_6.placeAt(2, 5, 6); stud6_7.placeAt(4, 7, 6); } import styled from 'styled-components'; import { themeGet } from '@styled-system/theme-get'; export const PortfolioButton = styled.span` display: block; background: ${themeGet('color.yellow', '#FF4C60')}; border-radius: 100%; height: 40px; line-height: 36px; text-align: center; position: absolute; bottom: 20px; left: 20px; width: 40px; opacity: 0; @include transition(0.3s); `; export const PortfolioDetails = styled.div` color: ${themeGet('color.white', '#fff')}; position: absolute; height: 100%; width: 100%; z-index: 1; `; export const PortfolioMask = styled.div` background: ${themeGet('color.blue', '#FF4C60')}; position: absolute; left: 0; top: 0; opacity: 0; height: 100%; width: 100%; @include transition(0.3s); `; const PortfolioItemWrapper = styled.div` position: relative; overflow: hidden; border-radius: 20px; &:hover { ${PortfolioMask} { opacity: 0.9; } ${PortfolioDetails} { h4, span { opacity: 1; transform: translateY(0); } ${PortfolioButton} { opacity: 1; } } } `; export const PortfolioThumb = styled.div` img { width: 330px; height: 260px; margin-bottom: 0px; } `; export const PortfolioCategory = styled.span` color: ${themeGet('color.white', '#fff')}; background: ${themeGet('color.pink', '#FF4C60')}; text-transform: capitalize; border-bottom-left-radius: 15px; border-bottom-right-radius: 15px; font-size: 15px; opacity: 0; display: inline-block; padding: 3px 10px; position: absolute; top: 0; left: 20px; transform: translateY(-40px); transition: all cubic-bezier(0.075, 0.82, 0.165, 1) 1s; `; export const PortfolioTitle = styled.h4` color: ${themeGet('color.white', '#fff')}; text-transform: capitalize; font-size: 20px; margin: 0 0 10px; padding: 0 20px; opacity: 0; transform: translateY(30px); transition: all cubic-bezier(0.075, 0.82, 0.165, 1) 1s; position: absolute; top: 60px; `; export default PortfolioItemWrapper; <reponame>mopanc/ws //para criar o package.json no terminal "npm init -v" //usei o express pra criar e configurar meu servidor const express = require("express") const server = express() const db = require("./db") /*const ideas = [ { img: "https://image.flaticon.com/icons/svg/2729/2729007.svg", title: "Cursos de Programação", category: "Estudo", description: "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquid ad porro distinctio pariatur repellendus ratione, at sequi, veritatis corrupti, voluptatem iure perferendis blanditiis officiis vitae itaque necessitatibus molestias eum nesciunt!", url: "https://rocketseat.com.br" }, { img: "https://image.flaticon.com/icons/svg/2729/2729005.svg", title: "Exercícios", category: "saúde", description: "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquid ad porro distinctio pariatur repellendus ratione, at sequi, veritatis corrupti, voluptatem iure perferendis blanditiis officiis vitae itaque necessitatibus molestias eum nesciunt!", url: "https://rocketseat.com.br" }, { img: "https://image.flaticon.com/icons/svg/2729/2729027.svg", title: "Meditação", category: "Mentalidade", description: "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquid ad porro distinctio pariatur repellendus ratione, at sequi, veritatis corrupti, voluptatem iure perferendis blanditiis officiis vitae itaque necessitatibus molestias eum nesciunt!", url: "https://rocketseat.com.br" }, { img: "https://image.flaticon.com/icons/svg/2729/2729032.svg", title: "Karaoke", category: "Diversão em Família", description: "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquid ad porro distinctio pariatur repellendus ratione, at sequi, veritatis corrupti, voluptatem iure perferendis blanditiis officiis vitae itaque necessitatibus molestias eum nesciunt!", url: "https://rocketseat.com.br" }, { img: "https://image.flaticon.com/icons/svg/2729/2729038.svg", title: "Pintura", category: "Criatividade", description: "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquid ad porro distinctio pariatur repellendus ratione, at sequi, veritatis corrupti, voluptatem iure perferendis blanditiis officiis vitae itaque necessitatibus molestias eum nesciunt!", url: "https://rocketseat.com.br" }, { img: "https://image.flaticon.com/icons/svg/2729/2729048.svg", title: "Recortes", category: "Criatividade", description: "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquid ad porro distinctio pariatur repellendus ratione, at sequi, veritatis corrupti, voluptatem iure perferendis blanditiis officiis vitae itaque necessitatibus molestias eum nesciunt!", url: "https://rocketseat.com.br" }, ]*/ //consigurar arquivos estáticos(css, scripts, imagens) server.use(express.static("public")) //Habilitar uso do req.body server.use(express.urlencoded({ extended: true })) //configuração do nunjucks const nunjucks = require("nunjucks") nunjucks.configure("views", { express: server, noCache: true, //boolean noCache serve para não guardar algumas coisas em cahce no desenvolvimento nãl é bom }) //criei uma rota / //e capturo o pedido do cliente para responder server.get("/", function(req, res) { db.all(`SELECT * FROM ideas`, function(err, rows) { if (err) { console.log(err) return res.send("Erro no banco de dados!") } const reversedIdeas = [...rows].reverse() let lastIdeas = [] for(let idea of reversedIdeas) { if(lastIdeas.length < 2) { lastIdeas.push(idea) } } return res.render("index.html", { ideas: lastIdeas }) }) }) server.get("/ideias", function(req, res) { db.all(`SELECT * FROM ideas`, function(err, rows) { if (err) { console.log(err) return res.send("Erro no banco de dados!") } const reversedIdeas = [...rows].reverse() return res.render("ideias.html", {ideas: reversedIdeas}) }) }) server.post("/", function(req, res) { //inserir os dados na tabela const query = ` INSERT INTO ideas( image, title, category, description, link ) VALUES (?,?,?,?,?); ` const values = [ req.body.image, req.body.title, req.body.category, req.body.description, req.body.link ] db.run(query, values, function(err) { if (err) { console.log(err) return res.send("Erro no banco de dados!") } return res.redirect("/ideias") }) }) //liguei meu servidor na porta 3000 server.listen(3000) import React from 'react' import Form from './Form' import List from './List' const Contact = () => { return ( <div className="contact"> <h1 className="head">Contacts</h1> <List/> <Form /> </div> ) } export default Contact <filename>templates/react-common/actions/foo/list.js<gh_stars>1-10 import {{{ lc }}}Fetch from '../../api/{{{ lc }}}Fetch'; export function error(error) { return {type: '{{{ uc }}}_LIST_ERROR', error}; } export function loading(loading) { return {type: '{{{ uc }}}_LIST_LOADING', loading}; } export function success(items) { return {type: '{{{ uc }}}_LIST_SUCCESS', items}; } export function view(items) { return { type: '{{{ uc }}}_LIST_VIEW', items}; } export function page(page) { return (dispatch) => { dispatch(loading(true)); dispatch(error('')); {{{ lc }}}Fetch(page) .then(response => response.json()) .then(data => { dispatch(loading(false)); dispatch(success(data['{{{ hydraPrefix }}}member'])); dispatch(view(data['{{{ hydraPrefix }}}view'])); }) .catch(e => { dispatch(loading(false)); dispatch(error(e.message)) }); }; } export function list() { return page('/{{{ name }}}'); } export function reset() { return {type: '{{{ uc }}}_LIST_RESET'}; } import mongoose from 'mongoose' const commentSchema = mongoose.Schema({ article:{ type: mongoose.Schema.Types.ObjectId, ref: 'Article' }, sender: { type: String, required: true }, comment: { type: String, required: true } }) const Comment = mongoose.model('Comment', commentSchema) export default Comment<reponame>Robot-Scholar/4mans require('dotenv').config(); const Discord = require('discord.js'); const logger = require('winston'); const client = new Discord.Client(); logger.remove(logger.transports.Console); logger.add( new logger.transports.Console, { colorize: true }); logger.level = 'debug'; client.once('ready', () => { logger.info('Ready'); }); client.login(process.env.BOT_TOKEN); const prefix = process.env.PREFIX; let Queues = {}; client.on('message', message => { if ( ! message.content.startsWith(prefix) || message.author.bot ) { return; } const args = message.content.slice(prefix.length).split(/ +/); const cmd = args.shift().toLowerCase(); switch(cmd) { // !ping case 'ping': message.channel.send('pong...'); break; case 'debug': message.channel.send(`Server name: ${message.guild.name}\nMembers: ${message.guild.memberCount}`); break; case 'args-info': if ( ! args.length ) { return message.reply(` you didn't provide any arguments.`); } message.channel.send(`Command name: ${cmd}\nArguments: ${args}`); break; case 'avatar': if ( ! message.mentions.users.size ) { return message.reply(` your avatar is <${message.author.displayAvatarURL}>`); } const avatars = message.mentions.users.map(user => { return `${user.username}'s avatar: <${user.displayAvatarURL}>`; }); break; case 'user-info': message.reply(` Your username: <@${message.author.id}>\nYour ID: ${message.author.id}`); break; case 'test': message.channel.send(message); break; case 'activity': client.user.setActivity(args.join(' ')); break; case 'createqueue': if ( args.length ) { let guild = message.guild; if ( args[0] in Queues ) { message.reply(' ${args[0]} already exists.'); } else { Queues[ args[0] ] = {}; } guild.createChannel(args[0], {type: 'text'}) .then(logger.info) .then(function(something) { logger.info('Storing the queue?'); logger.info('Args:'); logger.info(arguments); }) .catch(logger.error); } break; case 'q': if ( message.channel.name in Queues ) { Queues[ message.channel.name ][ message.author.id ] = message.author; } //logger.info(Queues); let q_users = Queues[ message.channel.name ]; let counts = q_users.keys(); message.channel.send(`Users in #${message.channel.name} queue: ${counts}\n`); //message.channel.send(`<@${Queues.keys()}`); break; } }); /* var Discord = require('discord.io'); var logger = require('winston'); // Configure logger settings logger.remove(logger.transports.Console); logger.add(new logger.transports.Console, { colorize: true }); logger.level = 'debug'; var Queues = {}; // Initialize Discord Bot var bot = new Discord.Client({ token: process.env.BOT_TOKEN, autorun: true }); bot.on('ready', function (evt) { logger.info('Connected'); logger.info('Logged in as: '); logger.info(bot.username + ' - (' + bot.id + ')'); }); bot.on('message', function (user, userID, channelID, message, evt) { // Our bot needs to know if it will execute a command // It will listen for messages that will start with `!` if (message.substring(0, 1) == '!') { var args = message.substring(1).split(' '); var cmd = args[0]; logger.info('user sending message: ' + userID + ', channel: ' + channelID); logger.info(user); args = args.splice(1); switch(cmd) { // !ping case 'ping': bot.sendMessage({ to: channelID, message: 'Pong!' }); break; case 'createqueue': break; case 'q': break; } } }); *//* * Create a list that holds all of your cards */ let cards = ["fa fa-diamond", "fa fa-diamond", "fa fa-paper-plane-o", "fa fa-paper-plane-o", "fa fa-anchor", "fa fa-anchor", "fa fa-bolt", "fa fa-bolt", "fa fa-cube", "fa fa-cube", "fa fa-bicycle", "fa fa-bicycle", "fa fa-bomb", "fa fa-bomb", "fa fa-leaf", "fa fa-leaf"]; //shortened variables and selectors $container = $('.container'), $scorePanel = $('.score-panel'), $rating = $('.fa-star'), $moves = $('.moves'), $timer = $('.timer'), $restart = $('.restart'), $deck = $('.deck'), allOpen = [], match = 0, second = 0, moves = 0, totalCard = cards.length / 2, stars3 = 14, stars2 = 16, star1 = 20; // Shuffle function from http://stackoverflow.com/a/2450976 function shuffle(array) { let currentIndex = array.length, temporaryValue, randomIndex; while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function newGame() { let allCards = shuffle(cards); $deck.empty(); match = 0; moves = 0; $moves.text('0'); for (let i = 0; i < allCards.length; i++) { $deck.append($('<li class="card"><i class="fa fa-' + allCards[i] + '"></i></li>')) } addCardListener(); // Resets time to 0 resetTimer(); second = 0; $timer.text(`${second}`) initTime(); } //starts rating function rating(moves) { let rating = 3; if (moves > stars3 && moves < stars2) { $rating.eq(3).removeClass('fa-star').addClass('fa-star-o'); } else if (moves > stars2 && moves < star1) { $rating.eq(2).removeClass('fa-star').addClass('fa-star-o'); } else if (moves > star1) { $rating.eq(1).removeClass('fa-star').addClass('fa-star-o'); rating = 1; } return {score: rating}; } // Boostrap modal alert window function gameOver(moves, score) { $('#winnerText').text(`You've completed the game in ${second} seconds with a total of ${moves} moves and a score of ${score}.`); $('#winnerModal').modal('toggle'); } // Restarts the game $restart.bind('click', function (confirmed) { if (confirmed) { $rating.removeClass('fa-star-o').addClass('fa-star'); newGame(); } }); //Matching the cards let addCardListener = function () { $deck.find('.card').bind('click', function () { let $this = $(this); if ($this.hasClass('show') || $this.hasClass('match')) { return true; } let card = $this.context.innerHTML; $this.addClass('open show'); allOpen.push(card); if (allOpen.length > 1) { if (card === allOpen[0]) { $deck.find('.open').addClass('match'); setTimeout(function () { $deck.find('open').removeClass('open show'); }); match++; } else { $deck.find('.open').addClass('notmatch'); setTimeout(function () { $deck.find('.open').removeClass('open show'); }, 700); } allOpen = []; moves++; rating(moves); $moves.html(moves); } // if (totalCard === match) { rating(moves); let score = rating(moves).score; setTimeout(function () { gameOver(moves, score); }); } }); } // Timer const timerContainer = document.querySelector(".timer"); let liveTimer, totalSeconds = 0; function initTime() { liveTimer = setInterval(function () { $timer.text(`${second}`) second++; }, 1000); } // Resets the timer when the game ends or is restarted function resetTimer() { clearInterval(liveTimer); } newGame(); /*! ======================================================================== * FilterList: filterlist.js v2.0.0 * ======================================================================== * Copyright 2015, <NAME> (disalvo-infographiste[dot]be) * ======================================================================== */ (function ($) { 'use strict'; // SELECT FILTER PUBLIC CLASS DEFINITION // ==================================== var FilterSelect = function (element, options) { this.$element = $(element) this.options = $.extend({}, this.defaults(), options) this.structure = $.extend({}, this.parts()) } FilterSelect.VERSION = '1.0.0' FilterSelect.DEFAULTS = { method : 'recursive', items : '.items' } FilterSelect.prototype.defaults = function() { return { select : FilterSelect.DEFAULTS.select, method : this.$element.attr('data-method') || FilterSelect.DEFAULTS.method, items : this.$element.attr('data-items') || FilterSelect.DEFAULTS.items } } FilterSelect.prototype.parts = function() { return { $items : $(this.options.items, this.$element) } } FilterSelect.prototype.filter = function( section, select, val ) { alert(section+' - '+select+' - '+val); var $select = this.$element; if ( val && $select.data('bs.dropdownselect') ) { var $selected = $('.items.selected', $select); if($selected.length) { $selected.each(function(){ if( $(this).data(section) != val ) { $select.bootstrapSelect('clear'); } }); } } this.filterItem( section, select, val, this.options.method ); if ( $('.live-filtering', $select).data('liveFilter') ) $('.live-filtering', $select).liveFilter('initAC'); } FilterSelect.prototype.filterItem = function( section, select, val, method ) { this.structure.$items.each(function(){ var ref = $(this).data('ref'), valid = $(this).data('valid'); if( ref != undefined && valid != undefined ) { ref = ref.split(','); valid = valid.split(','); if ( ref.length == valid.length ) { if (val != null) { if (ref.indexOf(section) > -1) { valid[ref.indexOf(section)] = val; }else { ref = ref.concat([section]); valid = valid.concat([val]); } } else { ref.splice(ref.indexOf(section),1); valid.splice(ref.indexOf(section),1); } } } else if (val != null) { ref = [section]; valid = [val]; } if( method == 'recursive' ) { var skip = true; for( var c = 0; c < ref.length; c++ ) { if ( valid[c] != $(this).data(ref[c])) { skip = false; } } } else if ( method == 'additionnal' ) { var skip = false; for( var c = 0; c < ref.length; c++ ) { if ( valid[c] == $(this).data(ref[c])) { skip = true; } } } $(this).data('ref',ref.toString()).data('valid',valid.toString()); if ( !skip ) { $(this).addClass('disabled').hide(); } else { $(this).removeClass('disabled').show(); } }); } // SELECT FILTER PLUGIN DEFINITION // ============================== function Plugin() { var option = arguments; return this.each(function () { var $this = $(this); var data = $this.data('filterSelect'); var method = option[0]; if( (typeof(method) == 'object' || !method) && !data ) { $this.data('filterSelect', (data = new FilterSelect(this, method))); method = data; } else if(data[method]) { method = data[method]; // Our method was sent as an argument, remove it using slice because it's not an argument for our method option = Array.prototype.slice.call(option, 1); method(option) } else { $.error( 'Method ' + method + ' does not exist on jQuery.pluginName' ); return this; } // Use apply to sent arguments when calling our selected method return method.call(this, option); }) } var old = $.fn.selectFilter $.fn.selectFilter = Plugin $.fn.selectFilter.Constructor = FilterSelect // SELECT FILTER NO CONFLICT // ======================== $.fn.toggle.noConflict = function () { $.fn.selectFilter = old return this } // SELECT FILTER DATA-API // ===================== $(function() { $('[data-filter]').selectFilter(); }); }(jQuery));<reponame>Coolguy3289/lbry-wunderbot<filename>bot/modules/example.js /* // Example #1 Command(use this to make your Commands with triggers like !demo) exports.commands = [ "demo" // command name that will be used for next lines of code below ] exports.demo = { usage: "<subcommand>", //command usage like !demo <@username>, exclude !demo description: 'description of command', //the description of command for !help command process: function(bot,msg,suffix){ // Here the bot,msg and suffix is available, this function can be async if needed. } } // Example #2 Function(use this to make your Functions that dont need trigger words unlike !demo) exports.custom = [ "myFunction" //change this to your function name ] exports.myFunction = function(bot) { // Other functions that need to be ran once on bootup! // For example a timed function and or some init stuff.. } */ <gh_stars>0 // @flow import { type Context } from "koa"; import { Document, Collection, Event } from "../models"; import { sequelize } from "../sequelize"; export default async function documentMover({ user, document, collectionId, parentDocumentId, index, ip, }: { user: Context, document: Document, collectionId: string, parentDocumentId: string, index?: number, ip: string, }) { let transaction; const result = { collections: [], documents: [] }; const collectionChanged = collectionId !== document.collectionId; try { transaction = await sequelize.transaction(); // remove from original collection const collection = await document.getCollection({ transaction }); const documentJson = await collection.removeDocumentInStructure(document, { save: false, }); // if the collection is the same then it will get saved below, this // line prevents a pointless intermediate save from occurring. if (collectionChanged) await collection.save({ transaction }); // add to new collection (may be the same) document.collectionId = collectionId; document.parentDocumentId = parentDocumentId; const newCollection: Collection = collectionChanged ? await Collection.findByPk(collectionId, { transaction }) : collection; await newCollection.addDocumentToStructure(document, index, { documentJson, }); result.collections.push(collection); // if collection does not remain the same loop through children and change their // collectionId too. This includes archived children, otherwise their collection // would be wrong once restored. if (collectionChanged) { result.collections.push(newCollection); const loopChildren = async (documentId) => { const childDocuments = await Document.findAll({ where: { parentDocumentId: documentId }, }); await Promise.all( childDocuments.map(async (child) => { await loopChildren(child.id); await child.update({ collectionId }, { transaction }); child.collection = newCollection; result.documents.push(child); }) ); }; await loopChildren(document.id); } await document.save({ transaction }); result.documents.push(document); await transaction.commit(); await Event.create({ name: "documents.move", actorId: user.id, documentId: document.id, collectionId, teamId: document.teamId, data: { title: document.title, collectionIds: result.collections.map((c) => c.id), documentIds: result.documents.map((d) => d.id), }, ip, }); } catch (err) { if (transaction) { await transaction.rollback(); } throw err; } // we need to send all updated models back to the client return result; } "use strict"; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert("sites", [ { site_name: "Empire Building", address1: "101 Collins Street", address2: "Level 40", suburb: "Melbourne", postcode: 3000, country: "Australia", user_id: 1, createdAt: "2019-11-07 00:00:00", updatedAt: "2019-11-07 00:00:00" }, { site_name: "Pylon Observatory", address1: "Bridge Road", address2: "Level 24", suburb: "Richmond", postcode: 3121, country: "Australia", user_id: 1, createdAt: "2019-11-07 00:00:00", updatedAt: "2019-11-07 00:00:00" }, { site_name: "GGR Republic", address1: "120 Sepulveda Blvd", address2: "Building", suburb: "Los Angeles", postcode: 90024, user_id: 1, country: "United States of America", createdAt: "2019-11-07 00:00:00", updatedAt: "2019-11-07 00:00:00" } ]); /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkInsert('People', [{ name: '<NAME>', isBetaMember: false }], {}); */ }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ } }; <filename>lib/jonny.js 'use strict'; const tryCatch = require('try-catch'); const { parse, stringify, } = JSON; module.exports.parse = (...args) => { const [, data] = tryCatch(parse, ...args); return data; }; module.exports.stringify = (...args) => { const [, data] = tryCatch(stringify, ...args); return data; }; import isPlainObject from "is-plain-object"; var has = (o, p) => Object.prototype.hasOwnProperty.call(o, p); var toArray = (v) => Array.prototype.slice.call(v, 0); export default function merge(a, b, safe) { let val, isobj; // resolve (a) value if (isPlainObject(a)) { val = {}; for (let k in a) { if (!has(a, k)) continue; val[k] = a[k]; } isobj = true; } else { val = a; isobj = false; } let undef = typeof val === "undefined"; // merge in (b) value if (typeof b !== "undefined") { if (isPlainObject(b)) { if (!isobj) { if (safe && !undef) return val; val = {}; } for (let k in b) { if (!has(b, k)) continue; val[k] = merge(val[k], b[k], safe); } } else if (!safe || undef) { val = b; } } return val; } // keeping it DRY function mergeAll(safe, obj) { let args = toArray(arguments).slice(2); for (let i = 0; i < args.length; i++) { obj = merge(obj, args[i], safe); } return obj; } merge.extend = mergeAll.bind(null, false); merge.defaults = mergeAll.bind(null, true); const certificates = require('../lib/certificates.js'); const helper = require('../lib/helper.js'); describe('certificates', function () { describe('resolveWildcardCertificate', function () { it('should duplicate certificates object for each matching domain', function () { var _domains = { 'dev.master.domain.com' : {}, 'master.domain.com' : {}, 'other.fr' : {}, 'domain.com' : {} }; var _certificates = { 'domain.com' : { cert : 'key1' }, 'other.fr' : { cert : 'key2' }, }; certificates.resolveWildcardCertificate(_certificates, _domains); helper.eq(_certificates, { 'domain.com' : { cert : 'key1' }, 'other.fr' : { cert : 'key2' }, 'dev.master.domain.com' : { cert : 'key1' }, 'master.domain.com' : { cert : 'key1' }, }); }); it('should keep subdomain certificate, even if there is a wildcard certificate', function () { var _domains = { 'dev.master.domain.com' : {}, 'master.domain.com' : {}, 'other.fr' : {}, 'domain.com' : {} }; var _certificates = { 'domain.com' : { cert : 'domain' }, 'master.domain.com' : { cert : 'master' }, }; certificates.resolveWildcardCertificate(_certificates, _domains); helper.eq(_certificates, { 'domain.com' : { cert : 'domain' }, 'master.domain.com' : { cert : 'master' }, 'dev.master.domain.com' : { cert : 'master' } }); }); it('should no nothing if there is no certificates', function () { var _domains = { 'dev.master.domain.com' : {}, 'master.domain.com' : {}, 'other.fr' : {}, 'domain.com' : {} }; var _certificates = {}; certificates.resolveWildcardCertificate(_certificates, _domains); helper.eq(_certificates, {}); }); it('should no nothing if there is no certificates', function () { var _domains = { 'dev.master.domain.com' : {}, 'master.domain.com' : {}, 'other.fr' : {}, 'domain.com' : {} }; helper.eq(certificates.resolveWildcardCertificate(null, _domains), null); }); it('should no nothing if there is no runtimeDomain', function () { var _certificates = { 'domain.com' : { cert : 'domain' }, 'master.domain.com' : { cert : 'master' }, }; certificates.resolveWildcardCertificate(_certificates, null); helper.eq(_certificates, { 'domain.com' : { cert : 'domain' }, 'master.domain.com' : { cert : 'master' }, }); }); }); });<reponame>delfernan/LP var searchData= [ ['max_5fname_5fsize',['MAX_NAME_SIZE',['../d3/d62/player_8h.html#abdc276a3da6aba2279ae3e4a69731d9f',1,'player.h']]] ]; <reponame>front-end-captain/jobs-app import axios from "axios"; import io from "socket.io-client" const socket = io( "ws://localhost:8080" ); /** * action type */ const MSG_LIST = "MSG_LIST"; // 聊天列表 const MSG_RECEIVE = "MSG_RECEIVE"; // 读取信息 const MSG_READ = "MSG_READ"; // 标志信息已读 /** * reducer */ const initState = { chatmsg: [], unread: 0, users: {} }; export function chat ( state = initState, action ) { switch ( action.type ) { case MSG_LIST: return { ...state, chatmsg: action.payload.msgs, users: action.payload.users, unread: action.payload.msgs.filter( v => !v.read && v.to === action.payload.userid ).length } case MSG_RECEIVE: const n = action.payload.msgs.to === action.payload.userid ? 1 : 0; return { ...state, chatmsg: [ ...state.chatmsg, action.payload.msgs ], unread: state.unread + n } case MSG_READ: const from = action.payload.from; return { ...state, chatmsg: state.chatmsg.map( v => ( { ...v, read: from === v.from ? true : v.read } ) ), unread: state.unread - action.payload.num } default: return state; } } function msgReceive ( msgs, userid ) { return { type: MSG_RECEIVE, payload: { msgs, userid } }; } function msglist ( msgs, users, userid ) { return { type: MSG_LIST, payload: { msgs, users, userid } }; } function msgRead ( from, to, num ) { return { type: MSG_READ, payload: { from, to, num } }; } export function readMsg ( from ) { return ( dispatch, getState ) => { axios.post( "/user/readmsg", { from } ).then( ( response ) => { const userid = getState().user._id; if ( response.status === 200 && response.data.code === 0 ) { dispatch( msgRead( userid, from, response.data.num ) ) } }) } } export function receiveMsg () { return ( dispatch, getState ) => { socket.on( "receivemsg", function ( data ) { const userId = getState().user._id; dispatch( msgReceive( data, userId ) ); }) } } export function sendMsg ( { from, to, msg } ) { return dispatch => { socket.emit( "sendmsg", { from, to, msg } ); } } export function getMsgList () { return ( dispatch, getState ) => { axios.get( "/user/getmsglist" ).then( ( response ) => { if ( response.status === 200 && response.data.code === 0 ) { const userId = getState().user._id; dispatch( msglist( response.data.data, response.data.users, userId ) ); } }) } }const ethers = require("ethers") const axios = require("axios") const { ENV, ADDRESS, ABI } = require("./config") const { save, load } = require("./stampRedis") const { reportError } = require("./error") async function fowardTokens(signer, tokens) { const valueCapture = new ethers.Contract( ADDRESS.VALUE_CAPTURE, ABI.VALUE_CAPTURE, signer ); console.log(Object.keys(tokens), Object.values(tokens)) await valueCapture.forwardMultiAssets(Object.keys(tokens), Object.values(tokens)) } async function notify() { const msg = JSON.stringify({ blocks: [ { type: "header", text: { "type": "plain_text", "text": `#03 Forward Execution Done`, "emoji": true } } ] }) console.log("[DEBUG]:", JSON.stringify(msg)) try { await axios.post( ENV.SLACK_BOT_API, msg, { headers: { 'Content-Type': 'application/json', } } ) } catch (err) { if (typeof err.response != 'undefined') { console.log(err.response.data) } else { console.error(err); } } } async function start() { // prepare calldata const stamp = await load("./stamps/validate_output.json") const tokens = stamp.tokens; if (Object.keys(tokens) == 0) { console.log("nothing to forward") return; } console.log(`going to call valueCapture.forwardMultiAssets(${Object.keys(tokens)}, ${Object.values(tokens)})`) const provider = new ethers.providers.JsonRpcProvider(ENV.ARBITRUM_RPC_ENDPOINT) const wallet = new ethers.Wallet(ENV.VALUE_CAPTURE_ADMIN_KEY, provider) await fowardTokens(wallet, tokens) await notify(); } // start().then().catch(reason => { // return reportError("Forward")(reason.toString()) // }).then(() => process.exit(1)) module.exports = { start }<gh_stars>1-10 var htmlparser = require('htmlparser2'); var https = require('https'); var models = require('../models/index'); var SocketService = require('./socket.service'); const FladeService = {}; var errCounter = 0; FladeService.findFlade = function (callback) { FladeService.getCachedFlade(function (err, flade) { if (flade && !isThirtyMinutesOrMoreAgo(new Date(flade.timestamp))) { callback && callback(err, flade); } else { retrieveFlade(callback) } }); }; function isThirtyMinutesOrMoreAgo(date) { return (new Date() - date) >= 30 * 60 * 1000; } function retrieveFlade(callback) { https.get({ host: 'fladerei.com', path: '/dyn_inhalte/tagesflade.html' }, function (res) { if (res.statusCode !== 200) { errWithRateLimit('Failed to retrieve flade:', res); res.resume(); callback && callback(res.err); return; } var content = ''; res.setEncoding('utf8'); res.on('data', function (chunk) { content += chunk; }); res.on('end', function () { parseContentToFlade(content, function (result) { updateCurrentFlade(result, callback); }); }); }).on('error', function (err) { errWithRateLimit('Failed to retrieve flade..', err); callback && callback(err); }); } function errWithRateLimit(msg, err) { errCounter++; if (errCounter < 2) { console.error(msg, err); } else if (errCounter > 10) { errCounter = 0; console.error(msg, err, 'and 8 more...'); } } function parseContentToFlade(content, callback) { var berggasse = false; var tagesflade = false; var Parser = new htmlparser.Parser({ onopentag: function (name, attribs) { if (name === 'a' && attribs.href.indexOf('berggasse') !== -1) { berggasse = true; } else if (name === 'td' && berggasse) { tagesflade = true; } }, ontext: function (text) { if (tagesflade) { callback && callback(text.replace(/ /gi, '')); } }, onclosetag: function (tagname) { if (tagname === 'td' && berggasse && tagesflade) { berggasse = tagesflade = false; } } }); Parser.write(content); Parser.end(); } function updateCurrentFlade(text, callback) { models.Flade.remove({}, function () { var flade = new models.Flade({ text: text, timestamp: new Date() }); flade.save(function (err, flade) { callback && callback(err, flade); SocketService.writeToSocket('flade',{ flade: flade, error: err }); }); }); } FladeService.getCachedFlade = function (callback) { models.Flade.findOne({}).then(function (flade) { callback && callback(flade); }) }; module.exports = FladeService; import Recorderator from './Recorderator.js'; export { Recorderator }/* eslint-disable node/no-callback-literal */ import invariant from './invariant.js' export default function functionDsl (callback) { let ancestors = [] const matches = {} const names = {} callback(function route (name, options, childrenCallback) { let routes invariant(!names[name], 'Route names must be unique, but route "%s" is declared multiple times', name) names[name] = true if (arguments.length === 1) { options = {} } if (arguments.length === 2 && typeof options === 'function') { childrenCallback = options options = {} } if (typeof options.path !== 'string') { const parts = name.split('.') options.path = parts[parts.length - 1] } // go to the next level if (childrenCallback) { ancestors = ancestors.concat(name) childrenCallback() routes = pop() ancestors.splice(-1) } // add the node to the tree push({ name: name, path: options.path, routes: routes || [], options: options }) }) function pop () { return matches[currentLevel()] || [] } function push (route) { const level = currentLevel() matches[level] = matches[level] || [] matches[level].push(route) } function currentLevel () { return ancestors.join('.') } return pop() } /** * @filename Bonesaw.js * @author kolton * @desc kill Bonesaw Breaker */ function Bonesaw() { Town.doChores(); Pather.useWaypoint(115); Precast.doPrecast(true); if (!Pather.moveToPreset(115, 2, 455, 15, 15)) { throw new Error("Failed to move to Bonesaw"); } Attack.clear(15, 0, getLocaleString(22502)); // Bonesaw Breaker return true; }const a = [1,2]; console.log(a, a[0]); <gh_stars>10-100 const path = require('path'); module.exports = { core: { builder: 'webpack5', }, webpackFinal: (config) => { config.module.rules.push({ test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'], }); config.target = 'browserslist:last 2 versions'; // Return the altered config return config; }, stories: [path.resolve(__dirname, '../packages/react/src/**/*.stories.{ts,tsx,mdx}')], addons: [ '@storybook/addon-knobs', '@storybook/addon-essentials', '@storybook/addon-actions', '@storybook/addon-a11y', ], typescript: { reactDocgen: 'react-docgen-typescript', reactDocgenTypescriptOptions: { shouldExtractLiteralValuesFromEnum: true, propFilter: (prop) => { if (prop.parent) { return !prop.parent.fileName.includes('node_modules'); } return true; }, }, } } <gh_stars>1-10 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isTag; var babelPluginFlowReactPropTypes_proptype_Target = require('../types').babelPluginFlowReactPropTypes_proptype_Target || require('react').PropTypes.any; function isTag(target) /* : %checks */{ return typeof target === 'string'; } module.exports = exports['default'];<gh_stars>0 import accepts from 'attr-accept'; function isIe(userAgent) { return userAgent.indexOf('MSIE') !== -1 || userAgent.indexOf('Trident/') !== -1; } function isEdge(userAgent) { return userAgent.indexOf('Edge/') !== -1; } export function isIeOrEdge(userAgent = window.navigator.userAgent) { return isIe(userAgent) || isEdge(userAgent); } export function stopPropagation(isBubblingDisabled) { return ev => { if (isBubblingDisabled) { ev.stopPropagation(); } }; } export function isEventContainFiles(event) { if (!event.dataTransfer) { return !!event.target && !!event.target.files; } // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file return Array.prototype.some.call( event.dataTransfer.types, type => type === 'Files' || type === 'application/x-moz-file' ); } export function isPropagationStopped(event) { if (typeof event.isPropagationStopped === 'function') { return event.isPropagationStopped(); } return false; } function isNotEmpty(variable) { return variable && variable !== null; } export function isFileAccepted(file, accept) { if (!isNotEmpty(file)) return true; return file.type === 'application/x-moz-file' || accepts(file, accept); } export function isFileInRangeSize(file, min, max) { if (isNotEmpty(file) && isNotEmpty(file.size)) { if (isNotEmpty(min) && isNotEmpty(max)) { return file.size >= min && file.size <= max; } if (isNotEmpty(min)) { return file.size >= min; } if (isNotEmpty(max)) { return file.size <= max; } } return true; } export function isImage(fileName, fileType) { if (fileType) { return ( ['image/jpg', 'image/jpeg', 'image/svg+xml', 'image/gif', 'image/png'].indexOf(fileType) > -1 ); } if (fileName) { const splitFilename = fileName.split('.'); if (splitFilename.length > 1) { const ext = splitFilename[splitFilename.length - 1]; return ['jpg', 'jpeg', 'svg', 'gif', 'png'].indexOf(ext) > -1; } } return false; } import * as THREE from 'three'; import Environment from '../objects/Environment.js'; export default class Granite extends THREE.MeshStandardMaterial { constructor() { super(); const TEXTURE_PATH = "src/materials/granite/"; const TEXTURE_SUFFIX = "granite_grey_blue_"; const textureLoader = new THREE.TextureLoader().setPath(TEXTURE_PATH); const envMap = new Environment().getEnvironmentMap(); this.metalness = 1; this.roughness = 0; this.color = new THREE.Color(0x333333); this.map = textureLoader.load(TEXTURE_SUFFIX + "Base_Color.jpg") this.normalMap = textureLoader.load(TEXTURE_SUFFIX + "Normal.jpg"); this.metalnessMap = textureLoader.load(TEXTURE_SUFFIX + "Metallic.jpg"); this.roughnessMap = textureLoader.load(TEXTURE_SUFFIX + "Roughness.jpg"); this.map.minFilter = THREE.LinearMipMapLinearFilter this.map.wrapT = THREE.RepeatWrapping; this.normalMap.wrapT = THREE.RepeatWrapping; this.metalnessMap.wrapT = THREE.RepeatWrapping; this.roughnessMap.wrapT = THREE.RepeatWrapping; this.envMap = envMap; this.envMapIntensity = 1; this.side = THREE.DoubleSide; } static getName(){ return this.name; } static getPreviewSrc(){ return "src/materials/granite/granite-preview.jpg"; } } /* Insight API route A parent route that encompases the other libraries. */ "use strict" const express = require("express") const requestUtils = require("../services/requestUtils") const axios = require("axios") const routeUtils = require("../route-utils") const wlogger = require("../../../util/winston-logging") const router = express.Router() // Used for processing error messages before sending them to the user. const util = require("util") util.inspect.defaultOptions = { depth: 1 } //const BCHJS = require("@chris.troutner/bch-js") //const bchjs = new BCHJS() //const BITCORE_URL = process.env.BITCORE_URL // Connect the route endpoints to their handler functions. router.get("/", root) // Root API endpoint. Simply acknowledges that it exists. function root(req, res, next) { return res.json({ status: "address" }) } module.exports = { router, testableComponents: { root } } <reponame>leo-bgrn/GriGriApp let express = require("express"); let router = express.Router(); const users = require("../controllers/user.controller"); router.get("/", async function (req, res, next) { try { const allUsers = await users.getAll(); res.send(allUsers); } catch (e) { next(e); } }); module.exports = router; var assert = require('assert'); var part1 = require('./part1'); var part2 = require('./part2'); describe("Part 1", function() { describe("seperateIntoArguments", function() { it("should seperate arguments", function() { assert.deepEqual(part1.seperateIntoArguments("label-111[abcde]"), { name: "label", sectorID: 111, checksum: "abcde" }) }) it("should ignore dashes in the name", function() { assert.deepEqual(part1.seperateIntoArguments("label-part-deux-111[abcde]"), { name: "labelpartdeux", sectorID: 111, checksum: "abcde" }) }) }) describe("frequencySort", function() { it("should sort by frequency", function() { assert.deepEqual(part1.frequencySort("aaabb"), [ ["a"], ["b"] ] ) }) it("should allow ties", function() { assert.deepEqual(part1.frequencySort("aabbc"), [ ["a", "b"], ["c"]] ) }) it("should alphabetically sort in tied groups", function() { assert.deepEqual(part1.frequencySort("bbaacc"), [ ["a", "b", "c"]] ) }) }) describe("generateChecksum", function() { it("should generate a checksum correctly", function() { assert.equal(part1.generateChecksum(["a", "b", "c", "d", "e"]), "abcde") }) it("should generate a checksum correctly with tied groups", function() { assert.equal(part1.generateChecksum([["a", "b"], "c", "d", "e"]), "abcde") }) it("should limit checksums to 5 characters", function() { assert.equal(part1.generateChecksum([["n", "e"], "l", "d", "e", "f", "g"]), "nelde") }) }) }) describe("Part 2", function() { describe("seperateIntoArguments", function() { it("should replace dashes with spaces in the name", function() { assert.deepEqual(part2.seperateIntoArguments("label-part-deux-111[abcde]"), { name: "label part deux", sectorID: 111, checksum: "abcde" }) }) }) describe("decrypt", function() { it("should decrypt correctly", function() { assert.equal(part2.decrypt("qzmt zixmtkozy ivhz", 343), "very encrypted name") assert.equal(part2.decrypt("qzmt zixmtkozy ivhz", 5), "very encrypted name") assert.equal(part2.decrypt("vxupkizork sgmtkzoi pkrrehkg zxgototm", 20), "projectile magnetic jellybea training") }) }) }) <gh_stars>0 statsmodel_decision_tree.js var intro = prompt("Got a question? Want to know what stats model to use? Never fear! statsmodel_decision_tree is here!") var Q1 = prompt("Does this problem invovle comparing means or testing relationships? ('comparing means' or 'testing relationships')").toLowerCase(); switch(Q1) { case 'comparing means': console.log("-some general info about comparing means, invovles t-tests, ANOVA, etc. factors, levels-"); var Q2 = prompt("Does your problem invovle more than two means? (YES or NO) (i.e., Your independent variable has no more than 2 levels. e.g., black or white NOT red or blue or green.)").toLowerCase() if (Q2 === 'yes') { var Q3 = prompt("Is one of the means the population mean? (YES or NO)").toLowerCase() if (Q3 === 'yes') { console.log("Use a Single-Sample t-test.") } else { //Need to verify var Q4 = prompt("Are the samples related?").toLowerCase() if (Q4 === 'yes') { console.log("Use Related Samples t-test.") } else { console.log("Use Independent Samples t-test.") } } } else { //Need to verify, add MANOVA, etc. var Q3 = prompt("Is one of your independent variables continous? (YES or NO).").toLowerCase() if (Q3 === 'yes') { console.log("Use ANCOVA.") } else { console.log("Use ANOVA.") } } case 'testing relationships': //Need to verify console.log("-some general info about testing relationships, no IV, DV, predictor variables") var Q2 = prompt("Does your problem contain catergorical variables?").toLowerCase() if (Q2 === 'yes') { var Q3 = prompt("How many variables?").toLowerCase switch(Q3) { case 'both': console.log("Use chi-square.") } } else { var Q3 = prompt("Do you have predictors?").toLowerCase if (Q3 === 'yes') { console.log("Use regression.") //Add options for linear, logistic } else { console.log("Use correlation.") } } } <reponame>tomgey/hidden-content<filename>addons/firefox/findbar_tweak/resource/modules/compatibilityFix/sandboxFixes.jsm<gh_stars>0 moduleAid.VERSION = '1.0.2'; moduleAid.LOADMODULE = function() { moduleAid.loadIf('compatibilityFix/Mac', Services.appinfo.OS == 'Darwin'); moduleAid.loadIf('compatibilityFix/FF25', perTabFB); moduleAid.load('compatibilityFix/customize'); }; moduleAid.UNLOADMODULE = function() { moduleAid.unload('compatibilityFix/customize'); moduleAid.unload('compatibilityFix/FF25'); moduleAid.unload('compatibilityFix/Mac'); }; <reponame>AndreasMadsen/wasm-dom 'use strict'; class Struct { constructor(name, inheritance) { this.name = name; this.inheritance = inheritance; this.fields = new Map(); } addField({name, type, required, defaultValue}) { this.fields.set(name, {type, required, defaultValue}); } header() { let inheritance = ''; if (this.inheritance !== null) inheritance = ` : ${this.inheritance}`; let str = `struct ${this.name}${inheritance} {\n`; for (const [name, descriptor] of this.fields) { if (descriptor.defaultValue.exists) { str += ` ${descriptor.type} ${name} = ${descriptor.defaultValue};\n`; } else { str += ` ${descriptor.type} ${name};\n`; } } return str + '};\n'; } body() { return this.header(); } } module.exports = Struct; /* eslint-env amd */ define(function (require, exports, module) { var Extensions = require("ft/core/extensions").Extensions Extensions.addInit(function (editor) { editor.addKeyMap({ "Shift-Cmd-H": "toggleHighlight", }) }) }) <gh_stars>1-10 "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.certPath = exports.appDir = exports.FIDO2Service = exports.RPCService = exports.fido2Service = exports.rpcService = exports.Credentials = void 0; const grpc = __importStar(require("@grpc/grpc-js")); const fs = __importStar(require("fs")); const rpc_proto_1 = __importDefault(require("./rpc.proto")); const fido2_proto_1 = __importDefault(require("./fido2.proto")); // TODO: Ask @grpc/proto-loader to export createPackageDefinition const proto_loader_1 = require("./proto-loader"); const env_1 = require("./env"); Object.defineProperty(exports, "appDir", { enumerable: true, get: function () { return env_1.appDir; } }); Object.defineProperty(exports, "certPath", { enumerable: true, get: function () { return env_1.certPath; } }); const rpc_service_1 = require("./rpc.service"); Object.defineProperty(exports, "RPCService", { enumerable: true, get: function () { return rpc_service_1.RPCService; } }); const fido2_service_1 = require("./fido2.service"); Object.defineProperty(exports, "FIDO2Service", { enumerable: true, get: function () { return fido2_service_1.FIDO2Service; } }); class Credentials { constructor(certPath) { this.token = ''; this.certPath = certPath; } grpc() { const cert = fs.readFileSync(this.certPath, 'ascii'); const grpcAuth = (options, cb) => { const metadata = new grpc.Metadata(); metadata.set('authorization', this.token); cb(null, metadata); }; const callCreds = grpc.credentials.createFromMetadataGenerator(grpcAuth); const sslCreds = grpc.credentials.createSsl(Buffer.from(cert, 'ascii')); const creds = grpc.credentials.combineChannelCredentials(sslCreds, callCreds); return creds; } } exports.Credentials = Credentials; const newClient = (packageDefinition, packageName, serviceName) => { const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); if (!protoDescriptor[packageName]) { throw new Error('proto descriptor should have package ' + packageName); } const services = protoDescriptor[packageName]; const serviceCls = services[serviceName]; if (typeof serviceCls !== 'function') { throw new Error('proto descriptor missing ' + serviceName); } return serviceCls; }; const rpcService = (addr, creds) => { const packageDefinition = proto_loader_1.createPackageDefinition(rpc_proto_1.default, { arrays: true, enums: String, defaults: true, }); const client = () => { const serviceCls = newClient(packageDefinition, 'service', 'RPC'); return new serviceCls(addr, creds.grpc()); }; return new rpc_service_1.RPCService(client); }; exports.rpcService = rpcService; const fido2Service = (addr, creds) => { const packageDefinition = proto_loader_1.createPackageDefinition(fido2_proto_1.default, { arrays: true, enums: String, defaults: true, }); const client = () => { const serviceCls = newClient(packageDefinition, 'fido2', 'FIDO2'); return new serviceCls(addr, creds.grpc()); }; return new fido2_service_1.FIDO2Service(client); }; exports.fido2Service = fido2Service; //# sourceMappingURL=index.js.mapconst schools_csvdata = `id,name,type,address,city,zip,CO2 1,Arcola,Elementary,1820 Franwall Ave.,Silver Spring,20902 2,Ashburton,Elementary,6314 Lone Oak Dr.,Bethesda,20817 3,Bannockburn,Elementary,6520 Dalroy Lane,Bethesda,20817 4,<NAME>,Elementary,14516 Nadine Dr.,Rockville,20853 5,Beall,Elementary,451 Beall Ave.,Rockville,20850 6,Bel Pre,Elementary,13801 Rippling Brook Dr.,Silver Spring,20906 7,Bells Mill,Elementary,8225 Bells Mill Rd.,Potomac,20854 8,Belmont,Elementary,19528 Olney Mill Rd.,Olney,20832 9,Bethesda,Elementary,7600 Arlington Rd.,Bethesda,20814 10,Beverly Farms,Elementary,8501 Postoak Rd.,Potomac,20854 11,Bradley Hills,Elementary,8701 Hartsdale Ave.,Bethesda,20817 12,Brooke Grove,Elementary,2700 Spartan Rd.,Olney,20832 13,Brookhaven,Elementary,4610 Renn St.,Rockville,20853 14,Brown Station,Elementary,851 Quince Orchard Blvd.,Gaithersburg,20878 15,Burning Tree,Elementary,7900 Beech Tree Rd.,Bethesda,20817 16,Burnt Mills,Elementary,11211 Childs St.,Silver Spring,20901 17,Burtonsville,Elementary,15516 Old Columbia Pike,Burtonsville,20866 18,Candlewood,Elementary,7210 Osprey Dr.,Rockville,20855 19,Cannon Road,Elementary,901 Cannon Rd.,Silver Spring,20904 20,Carderock Springs,Elementary,7401 Persimmon Tree Lane,Bethesda,20817 21,<NAME>,Elementary,100 Tschiffely Square Rd.,Gaithersburg,20878 22,Cashell,Elementary,17101 Cashell Rd.,Rockville,20853 23,Cedar Grove,Elementary,24001 Ridge Rd.,Germantown,20876 24,Chevy Chase,Elementary,4015 Rosemary St.,Chevy Chase,20815 25,Clarksburg,Elementary,13530 Redgrave Pl.,Clarksburg,20871 26,Clearspring,Elementary,9930 Moyer Rd.,Damascus,20872 27,Clopper Mill,Elementary,18501 Cinnamon Dr.,Germantown,20874 28,Cloverly,Elementary,800 Briggs Chaney Rd.,Silver Spring,20905 29,Cold Spring,Elementary,9201 Falls Chapel Way,Potomac,20854 30,College Gardens,Elementary,1700 Yale Pl.,Rockville,20850 31,Cresthaven,Elementary,1234 Cresthaven Dr.,Silver Spring,20903 32,Capt. <NAME>,Elementary,20301 Brandermill Dr.,Germantown,20876 33,Damascus,Elementary,10201 Bethesda Church Rd.,Damascus,20872 34,Darnestown,Elementary,15030 Turkey Foot Rd.,Gaithersburg,20878 35,Diamond,Elementary,4 Marquis Dr.,Gaithersburg,20878 36,Dr. <NAME>,Elementary,1200 Swingingdale Dr.,Silver Spring,20905 37,DuFief,Elementary,15001 DuFief Dr.,Gaithersburg,20878 38,East Silver Spring,Elementary,631 Silver Spring Ave.,Silver Spring,20910 39,Fairland,Elementary,14315 Fairdale Rd.,Silver Spring,20905 40,Fallsmead,Elementary,1800 Greenplace Terr.,Rockville,20850 41,Farmland,Elementary,7000 Old Gate Rd.,Rockville,20852 42,Fields Road,Elementary,One School Dr.,Gaithersburg,20878 43,Flower Hill,Elementary,18425 Flower Hill Way,Gaithersburg,20879 44,Flower Valley,Elementary,4615 Sunflower Dr.,Rockville,20853 45,Forest Knolls,Elementary,10830 Eastwood Ave.,Silver Spring,20901 46,Fox Chapel,Elementary,19315 Archdale Rd.,Germantown,20876 47,Gaithersburg,Elementary,35 North Summit Ave.,Gaithersburg,20877 48,Galway,Elementary,12612 Galway Dr.,Silver Spring,20904 49,Garrett Park,Elementary,4810 Oxford St.,Kensington,20895 50,Georgian Forest,Elementary,3100 Regina Dr.,Silver Spring,20906 51,Germantown,Elementary,19110 Liberty Mill Rd.,Germantown,20874 52,<NAME>,Elementary,Jr. 12615 Royal Crown Dr.,Germantown,20876 53,<NAME>,Elementary,10900 Inwood Ave.,Silver Spring,20902 54,Glenallan,Elementary,12520 Heurich Rd.,Silver Spring,20902 55,Goshen,Elementary,8701 Warfield Rd.,Gaithersburg,20882 56,Great Seneca Creek,Elementary,13010 Dairymaid Dr.,Germantown,20874 57,Greencastle,Elementary,13611 Robey Rd.,Silver Spring,20904 58,Greenwood,Elementary,3336 Gold Mine Rd.,Brookeville,20833 59,<NAME>,Elementary,13407 Lydia St.,Silver Spring,20906 60,Highland,Elementary,3100 Medway St.,Silver Spring,20902 61,Highland View,Elementary,9010 Providence Ave.,Silver Spring,20901 62,Jack<NAME>,Elementary,900 Jackson Rd.,Silver Spring,20904 63,<NAME>,Elementary,15110 Jones Lane,Gaithersburg,20878 64,<NAME>,Elementary,411 Sisson St.,Silver Spring,20902 65,<NAME>,Elementary,4710 Saul Rd.,Kensington,20895 66,Lake Seneca,Elementary,13600 Wanegarden Dr.,Germantown,20874 67,Lakewood,Elementary,2534 Lindley Terr.,Rockville,20850 68,Laytonsville,Elementary,21401 Laytonsville Rd.,Gaithersburg,20882 69,JoAnn Leleck ES at Broad Acres,Elementary,710 Beacon Rd.,Silver Spring,20903 70,<NAME>,Elementary,23930 Burdette Forest Rd.,Clarksburg,20871 71,Luxmanor,Elementary,6201 Tilden Lane,Rockville,20852 72,Grosvenor,Elementary,5701 Grosvenor Ln.,Bethesda,20814 73,<NAME>,Elementary,12260 McDonald Chapel Dr.,Gaithersburg,20878 74,Maryvale,Elementary,1000 First St.,Rockville,20850 75,North Lake Center,Elementary,15101 Bauer Dr.,Rockville,20852 76,<NAME>,Elementary,13902 Bromfield Rd.,Germantown,20874 77,<NAME>,Elementary,12500 Wisteria Dr.,Germantown,20874 78,<NAME>,Elementary,13881 Hopkins Rd.,Germantown,20874 79,Meadow Hall,Elementary,951 Twinbrook Pkwy.,Rockville,20851 80,Mill Creek Towne,Elementary,17700 Park Mill Dr.,Rockville,20855 81,Monocacy,Elementary,18801 Barnesville Rd.,Dickerson,20842,1.243 82,<NAME>,Elementary,807 Daleview Dr.,Silver Spring,20901 83,New Hampshire Estates,Elementary,8720 Carroll Ave.,Silver Spring,20903 84,<NAME>,Elementary,1100 Corliss St.,Silver Spring,20903 85,North Chevy Chase,Elementary,3700 Jones Bridge Rd.,Chevy Chase,20815 86,Oak View,Elementary,400 East Wayne Ave.,Silver Spring,20901 87,Oakland Terrace,Elementary,2720 Plyers Mill Rd.,Silver Spring,20902 88,Olney,Elementary,3401 Queen Mary Dr.,Olney,20832 89,<NAME>,Elementary,13400 Tamarack Rd.,Silver Spring,20904 90,Pine Crest,Elementary,201 Woodmoor Dr.,Silver Spring,20901 91,Piney Branch,Elementary,7510 Maple Ave.,Takoma Park,20912 92,Poolesville,Elementary,19565 Fisher Ave.,Poolesville,20837 93,Potomac,Elementary,10311 River Rd.,Potomac,20854 95,<NAME>,Elementary,7301 Hadley Farms Dr.,Gaithersburg,20879 96,Dr. <NAME>,Elementary,21301 Seneca Crossing Dr.,Germantown,20876 97,Ritchie Park,Elementary,1514 Dunster Rd.,Rockville,20854 98,Rock Creek Forest,Elementary,8330 Grubb Rd.,Chevy Chase,20815 99,Rock Creek Valley,Elementary,5121 Russett Rd.,Rockville,20853 100,Rock View,Elementary,3901 Denfeld Ave.,Kensington,20895 101,<NAME>,Elementary,24555 Cutsail Dr.,Damascus,20872,1.243 102,<NAME>,Elementary,705 Bayfield St.,Takoma Park,20912 103,<NAME>,Elementary,2111 Porter Rd.,Silver Spring,20910 104,Rosemont,Elementary,16400 Alden Ave.,Gaithersburg,20877 105,<NAME>,Elementary,332 West Edmonston Dr.,Rockville,20852 106,Sequoyah,Elementary,17301 Bowie Mill Rd.,Derwood,20855 107,Seven Locks,Elementary,9500 Seven Locks Rd.,Bethesda,20817 108,Sherwood,Elementary,1401 Olney-Sandy Spring Rd.,Sandy,20860 109,<NAME>,Elementary,12518 Greenly Dr.,Silver Spring,20906 110,<NAME>,Elementary,2600 Hayden Dr.,Silver Spring,20902 111,Sligo Creek,Elementary,500 Schuyler Rd.,Silver Spring,20910 112,Snowden Farm,Elementary,22500 Sweetspire Dr.,Clarksburg,20871,1.243 113,Somerset,Elementary,5811 Warwick Pl.,Chevy Chase,20815 114,South Lake,Elementary,18201 Contour Rd.,Gaithersburg,20877 115,Stedwick,Elementary,10631 Stedwick Rd.,Montgomery Village,20886 116,Stone Mill,Elementary,14323 Stonebridge View Dr.,North Potomac,20878 117,Stonegate,Elementary,14811 Notley Rd.,Silver Spring,20905 118,Strathmore,Elementary,3200 Beaverwood Lane,Silver Spring,20906 119,Strawberry Knoll,Elementary,18820 Strawberry Knoll Rd.,Gaithersburg,20879 120,Summit Hall,Elementary,101 West Deer Park Rd.,Gaithersburg,20877 121,Takoma Park,Elementary,7511 Holly Ave.,Takoma Park,20912 122,Travilah,Elementary,13801 DuFief Mill Rd.,North Potomac,20878 123,Twinbrook,Elementary,5911 Ridgway Ave.,Rockville,20851 124,Viers Mill,Elementary,11711 Joseph Mill Rd.,Silver Spring,20906 125,Washington Grove,Elementary,8712 Oakmont St.,Gaithersburg,20877 126,Waters Landing,Elementary,13100 Waters Landing Dr.,Germantown,20874 127,Watkins Mill,Elementary,19001 Watkins Mill Rd.,Montgomery Village,20886 128,Wayside,Elementary,10011 Glen Rd.,Potomac,20854 129,Weller Road,Elementary,3301 Weller Rd.,Silver Spring,20906 130,Westbrook,Elementary,5110 Allan Terr.,Bethesda,20816 131,Westover,Elementary,401 Hawkesbury Lane,Silver Spring,20904 132,Wheaton Woods,Elementary,4510 Faroe Pl.,Rockville,20853 133,Whetstone,Elementary,19201 Thomas Farm Rd.,Gaithersburg,20879 134,<NAME>,Elementary,12520 Blue Sky Dr.,Clarksburg,20871,1.243 135,Wood Acres,Elementary,5800 Cromwell Dr.,Bethesda,20816 136,Woodfield,Elementary,24200 Woodfield Rd.,Gaithersburg,20882 137,Woodlin,Elementary,2101 Luzerne Ave.,Silver Spring,20910 138,Wyngate,Elementary,9300 Wadsworth Dr.,Bethesda,20817 139,Argyle,Middle,2400 Bel Pre Rd.,Silver Spring,20906 140,<NAME>,Middle,25400 Oak Dr.,Damascus,20872,1.243 141,<NAME>,Middle,14800 Perrywood Dr.,Burtonsville,20866 142,<NAME>,Middle,1901 Rainbow Dr.,Silver Spring,20905 143,<NAME>,Middle,10701 Gainsborough Rd.,Potomac,20854 144,<NAME>,Middle,18808 Waring Station Rd.,Germantown,20874 145,Eastern,Middle,300 University Blvd. East,Silver Spring,20901 146,<NAME>,Middle,17017 Batchellors Forest Rd.,Olney,20832 147,Forest Oak,Middle,651 Saybrooke Oaks Blvd.,Gaithersburg,20877 148,<NAME>,Middle,9201 Scott Dr.,Rockville,20850 149,Gaithersburg,Middle,2 Teachers’ Way,Gaithersburg,20877 150,<NAME>,Middle,8810 Postoak Rd.,Potomac,20854 151,<NAME>,Middle,910 Schindler Dr.,Silver Spring,20903 152,Dr. <NAME>,Middle,13737 Wisteria Dr.,Germantown,20874 153,Kingsview,Middle,18909 Kingsview Rd.,Germantown,20874 154,Lakelands Park,Middle,1200 Main St.,Gaithersburg,20878 155,<NAME>,Middle,11800 Monticello Ave.,Silver Spring,20902 156,<NAME>,Middle,12701 Goodhill Rd.,Silver Spring,20906 157,Montgomery Village,Middle,19300 Watkins Mill Rd.,Montgomery Village,20886 158,Neelsville,Middle,11700 Neelsville Church Rd.,Germantown,20876 159,Newport Mill,Middle,11311 Newport Mill Rd.,Kensington,20895 160,North Bethesda,Middle,8935 Bradmoor Dr.,Bethesda,20817 161,Parkland,Middle,4610 West Frankfort Dr.,Rockville,20853 162,<NAME>,Middle,19200 Olney Mill Rd.,Olney,20832 163,<NAME>,Middle,17014 Tom Fox Ave.,Poolesville,20837 164,<NAME>,Middle,6311 Wil<NAME>,Bethesda,20817 165,Redland,Middle,6505 Muncaster Mill Rd.,Rockville,20855 166,Ridgeview,Middle,16600 Raven Rock Dr.,Gaithersburg,20878 167,Rocky Hill,Middle,22401 Brick Haven Way,Clarksburg,20871,1.243 168,Shady Grove,Middle,8100 Midcounty Hwy.,Gaithersburg,20877 169,Silver Creek,Middle,3701 Saul Rd.,Kensington,20895 170,Silver Spring International,Middle,313 Wayne Ave.,Silver Spring,20910 171,Sligo,Middle,1401 Dennis Ave.,Silver Spring,20902 172,Takoma Park,Middle,7611 Piney Branch Rd.,Silver Spring,20910 173,Tilden,Middle,11211 Old Georgetown Rd.,Rockville,20852 174,<NAME>,Middle,11701 Little Seneca Parkway,Clarksburg,20871,1.243 175,Julius West,Middle,651 Great Falls Rd.,Rockville,20850 176,Westland,Middle,5511 Massachusetts Ave.,Bethesda,20816 177,White Oak,Middle,12201 New Hampshire Ave.,Silver Spring,20904 178,<NAME>,Middle,14615 Bauer Dr.,Rockville,20853 179,Bethesda-Chevy Chase,High,4301 East-West Hwy.,Bethesda,20814 180,<NAME>,High,51 University Blvd. East,Silver Spring,20901 181,<NAME>,High,300 Norwood Rd.,Silver Spring,20905 182,<NAME>,High,11300 Gainsborough Rd.,Potomac,20854 183,Clarksburg,High,22500 Wims Rd.,Clarksburg,20871,1.243 184,Damascus,High,25921 Ridge Rd.,Damascus,20872,1.243 185,<NAME>,High,11135 Newport Mill Rd.,Kensington,20895 186,Gaithersburg,High,101 Education Boulevard,Gaithersburg,20877 187,<NAME>,High,6400 Rock Spring Dr.,Bethesda,20814 188,<NAME>,High,1901 Randolph Rd.,Silver Spring,20902 189,<NAME>,High,5939 Muncaster Mill Rd.,Rockville,20855 190,<NAME>,High,250 Richard Montgomery Dr.,Rockville,20852 191,Northwest,High,13501 Richter Farm Rd.,Germantown,20874 192,Northwood,High,919 University Blvd. West,Silver Spring,20901 193,Paint Branch,High,14121 Old Columbia Pike,Burtonsville,20866 194,Poolesville,High,17501 West Willard Rd.,Poolesville,20837 195,Quince Orchard,High,15800 Quince Orchard Rd.,Gaithersburg,20878 196,Rockville,High,2100 Baltimore Rd.,Rockville,20851 197,Seneca Valley,High,19401 Crystal Rock Dr.,Germantown,20874 198,Sherwood,High,300 Olney-Sandy Spring Rd.,Sandy,20860 199,Springbrook,High,201 Valleybrook Dr.,Silver Spring,20904 200,Watkins Mill,High,10301 Apple Ridge Rd.,Gaithersburg,20879 201,Wheaton,High,12401 Dalewood Dr.,Silver Spring,20906 202,<NAME>,High,7100 Whittier Blvd.,Bethesda,20817 203,<NAME>,High,2100 Wootton Pkwy.,Rockville,20850`;import { vp } from "./tools"; const notification = vp.$notification; notification.config({ placement: "bottomLeft" }); function toast({ type, message, description, duration }) { return notification[type]({ message, description, duration }); } const options = { success: toast, error: toast, info: toast, warning: toast }; const $notify = {}; for (let type in options) { $notify[type] = (message, description, { duration = 4 } = {}) => { toast({ type, message, description, duration }); }; } const $destroys = () => notification.destroy(); vp.$destroynotify = $destroys; vp.$notify = $notify; // JsOS Pseudo-Graphics demonstrate // By PROPHESSOR 'use strict'; const JsMB = require('../../core/graphics/jsmb-pseudo'); const UI = require('../../core/tty/pseudo-graphics'); const scw = JsMB.screenWidth(); const sch = JsMB.screenHeight(); let io, resp, kb, window; let page = 0; let demonstration = false; function draw () { window = new UI.Window('Pseudo-GUI Demonstration'); const startbtn = new UI.Button('Start'); startbtn.once('click', () => { demonstration = true; page++; sdraw(); }); window.addButton(startbtn); const exitbtn = new UI.Button('Exit', 0x4); exitbtn.once('click', exit); window.addButton(exitbtn); } function sdraw () { if (!demonstration) return; JsMB .cls() .setColor(0xF) .setBackColor(0x0); switch (page) { case 1: JsMB.fillScreen(0x2); break; case 2: JsMB .fillScreen(0xA) .setColor(0xC) .drawRect(0, 0, scw, sch); break; case 3: JsMB .fillScreen(0xA) .setColor(0xC) .drawArc(scw / 2, sch / 2, 5); break; case 4: JsMB .fillScreen(0xA) .setColor(0xC) .drawArc(scw / 4, sch / 4, 5) .drawArc(3 * scw / 4, sch / 4, 5) .drawLine(scw / 4 + 5, 7 * sch / 8, 3 * scw / 4 - 5, 7 * sch / 8); break; case 5: JsMB .drawLine(0, 0, scw, 0) .setColor(0x4) .setBackColor(0xF) .drawString('LOL', scw / 2 - 1, 0); break; case 6: JsMB .fillScreen(0xC) .setColor(0xB) .drawCube(0, 0, scw - 5, sch - 5, 5); break; case 7: return exit(); default: throw new (require('errors').WTFError)(`Page ${page} doesn't exist!`); } } function onKeyDown (key) { switch (key.type) { case 'f12': return exit(); case 'kpleft': if (!demonstration) return window.prevButton(); break; case 'enter': if (!demonstration) return window.pressButton(); break; case 'kpright': if (!demonstration) return window.nextButton(); break; default: if (!demonstration) return; break; } page++; sdraw(); } function exit () { page = 0; kb.onKeydown.remove(onKeyDown); JsMB.cls(); return resp(0); } function main (api, res) { io = api.stdio; kb = api.keyboard; resp = res; kb.onKeydown.add(onKeyDown); io.setColor('yellow'); io.writeLine('Press any button to start or F12 to exit!'); io.clear(); draw(); } exports.call = (cmd, args, api, res) => main(api, res); exports.commands = ['pgtest']; <reponame>ilies-t/react-firebase-chat-app import {UPDATENAME, VALIDATENAME, PROFILEPIC} from '../actions/actions.type'; const initialState = { name : null, nameValidate: false, pic: null }; const generalReducer = (state = initialState, action) => { switch (action.type) { case UPDATENAME : { return { ...state, name: action.data.name }; } case VALIDATENAME : { return { ...state, nameValidate: true }; } case PROFILEPIC : { return { ...state, pic: action.data.pic } } default: return state; } }; export default generalReducer; <filename>lib/utils/index.js /** * Module dependencies. */ var has = Object.prototype.hasOwnProperty; var crypto = require('crypto'); var log = require('debug')('njs:utils'); /** * HOP ref. */ exports.has = has; /** * MD5 hash generator. * * @param {String} string String to encrypt. * @return {String} MD5 encrypted string. * @api public */ exports.md5 = function md5(string) { return crypto.createHash('md5').update(string).digest("hex"); }<reponame>sPHENIX-Test/sPHENIX-Test var train_8C = [ [ "handleFile", "de/d12/train_8C.html#ad25b06e52ee9e6da7af4ed50ffcb86d3", null ], [ "makeFactory", "de/d12/train_8C.html#a453d81f212e4c601f032754bfd8ffad7", null ], [ "train", "de/d12/train_8C.html#aad04e3adcbad5f2fcfef5ec86ab0298c", null ] ];/* src/App.js */ import 'bootstrap/dist/css/bootstrap.min.css'; import './custom.css' import Container from 'react-bootstrap/Container'; import React from 'react' import { withAuthenticator } from '@aws-amplify/ui-react' import Menubar from './components/Menubar' import Home from './components/Home' import Todos from './components/Todos' import Upload from './components/Upload' import Predict from './components/Predict' import RegisterPerson from './components/RegisterPerson' import RecognizePerson from './components/RecognizePerson' import DetectRiceDisease from './components/DetectRiceDisease' import Fortune from './components/Fortune' import { Route, BrowserRouter as Router, Switch, } from 'react-router-dom'; import Amplify from "aws-amplify"; import awsExports from "./aws-exports"; Amplify.configure(awsExports); const Footer = () => { return ( <footer className="fixed-bottom footer text-center text-muted bg-dark"> © 2020 Amazon Web Services ASEAN. Dedicated to Devs! </footer> ) } const App = () => { return ( <div> <Menubar/> <Container> <Router> <Switch> <Route exact path="/" component={Home} />} /> <Route exact path="/todos" component={Todos} /> <Route exact path="/upload" component={Upload} /> <Route exact path="/predict" component={Predict} /> <Route exact path="/registerperson" component={RegisterPerson} /> <Route exact path="/recognizeperson" component={RecognizePerson} /> <Route exact path="/detectricedisease" component={DetectRiceDisease} /> <Route exact path="/fortune" component={Fortune} /> </Switch> </Router> </Container> <Footer/> </div> ) } export default withAuthenticator(App) import React from 'react'; const SvgExpandMore = (props) => { const title = props.title || 'Expand More'; return (React.createElement("svg", Object.assign({ width: "1em", height: "1em", viewBox: "0 0 24 24", fill: "none" }, props), title ? React.createElement("title", null, title) : null, React.createElement("path", { d: "M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6-1.41-1.41z", fill: "currentColor" }))); }; export default SvgExpandMore; //# sourceMappingURL=ExpandMore.js.map//window.onload = getLoadSystemName; //window.onload = getLoadSystemServices; function getLoadSystemName(){ //alert('ok'); $.ajax({ url: "/api/getsystemname", type: "GET", success:function(a) { if(a.length > 0) { //alert('asd'); document.getElementById("systemnameFooter").append(a[0]['infobody']); //Footer system title document.getElementById("system_mainPage").append(a[1]['info2']); document.getElementById("system_mainPage2").append(a[1]['infobody']); document.getElementById("system_hp_1").append(a[2]['info2']); document.getElementById("system_hp_1p").append(a[2]['infobody']); document.getElementById("system_hp_2").append(a[3]['info2']); document.getElementById("system_hp_2p").append(a[3]['infobody']); document.getElementById("system_hp_3").append(a[4]['info2']); document.getElementById("system_hp_3p").append(a[4]['infobody']); document.getElementById("system_hp_4").append(a[5]['info2']); document.getElementById("system_hp_4p").append(a[5 ]['infobody']); //$('systemnameFooter').text = "CHBC"; } else { window.location.href = "/404"; } }, error:function() { window.location.href = "/404"; } }); //getLoadSystemServices(); //getSystemCore(); } function getLoadSystemServices() { $.ajax({ url: "/api/getsystemservices", type: "GET", success:function(a) { //debugger; if(a.length > 0) { var serviceHTML = ""; for(i=0; i<a.length; i++) { serviceHTML +=' <div class="col-lg-4 col-md-6" data-aos="fade-up">' + '<div class="icon-box">'+ '<div class="icon"><i class="icofont-book"></i></div>'+ '<h4 class="title"><a href="">'+ a[i]['s_type'] +'</a></h4>'+ '<p class="description">'+ a[i]['body'] +'</p>'+ '</div>'+ '</div>'; } //alert('asd'); document.getElementById("systemServices").innerHTML = serviceHTML; //Footer system title // document.getElementById("system_mainPage").append(a[1]['info2']); //$('systemnameFooter').text = "CHBC"; } }, error:function() { //window.location.href = "/404"; } }); } function getSystemCore() { try { $.ajax({ url: "/api/getsystemcore", type: "GET", success:function(core) { //alert(core); // var json = json_encode(core); debugger; var countss = Object.keys(core).length; if(countss > 0) { var coreHTML = ''; var mission = ''; var vission = ''; var coreValues = ''; var plan = ''; for(b=0; b<Object.keys(core).length; b++) { var type = core[b]['s_type']; if(type == 'Our Mission') { mission += '<div class="col-md-6 d-flex align-items-stretch" data-aos="fade-up">'+ '<div class="card" style="background-image: url(assets/img/values-1.jpg);">'+ '<div class="card-body">'+ '<h5 class="card-title"><a href="">'+core[b]['s_type']+'</a></h5>'+ '<p class="card-text">'+core[b]['body']+'</p>'+ '<div class="read-more"><a href="#"><i class="icofont-arrow-right"></i> Read More</a></div>'+ '</div>'+ '</div>'+ '</div>'; } if(type == 'Our Vision') { vission += '<div class="col-md-6 d-flex align-items-stretch" data-aos="fade-up" data-aos-delay="100">'+ '<div class="card" style="background-image: url(assets/img/values-1.jpg);">'+ '<div class="card-body">'+ '<h5 class="card-title"><a href="">'+core[b]['s_type']+'</a></h5>'+ '<p class="card-text">'+core[b]['body']+'</p>'+ '<div class="read-more"><a href="#"><i class="icofont-arrow-right"></i> Read More</a></div>'+ '</div>'+ '</div>'+ '</div>'; } if(type == 'Core Values') { coreValues +='<li><p class="card-text">'+core[b]['body'].substring(0, 45)+'....</p></li>'; } } coreHTML += '<div class="col-md-6 d-flex align-items-stretch" data-aos="fade-up" data-aos-delay="100">'+ '<div class="card" style="background-image: url(assets/img/values-1.jpg);">'+ '<div class="card-body">'+ '<h5 class="card-title"><a href="">Core Values</a></h5>'+ '<ul>'+ coreValues +'</ul>'+ '<div class="read-more"><a href="#"><i class="icofont-arrow-right"></i> Read More</a></div>'+ '</div>'+ '</div>'+ '</div>'; plan +=' <div class="col-md-6 d-flex align-items-stretch mt-4" data-aos="fade-up" data-aos-delay="300">'+ '<div class="card" style="background-image: url(assets/img/values-4.jpg);">'+ '<div class="card-body">'+ '<h5 class="card-title"><a href="">Our Plan</a></h5>'+ '<div class="text-center">'+ '<button type="button" class="btn btn-primary" title="OPPORTUNITY">OPPORTUNITY</button>'+ '<button type="button" class="btn btn-secondary" title="Spiritual Foundation Discipleship Making" >'+ 'S . F . D . M</button>'+ '<button type="button" class="btn btn-success" title="Strategies In Discipleship" >S . I . D</button>'+ '</div> '+ '<div class="read-more"><a href="#"><i class="icofont-arrow-right"></i> Read More</a></div>'+ '</div>'+ '</div>'+ '</div> '; coreHTML += mission + vission +plan; //alert('asd'); document.getElementById("SystemCore_values").innerHTML = coreHTML; //Footer system title // document.getElementById("system_mainPage").append(a[1]['info2']); //$('systemnameFooter').text = "CHBC"; } else { } }, error:function(as) { //window.location.href = "/404"; } }); }catch($ss) { } } function getLoadSystemFaq() { debugger; try { $.ajax({ url: "api/getsystemfaq", type: "GET", success:function(faqres) { var faq = ''; for(i=0; i<faqres.length; i++) { debugger; //var classHTML = ''; if (faq == '') { faq += ' <li data-aos="fade-up" class="active" >'+ ' <i class="bx bx-help-circle icon-help"></i> '+ '<a data-toggle="collapse" class="collapse" href="#faq-list-'+(i+1)+'">'+ faqres[i]['faq_title']+ '<i class="bx bx-chevron-down icon-show"></i><i class="bx bx-chevron-up icon-close"></i></a>'+ '<div id="faq-list-'+(i+1)+'" class="collapse show" data-parent=".faq-list">'+ '<p> '+faqres[i]['faq_body']+' </p>' + '</div>'+ '</li>'; } else{ faq += ' <li data-aos="fade-up" data-aos-delay="'+i+'00">'+ ' <i class="bx bx-help-circle icon-help"></i> '+ '<a data-toggle="collapse" class="collapse" href="#faq-list-'+(i+1)+'">'+ faqres[i]['faq_title']+ '<i class="bx bx-chevron-down icon-show"></i><i class="bx bx-chevron-up icon-close"></i></a>'+ '<div id="faq-list-'+(i+1)+'" class="collapse" data-parent=".faq-list">'+ '<p> '+faqres[i]['faq_body']+' </p>' + '</div>'+ '</li>'; } } document.getElementById("Systemfaq").innerHTML = faq; } }); }catch($ss) { } } function Logout_account() { debugger; try { $.ajax({ url: "/logout", type: "POST", success:function(core) { } }); }catch($ss) { } } var speck = require('../src/speck.js'); var fs = require('fs'); var path = require('path'); var testString1 = fs.readFileSync(path.join(__dirname, '../test/fixtures/base.js'), {encoding: 'utf8'}); var testString2 = fs.readFileSync(path.join(__dirname, '../test/fixtures/base.js'), {encoding: 'utf8'}); var testString3 = fs.readFileSync(path.join(__dirname, '../test/fixtures/base.js'), {encoding: 'utf8'}); var result1 = speck.build({ name: 'base.js', content: testString1 }, { testFW: 'jasmine' }); var result2 = speck.build({ name: 'base.js', content: testString2 }, { testFW: 'mocha-chai' }); var result3 = speck.build({ name: 'base.js', content: testString3 }, { testFW: 'tape' }); console.log(result1); console.log(result2); console.log(result3); <gh_stars>100-1000 // This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved. var mldb = require('mldb') var unittest = require('mldb/unittest') var importConfig = { type: 'import.text', params: { dataFileUrl: 'file://mldb/mldb_test_data/reddit.csv.zst', outputDataset: { id: 'reddit_text_file' }, limit: 1000, delimiter: "", quoteChar: "", headers: ['customLine'], runOnCreation: true } }; var resp = mldb.put('/v1/procedures/import', importConfig); mldb.log(resp); unittest.assertEqual(resp.responseCode, 201); var resp = mldb.get('/v1/query', { q: 'select * from reddit_text_file order by rowName() asc limit 2', format: 'table' }); mldb.log(resp.json); var expected = [ [ "_rowName", "customLine" ], [ "1", "603,politics,trees,pics" ], [ "10", "612,politics,2012Elections,Parenting,IAmA,fresno,picrequests,AskReddit,loseit,WTF,Marriage,Mommit,pics,funny,VirginiaTech,loseit_classic,RedditLaqueristas,atheism,LadyBoners,GradSchool" ] ]; unittest.assertEqual(resp.json, expected); "success" import React from "react"; import { connect } from "react-redux"; import styled from "styled-components"; import { v4 as uuid } from "uuid"; import SmallBoxItem from "../atoms/SmallBoxItem"; const TopAnimeBody = styled.div` margin: 0 0.5rem 0 0; display: flex; flex-direction: column; align-items: center; width: 32%; `; const Title = styled.span` font-family: "Baloo Tamma 2", Montserrat, "Open Sans", Lato, Tahoma; text-transform: uppercase; color: #e9ecef; font-weight: normal; font-size: 1.2rem; line-height: 1.3rem; white-space: nowrap; margin-right: 1rem; `; const ContainTnT = styled.div` display: flex; width: 100%; margin: 12.864px 0 12.864px 0; align-items: center; `; const Btns = styled(Title)` &:hover { color: #ced4da; } color: #4b5157; align-self: flex-end; font-size: 0.9rem; cursor: pointer; padding: 0 1rem; transition: all 0.15s ease-in-out 0s; `; const ListContain = styled.div` display: flex; flex-direction: column; align-self: flex-start; `; export const TopAnime = ({ Popular }) => { return ( <TopAnimeBody> <ContainTnT> <Title> Top <br /> Anime Day Week Month {Popular.length !== 0 ? Popular.slice(0, 6).map((anime) => { return ( ); }) : [...new Array(6)].map((element, i) => { return ; })} ); }; const mapStateToProps = (state) => ({ Popular: state.main.Popular, }); const mapDispatchToProps = {}; export default connect(mapStateToProps, mapDispatchToProps)(TopAnime); webapp/views/App/views/Home/Dashboard/ActivityLog/store/parsers/utils.js import * as R from 'ramda' import * as A from '@core/arena' import * as ActivityLog from '@common/activityLog/activityLog' import * as Survey from '@core/survey/survey' import * as Category from '@core/survey/category' // ===== SURVEY export const getNodeDef = (survey) => R.pipe(ActivityLog.getContentUuid, (nodeDefUuid) => Survey.getNodeDefByUuid(nodeDefUuid)(survey)) // ===== CATEGORY export const getItemCategory = ActivityLog.getCategory export const isItemCategoryDeleted = () => R.pipe(ActivityLog.getCategory, R.isNil) export const isCategoryDeleted = isItemCategoryDeleted // ==== CATEGORY, LEVELS export const isLevelDeleted = ({ category, levelUuid }) => A.isEmpty(category) || !Category.getLevelByUuid(levelUuid)(category) // ===== TAXONOMY export const { getTaxonomy } = ActivityLog export const isTaxonomyDeleted = () => A.pipe(ActivityLog.getTaxonomy, R.isNil) 'use strict'; const { clone, Empty, merge, prototype, statics } = require('./Util.js'); const metaSym = Symbol('configMeta'); const initSym = Symbol('configInit'); const openSym = Symbol('configOpen'); const valuesSym = Symbol('configValues'); @statics({ all: new Empty(), symbols: { meta: metaSym, init: initSym, open: openSym, values: valuesSym } }) @prototype({ isConfig: true, owner: null, cached: false, initial: false, initialValue: null, lazy: false }) class Config { constructor (name) { this.$ = this; this.name = name; this.changer = name + 'Change'; this.updater = name + 'Update'; } static addMeta (descriptor, metaName, metaValue) { let value = descriptor.initializer(); let cm = value && value[metaSym]; if (!cm) { value = { [metaSym]: cm = {}, value: value }; } cm[metaName] = metaValue; descriptor.initializer = () => value; } static get (name) { let all = Config.all; return all[name] || (all[name] = new Config(name)); } define (target, init) { let def = init ? (this.initDef || this.getInitDef()) : (this.def || this.getDef()); Object.defineProperty(target, this.name, def); } extend (options, owner = null) { let cfg = this; if (!owner || owner !== cfg.owner) { cfg = Object.create(cfg); cfg.owner = owner; } Object.assign(cfg, options); return cfg; } merge (value, newValue, target = null, mixinMeta = null) { if (mixinMeta) { return value; //UNC } if (newValue && newValue.constructor === Object) { if (value && value.constructor === Object) { newValue = merge(clone(value), newValue); } } return newValue; } getDef () { return this.def || this.$.createDef(); } getInitDef () { return this.initDef || this.$.createInitDef(); } //-------------------------------------------------------- // Private createDef () { let cfg = this; let name = cfg.name; let changer = cfg.changer; let updater = cfg.updater; return cfg.def = { get () { return this[valuesSym][name]; }, set (val) { let me = this; let values = me[valuesSym]; if (!me[changer] || (val = me[changer](val, values[name])) !== undefined) { let old = values[name]; if (old !== val) { values[name] = val; if (me[updater]) { me[updater](val, old); } } } } }; } createInitDef () { const name = this.name; return this.initDef = { configurable: true, get () { delete this[name]; // remove the initDef property definition // Now that our init def is removed, the following assignment will run // the normal def's set() method. this[name] = this[initSym][name]; // std setter return this[name]; // std getter }, set (v) { delete this[name]; // remove the initDef property definition this[name] = v; // std setter } } } } module.exports = Config; 'use strict'; (function () { function poiModel(modelUtils, cityService) { // EventModel constructor function POIModel(data) { this.id = data.id || null; this.lang = data.lang || 'en-GB'; this.created = data.created || null; this.url = [data.base, data.id].join('/'); this.transformDescription(data.description || []); this.transformTitle(data.label || []); this.transformLocation(data.location || {}); this.transformStatus(data.time || []); } // behaviour of POIModel POIModel.prototype.transformDescription = function (data) { var self = this; // clear description; this.description = ''; this.secondaryDescription = ''; data.forEach(function (descriptionObj) { if (descriptionObj.type) self.secondaryDescription += descriptionObj.value; else self.description += descriptionObj.value; }); }; POIModel.prototype.transformTitle = function (data) { this.title = modelUtils.getDataByCondition(data, {term: 'primary'}); }; POIModel.prototype.transformLocation = function (data) { // get default point by condition term = entrance var selectedPoint = modelUtils.getDataByCondition(data.point, {term: 'entrance'}, true); var point = (selectedPoint && selectedPoint.Point) ? (selectedPoint.Point.posList || '').trim().split(' ') : []; this.location = { coords: { latitude: point[0], longitude: point[1] } } }; POIModel.prototype.transformStatus = function (time) { this.status = (!time || !time.length) ? 'closed' : time[0].term; }; return cityService.targetPOIResource({ query: { method: 'GET', isArray: true, transformResponse: function (data, header) { var wrapped = angular.fromJson(data); var result = []; if(!wrapped) return result; wrapped = (wrapped && wrapped.poi) ? wrapped.poi : [wrapped]; wrapped.forEach(function (item) { if (!item.id) return; result.push(new POIModel(item)); }); return result; } } }); } poiModel.$inject = ['modelUtils', 'cityService']; angular.module("event") .factory('poi.model', poiModel); })(); const bcrypt = require('bcrypt'); // // exports.seed = async function seed(knex) { // const hashedPass = await bcrypt.hash('secret', 5); // await knex('users').insert({ // name: 'admin admin', // email: '', // password: , // created_at: new Date(), // updated_at: new Date(), // email_verified_at: new Date(), // }); // }; 1-10 const Command = require("../../util/Command.js"); const { RichEmbed } = require("discord.js"); const { stripIndents } = require("common-tags"); class Mute extends Command { constructor(client) { super(client, { name: "mute", description: "Mutes the mentioned user.", category: "Moderation", usage: "mute <@user> ", aliases: ["permmute", "perm"], permLevel:"Moderator", guildOnly: true }); } async run(message, args, level) { if (!message.guild.available) return this.client.logger.info(`Guild "${message.guild.name}" (${message.guild.id}) is unavailable.`); if (!message.guild.me.hasPermission("MANAGE_ROLES")) { const embed = new RichEmbed().setColor(0x00FFFF).setAuthor("❌ Error").setDescription("I cannot create a \"Muted\" role, make sure I have the proper permissions!"); return message.channel.send({embed}); } const muteRole = message.guild.roles.find(role => role.name === "Muted"); const empty = await this.isEmpty(muteRole); if (empty) { const roleRequest = await this.client.awaitReply(message, "A \"**Muted**\" role does not exist on this server. Would you like me to create one? (__Y__es / __N__o)", 30000); if (roleRequest.toLowerCase() === "y" || roleRequest.toLowerCase() === "yes") { message.guild.createRole({ name: "Muted" }) .then(role => message.channel.send(`✅ Created new role: **${role.name}**.`)) .catch(err => { this.client.logger.error(err.stack); return this.client.embed("", message); }); } else { return message.channel.send("Cancelled. I will not create a \"Muted\" role. You will not be able to mute users without having a \"Muted\" role."); } } const user = message.mentions.users.first(); let reason = args.slice(1).join(" "); if (!user) return message.channel.send("You must mention a user to mute."); if (user === message.author) return message.channel.send("You cannot mute yourself. 🤔"); if (user.id === process.env.OWNER) return message.channel.send("I cannot mute my master."); if (message.guild.member(message.author).highestRole.position <= message.guild.member(user).highestRole.position) return message.channel.send("You cannot mute this user as they have a higher role than you."); if (!empty) { if (message.guild.member(user).roles.has(muteRole.id)) return message.channel.send("The mentioned user is already muted."); if (!reason) { message.channel.send("Please enter a reason for the mute...\nThis text-entry period will time-out in 60 seconds. Reply with `cancel` to exit."); await message.channel.awaitMessages(m => m.author.id === message.author.id, { "errors": ["time"], "max": 1, time: 60000 }).then(resp => { if (!resp) return message.channel.send("Timed out. The user has not been muted."); resp = resp.array()[0]; if (resp.content.toLowerCase() === "cancel") return message.channel.send("Cancelled. The user has not been muted."); reason = resp.content; if (resp) resp.react("✅"); }).catch(() => { message.channel.send("Timed out. The user has not been muted."); }); } message.guild.channels.forEach(async (channel) => { await channel.overwritePermissions(muteRole, { SEND_MESSAGES: false, SPEAK: false }).catch(err => { this.client.logger.error(err.stack); return this.client.embed("", message); }); }); message.guild.member(user).addRole(muteRole.id) .then(member => message.channel.send(`**${member.user.tag}** was successfully muted.`)) .catch(err => { this.client.logger.error(err.stack); return this.client.embed("", message); }); try { const embed = new RichEmbed() .setTitle(`🔇 Member muted in #${message.channel.name}`) .setColor(16772735) .setDescription(stripIndents` \`\`\`css Target: ${user.tag} (${user.id}) Issued by: ${message.author.tag} (${message.author.id}) Reason: ${reason} \`\`\` `) .setFooter("Moderation system powered by Amaterasu", this.client.user.displayAvatarURL) .setTimestamp(); user.send(stripIndents` You were muted by staff in the **${message.guild.name}** server for the reason "${reason}". Please ensure you follow all the rules of the server in the future to avoid this occurring again.`); } catch (err) { this.client.logger.error(err.stack); return this.client.embed("", message); } } } async isEmpty(obj) { for (const key in obj) { if (obj.hasOwnProperty(key)) return false; } return true; } } module.exports = Mute;ChallengeProject/coderlane/src/app/actions/index.js import { createAction } from 'redux-actions'; import axios from 'axios'; export const userMenuOpen = createAction('USER_MENU_OPEN'); // 切换用户菜单 export const snippetOpen = createAction('SNIPPET_OPEN'); // 切换语言选择窗口 export const sandboxOpen = createAction('SANDBOX_OPEN'); export const socketConnect = createAction('SOCKET_CONNECT'); // socket连接状态 true在线, false离线 export const updateApp = createAction('UPDATE_APP'); // 更新app某一个值 export const updateToken = createAction('UPDATE_TOKEN'); // 更新视频token export const settingUpdate = createAction('SETTING_UPDATE'); // 更新单个配置 export const settingUpdateAll = createAction('SETTING_UPDATE_ALL'); // 更新整个配置, 用于ssr export const updateLang = createAction('UPDATE_LANG'); // 更新当前语言 export const runStatus = createAction('RUN_STATUS'); // 更新运行状态 export const updateSandbox = createAction('UPDATE_SANDBOX'); // 更新sandbox某一个值 {key:value} export const updateSandboxAll = createAction('UPDATE_SANDBOX_ALL'); // 一次更新所有redux export const openLive = createAction('OPEN_LIVE'); // 开始live export const createSandboxAction = params => { return dispatch => { axios.post('/api/sandbox', params).then(({ data }) => { if (!params._id && !data.code) { window.location.href = `/sandbox/${data._id}`; } }).catch(e => { console.log('e > ', e); }) } } export const getToken = params => { return dispatch => { axios.post('/api/token', params).then(({ data }) => { dispatch(updateToken(data.token)); }).catch(e => { console.log('e > ', e); }) } }ziransun/wpt test(function() { var desc1 = Object.getOwnPropertyDescriptor(new Event("x"), "isTrusted"); assert_not_equals(desc1, undefined); assert_equals(typeof desc1.get, "function"); var desc2 = Object.getOwnPropertyDescriptor(new Event("x"), "isTrusted"); assert_not_equals(desc2, undefined); assert_equals(typeof desc2.get, "function"); assert_equals(desc1.get, desc2.get); }); module.exports = `/* ────────╔╗─── ───────────╔═╗───────── ╔═╦╗╔═╗╔╝║╔═╗ ╔══╗╔═╗─╔╦╗║╬║╔╦╗╔═╗╔═╗ ║║║║║╬║║╬║║╩╣ ║║║║║╬╚╗║╔╝╚╗║║║║║╩╣║╩╣ ╚╩═╝╚═╝╚═╝╚═╝ ╚╩╩╝╚══╝╚╝──╚╝╚═╝╚═╝╚═╝ GitHub Repository: https://github.com/antonbobrov/node-marquee Powered by | https://github.com/antonbobrov */`; 0 import { DrawingUtils } from './drawing_utils.js' import { Geometry } from './geometry.js' var DrawingNote DrawingNote = class DrawingNote { constructor (options) { this.options = options this.path = DrawingUtils.create_element(this.options.parent, 'path') DrawingUtils.style(this.options.parent, 'stroke', this.options.color) DrawingUtils.style(this.options.parent, 'fill', this.options.color) DrawingUtils.style(this.options.parent, 'stroke-width', (this.options.size / 2) + 'px') DrawingUtils.style(this.options.parent, 'stroke-linecap', 'round') DrawingUtils.style(this.path, 'fill-opacity', 0.1) } update (from, to) { var _from, _to, foldLength, foldPct, len, pathD, wid this.from = from this.to = to if (this.bigEnough()) { this.options.parent.setAttribute('opacity', 1) _from = [Math.min(this.from[0], this.to[0]), Math.min(this.from[1], this.to[1])] _to = [Math.max(this.from[0], this.to[0]), Math.max(this.from[1], this.to[1])]; [len, wid] = [_to[0] - _from[0], _to[1] - _from[1]] foldPct = 0.25 foldLength = Math.min(foldPct * len, foldPct * wid) pathD = `M0,0 L${len},${0} L${len},${wid - foldLength} L${len - foldLength},${wid} L0,${wid} L0,0 M${len},${wid - foldLength} L${len - foldLength},${wid - foldLength} L${len - foldLength},${wid}` this.path.setAttribute('d', pathD) return DrawingUtils.apply_matrix(this.path, Geometry.translation_matrix(_from)) } else { return this.options.parent.setAttribute('opacity', 0) } } size () { if (this.from == null) { return 0 } if (this.to == null) { return 0 } return Geometry.distance(this.from, this.to) } bigEnough () { return this.size() > 8 } end (callback) { if (this.options.promptText != null) { this.options.promptText('', (input) => { if (input !== '') { return this.options.parent.setAttribute('data-sharinpix-note-text', input) } }) } return callback() } } DrawingNote.type = 'note' export { DrawingNote } 0 const $=require('jquery') $( ".ajax-form" ).validate( { rules: { name: { required: true, minlength: 2 }, email: { required: true, email: true }, message: { required: true, minlength: 5 } }, errorPlacement: function ( error, element ) {}, submitHandler: function ( form ) { $.ajax( { dataType: "jsonp", url: "http://getsimpleform.com/messages/ajax?form_api_token=", data: $( ".ajax-form" ).serialize() } ).done( function () { //callback which can be used to show a thank you message //and reset the form $( ".ajax-form" ).hide(); $( ".form-thank-you" ).fadeIn( "400" ); } ); return false; //to stop the form from submitting } } ); avalonmediasystem/react-structural-metadata-editor1-10 "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.reBuildSMUI = reBuildSMUI; exports.buildSMUI = buildSMUI; exports.deleteItem = deleteItem; exports.addDropTargets = addDropTargets; exports.removeDropTargets = removeDropTargets; exports.setActiveDragSource = setActiveDragSource; exports.removeActiveDragSources = removeActiveDragSources; exports.handleListItemDrop = handleListItemDrop; exports.handleItemDrop = handleItemDrop; exports.saveInitialStructure = saveInitialStructure; var types = _interopRequireWildcard(require("./types")); var _forms = require("./forms"); function reBuildSMUI(items, duration) { return function (dispatch, getState) { dispatch(buildSMUI(items, duration)); var _getState = getState(), structuralMetadata = _getState.structuralMetadata; // Remove invalid structure alert when data is corrected if (structuralMetadata.smDataIsValid) { dispatch((0, _forms.clearExistingAlerts)()); } dispatch((0, _forms.updateStructureStatus)(0)); }; } function buildSMUI(json, duration) { return { type: types.BUILD_SM_UI, json: json, duration: duration }; } function deleteItem(id) { return { type: types.DELETE_ITEM, id: id }; } function addDropTargets(item) { return { type: types.ADD_DROP_TARGETS, payload: item }; } function removeDropTargets() { return { type: types.REMOVE_DROP_TARGETS }; } function setActiveDragSource(id) { return { type: types.SET_ACTIVE_DRAG_SOURCE, id: id }; } function removeActiveDragSources() { return { type: types.REMOVE_ACTIVE_DRAG_SOURCES }; } function handleListItemDrop(dragSource, dropTarget) { return function (dispatch) { dispatch(handleItemDrop(dragSource, dropTarget)); dispatch((0, _forms.updateStructureStatus)(0)); }; } function handleItemDrop(dragSource, dropTarget) { return { type: types.HANDLE_LIST_ITEM_DROP, dragSource: dragSource, dropTarget: dropTarget }; } function saveInitialStructure(initData) { return { type: types.SAVE_INIT_SMDATA, payload: initData }; }lib/snippet.js 'use strict'; // require('time-require'); var path = require('path'); var relative = require('relative'); var define = require('define-property'); var extend = require('extend-shallow'); var utils = require('./utils'); /** * Create a new `Snippet`, optionally passing a `file` object * to start with. * * @param {Object} `file` * @api public */ function Snippet(file) { if (!(this instanceof Snippet)) { return new Snippet(file); } if (typeof file === 'string') { file = {path: file}; } this.history = []; if (typeof file === 'object') { this.visit('set', file); } this.cwd = this.cwd || process.cwd(); this.content = this.content || null; this.options = this.options || {}; } /** * Snippet prototype methods */ Snippet.prototype = { constructor: Snippet, /** * Set or get an option on the snippet. Dot notation may be used. * * @name .option * @param {String} `prop` The property to get. * @api public */ option: function (prop, val) { if (arguments.length === 1) { if (typeof prop === 'string') { return utils.get(this.options, prop); } if (typeof prop === 'object') { return this.visit('option', prop); } } utils.set(this.options, prop, val); return this; }, /** * Set a property on the snippet. Dot notation may be used. * * @name .set * @param {String} `prop` The property to set. * @api public */ set: function (prop, val) { if (typeof prop === 'object') { return this.visit('set', prop); } utils.set(this, prop, val); return this; }, /** * Get a property from the snippet. Dot notation may be used. * * @name .get * @param {String} `prop` The property to get. * @api public */ get: function (prop) { return utils.get(this, prop); }, /** * Read a utf8 string from the file system, or return if * `content` is already a string. * * @name .read * @param {String} `fp` Filepath * @api public */ read: function (fp) { if (this.content) return this; fp = path.resolve(this.cwd, fp || this.path); this.content = utils.tryRead(fp); return this; }, /** * Attempts to return a snippet object from the given `value`. * * @name .toSnippet * @param {String|Object} `val` Can be a filepath, content string, object or instance of `Snippet`. * @param {Object} `opts` * @api public */ toSnippet: function (val, opts) { if (typeof val === 'function') { return new Snippet(val(this)); } if (typeof val === 'string') { var str = utils.tryRead(val); var res = {content: null, options: opts || {}}; if (str) { res.path = val; res.content = str.toString(); } else { res.content = val; } return new Snippet(res); } if (val instanceof Snippet) { val.option(opts); return val; } if (typeof val === 'object') { val.options = extend({}, val.options, opts); return new Snippet(val); } }, /** * Prepend the snippet's contents to the given `string`. * * @name .prepend * @param {String} `str` * @param {Object} `opts` * @api public */ prepend: function (str, opts) { var snippet = this.toSnippet(str, opts); utils.prepend(this, snippet); return this; }, /** * Append the snippet's contents to the given `string`. * * @name .append * @param {String} `str` * @param {Object} `opts` * @api public */ append: function (str, opts) { var snippet = this.toSnippet(str, opts); return utils.append(this, snippet); }, /** * Inject the snippet's contents into the given `string` at the * defined point of insertion (``) * * @name .inject * @param {String} `str` * @param {Object} `opts` * @api public */ inject: function (str, opts) { opts = extend({marker: 'snippet', action: 'add'}, opts); opts = extend({}, this.options, opts); var snippet = this.toSnippet(str, opts); return utils.inject(this, snippet, opts); }, /** * Calculate the destination path based on the given function or `filepath`. * * @name .dest * @param {String|Function} `fp` * @return {String} Returns the destination path. * @api public */ dest: function (fp, options) { if (typeof fp === 'function') { return fp.call(this, this.path); } var opts = extend({}, this.options, options); if (typeof fp === 'object') { opts = extend({}, opts, fp); } if (typeof fp === 'string' && ~fp.indexOf(':')) { fp = fp.replace(/:(\w+)/g, function (m, prop) { return opts[prop] || this[prop] || m; }.bind(this)); } this.path = this.path || fp; var base = opts.base || this.base || path.dirname(fp); var name = opts.basename || this.relative || this.basename; var ext = opts.ext || this.extname || path.extname(fp); if (typeof fp === 'string' && fp[fp.length - 1] === '/') { base = fp; } var dest = path.join(base, utils.rewrite(name, ext)); if (dest.slice(-1) === '.') { dest = dest.slice(0, dest.length - 1) + ext; } return dest; }, /** * Asynchronously write the snippet to disk. * * @name .write * @param {String} `fp` Destination filepath. * @param {Function} `cb` Callback function * @returns {Object} Returns the instance for chaining. * @api public */ write: function (fp, opts, cb) { if (typeof fp !== 'string') { cb = opts; opts = fp; fp = null; } if (typeof opts === 'function') { cb = opts; opts = {}; } if (typeof cb !== 'function') { throw new Error('expected a callback function.'); } var dest = this.dest(fp || this.path, opts); var file = { contents: this.content, path: dest }; opts = extend({ ask: true }, this.options, opts); utils.detect(file, opts, function (err) { if (file.contents) { utils.write(dest, file.contents, cb); } else { this.copy(dest, cb); } return this; }.bind(this)); return this; }, /** * Write the item to disk synchronously. * * @name .writeSync * @param {String} `fp` Destination filepath. * @return {Object} Returns the instance for chaining. * @api public */ writeSync: function (fp, opts) { var dest = path.resolve(this.dest(fp || this.path, opts)); var file = { contents: this.content, path: dest }; opts = extend({ ask: true, silent: false }, this.options, opts); utils.detect(file, opts, function (err) { if (file.contents) { utils.writeSync(dest, file.contents); utils.success('file written to', utils.bold(dest)); } else { utils.copy.sync(this.path, dest); utils.success('file copied to', utils.bold(dest)); } }); return this; }, /** * Copy snippet from its defined `path` to the given `dest`. * * @name .copy * @param {String} `dest` * @param {Function} `cb` * @api public */ copy: function (dest, cb) { utils.copy(this.path, dest, this.options, cb); return this; }, mixin: function (key, val) { Snippet.prototype[key] = val; return this; }, visit: function (method, val) { utils.visit(this, method, val); return this; } }; Object.defineProperty(Snippet.prototype, 'content', { get: function() { return this._content; }, set: function(val) { if (Buffer.isBuffer(val)) { val = val.toString(); } define(this, '_content', val); } }); Object.defineProperty(Snippet.prototype, 'path', { get: function() { return this.history[this.history.length - 1]; }, set: function(fp) { if (typeof fp !== 'string') { throw new Error('`snippet.path` must be a string.'); } if (fp && fp !== this.path) { this.history.push(fp); } } }); Object.defineProperty(Snippet.prototype, 'name', { get: function() { return this._name; }, set: function(name) { if (name && typeof name !== 'string') { throw new Error('`snippet.name` must be a string.'); } name = name || path.basename(this.path, path.extname(this.path)); define(this, '_name', name); } }); Object.defineProperty(Snippet.prototype, 'cwd', { get: function() { return path.resolve(this._cwd || process.cwd()); }, set: function(cwd) { define(this, '_cwd', cwd || process.cwd()); } }); Object.defineProperty(Snippet.prototype, 'relative', { get: function() { if (!this.base) {return null; } if (!this.path) { throw new Error('`snippet.path` must be defined to get relative path.'); } return relative(this.base, this.path); }, set: function() { throw new Error('file.relative is read-only and cannot be overridden.'); } }); Object.defineProperty(Snippet.prototype, 'absolute', { get: function() { if (!this.path) { throw new Error('`snippet.path` must be defined to get absolute path.'); } return path.resolve(this.base, this.path); }, set: function() { throw new Error('file.absolute is read-only and cannot be overridden.'); } }); Object.defineProperty(Snippet.prototype, 'dirname', { get: function() { if (!this.path) { throw new Error('`snippet.path` must be defined to get dirname.'); } return path.dirname(this.path); }, set: function(dirname) { if (!this.path) { throw new Error('`snippet.path` must be defined to set dirname.'); } this.path = path.join(dirname, path.basename(this.path)); } }); Object.defineProperty(Snippet.prototype, 'basename', { get: function() { if (!this.path) { throw new Error('`snippet.path` must be defined to get basename.'); } return path.basename(this.path); }, set: function(basename) { if (!this.path) { throw new Error('`snippet.path` must be defined to set basename.'); } this.path = path.join(path.dirname(this.path), basename); } }); Object.defineProperty(Snippet.prototype, 'extname', { get: function() { if (!this.path) { throw new Error('`snippet.path` must be defined to get extname.'); } return path.extname(this.path); }, set: function(extname) { if (!this.path) { throw new Error('`snippet.path` must be defined to set extname.'); } var ext = extname || this._extname || (this._extname = path.extname(this.path)); this.path = utils.rewrite(this.path, ext); } }); /** * Expose `Snippet` */ module.exports = Snippet; src/assets/js/app-form-validation.js $(document).ready(function() { // Set default jQuery.validate settings $.validator.setDefaults({ highlight: function(element) { $(element).closest('.form-group').addClass('has-error'); }, unhighlight: function(element) { $(element).closest('.form-group').removeClass('has-error'); }, errorContainer: $('#errorContainer'), errorLabelContainer: $('#errorContainer ul'), wrapper: 'li' }); // Validate 1.0 Login $('#login-form').validate({ rules: { userID : "required", userPassword: "" }, messages: { userID : "Enter your UserID", userPassword: "" } }); // Validate 3.0 Forgot Password $('#forgot-password').validate({ rules: { userID : "required", userEmail : { required: true, email:true }, }, messages: { userID : "Enter your UserID", userEmail : { required: "Your Email Address is required", } } }); // Validate 4.0 Expired Password $('#expired-password').validate({ rules: { userID : "required", oldPassword : "", newPassword : "", newPasswordConfirm: { required: true, equalTo: " } }, messages: { userID : "Enter your UserID", oldPassword : "", newPassword : "", newPasswordConfirm : { required: "Confirm new password is required", equalTo: "Must be same as New Password" } } }); // Validate 5.0 MFA Question Setup $('#mfa-question-setup').validate({ rules: { chQuestionA : "required", chResponseA: "required", chQuestionB : "required", chResponseB: "required", chQuestionC : "required", chResponseC: "required", preferredEmail : { required: true, email:true }, preferredEmailConfirm: { required: true, email:true, equalTo: "#preferredEmail" } }, messages: { chQuestionA : "Select a Question for Question A", chResponseA : "Type a Response for Question A", chQuestionB : "Select a Question for Question B", chResponseB : "Type a Response for Question B", chQuestionC : "Select a Question for Question C", chResponseC : "Type a Response for Question C", preferredEmail : "Your Email Address is required", preferredEmailConfirm: { required: "Confirm Email Address is required", equalTo: "Must be same as email entered" } } }); // Validate 6.0 Dealership Selection $('#dealership-selection').validate({ rules: { dealership : "required", }, messages: { userID : "Please Select Dealership", } }); // Validate 8.0 Challenge Question $('#challenge-question').validate({ rules: { chQuestion : "required", chResponse : "required" }, messages: { chQuestion : "Plese select a Question to Answer", chResponse : "Please provide and answer to Challenge Question Selected" } }); // Validate 8.2 Request Token Input $('#token-submit, #invalid-token').validate({ rules: { tokenCode : "required" }, messages: { tokenCode : "Plese enter Token Code" } }); // end document ready });"use strict"; module.exports = { up: async (queryInterface) => { return queryInterface.bulkInsert("Roles", [ { id:10000, name: "user", createdAt: new Date(), updatedAt: new Date(), }, { id:10001, name: "admin", createdAt: new Date(), updatedAt: new Date(), } ]); }, down: async (queryInterface) => { return queryInterface.bulkDelete("Roles", null, {}); }, };// TODO: Limit the calls rate /*****************************************************************************/ /* Server Methods */ /*****************************************************************************/ Meteor.methods({ 'server/postEntry': function (doc) { this.unblock(); GuestbookEntriesFormSchema.validate(doc); const user = Meteor.users.findOne({ _id: this.userId }); if (!user.services.twitter) { throw new Meteor.Error(401, `You can't post if you are not authenticated with Twitter.`, `Can't post if not authenticated`); } const username = `@${user.services.twitter.screenName}`; const userAlreadyPosted = GuestbookEntries.findOne({ author: username }) !== undefined; if (userAlreadyPosted) { throw new Meteor.Error(403, `You can't post an entry twice. If you're having a problem, please contact us through our Twitter.`, `Can't post twice`); } doc.author = username; const entriesCount = GuestbookEntries.find().count() + 1; doc.number = entriesCount; doc.answer = ''; doc.date = Date.now(); doc.approved = false; // TODO: check // check(doc, GuestbookEntries.simpleSchema()); GuestbookEntries.insert(doc); }, 'server/approveEntry': function (entryId) { this.unblock(); check(entryId, String); const user = Meteor.users.findOne({ _id: this.userId }); if (!Roles.userIsInRole(user, ['admin'])) { throw new Meteor.Error(401, `You can't approve an entry if you're not an admin.`, `Can't approve if not admin`); } GuestbookEntries.update({ _id : entryId }, { $set: { approved: true } }); }, 'server/registerDownload': function (type) { this.unblock(); check(type, String); if (!Downloads.findOne({ type: type })) { const doc = { type: type, count: 1 }; check(doc, DownloadsSchema); Downloads.insert(doc); } else { Downloads.update({ type: type }, { $inc: { count: 1 } }); } }, 'server/registerItemSetDownload': function (buildId) { this.unblock(); check(buildId, String); if (!ItemSetDownloads.findOne({ buildId: buildId })) { const doc = { buildId: buildId, count: 1 }; check(doc, ItemSetDownloadsSchema); ItemSetDownloads.insert(doc); } else { ItemSetDownloads.update({ buildId: buildId }, { $inc: { count: 1 } }); } Meteor.call('server/registerDownload', 'set-from-website'); }, 'server/getConfig': function (configName) { this.unblock(); check(configName, String); const result = Config.findOne({ id: configName, location: { $in: ['both', 'client'] } }); if (!result) { throw new Meteor.Error(404, 'Config not found.', 'Not found.'); } return result; }, 'server/rateCustomItemSet': function (buildId, rating) { this.unblock(); check(buildId, String); check(rating, Number); check(this.userId, String); if (rating < 0 || rating > 5) { throw new Meteor.Error(422, `Rating exceeded allowed range.`, `Invalid parameter`); } const customBuild = CustomItemSets.findOne(new Meteor.Collection.ObjectID(buildId)); if (!customBuild) { throw new Meteor.Error(404, 'Custom build not found.', 'Not found.'); } else { const updatedRatings = lodash.reject(customBuild.ratings || [], r => r.userId === this.userId); const ratings = [...updatedRatings, { rating: Math.floor(rating), userId: this.userId }]; const ratingsCount = ratings.length; const totalRating = ratings.reduce((total, current) => total + (current.rating || 0), 0) / ratingsCount; CustomItemSets.update(new Meteor.Collection.ObjectID(buildId), { $set: { ratingsCount: ratingsCount, totalRating: totalRating, ratings: ratings } }); } } }); "use strict"; // see http://eslint.org/docs/rules/#variables // The ESLint browser environment defines all browser globals as valid, // even though most people don't know some of them exist (e.g. `name` or `status`). // This is dangerous as it hides accidentally undefined variables. // We blacklist the globals that we deem potentially confusing. // To use them, explicitly reference them, e.g. `window.name` or `window.status`. const restrictedGlobals = require("confusing-browser-globals"); module.exports = { // Enforce or disallow variable initializations at definition // Situations are different "init-declarations": "off", // Disallow deletion of variables "no-delete-var": "error", // Disallow labels that share a name with a variable "no-label-var": "error", // Restrict usage of specified global variables "no-restricted-globals": ["error", ...restrictedGlobals], // Disallow declaration of variables already declared in the outer scope "no-shadow": [ "error", { builtinGlobals: false, allow: ["callback", "cb", "done", "next", "resolve", "reject"], }, ], // Disallow shadowing of names such as arguments "no-shadow-restricted-names": "error", // Disallow use of undeclared variables unless mentioned in a /*global */ block "no-undef": [ "error", { typeof: true, }, ], // Disallow use of undefined when initializing variables "no-undef-init": "error", // Disallow use of undefined variable // Preferable to use "unicorn/no-useless-undefined" "no-undefined": "off", // Disallow declaration of variables that are not used in the code "no-unused-vars": [ "error", { vars: "all", varsIgnorePattern: "^_", args: "after-used", argsIgnorePattern: "^_", caughtErrors: "all", caughtErrorsIgnorePattern: "^_", ignoreRestSiblings: true, }, ], // Disallow use of variables before they are defined "no-use-before-define": [ "error", { functions: true, classes: true, variables: true }, ], }; 1-10 import { Link } from "gatsby" import styled from "styled-components" export const StyledLink = styled(Link)` text-decoration: none; color: inherit; cursor: pointer; transition: all 0.3s ease-out; ` Darkwolf/node-telegram-bot const types = require('./') class Keyboard { constructor(rows) { this.setRows(rows) } setRows(rows) { this.rows = rows ? Keyboard.normalize(rows).map(row => row.map(button => button instanceof types.KeyboardButton ? button : new types.KeyboardButton(button.text, button) )) : [] return this } addRow(...rows) { this.rows = [ ...this.rows, ...Keyboard.normalize(rows).map(row => row.map(button => button instanceof types.KeyboardButton ? button : new types.KeyboardButton(button.text, button) )) ] return this } addButton(...buttons) { return this.addRow(buttons) } clear() { this.rows = [] return this } toParams() { return this.rows ? this.rows.map(row => row.map(button => button.toParams())) : [] } } Keyboard.normalize = keyboard => { const rows = [] keyboard.forEach(row => { if (Array.isArray(row) && row.length) { const buttons = row.filter(button => button) if (buttons.length) { rows.push(buttons) } } }) return rows } Keyboard.from = rows => new Keyboard(rows) module.exports = Keyboard "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var nserializer_1 = require("./nserializer"); exports.nSerializer = nserializer_1.default; //# sourceMappingURL=index.js.map// const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const TerserPlugin = require('terser-webpack-plugin'); module.exports = { entry: "./src/main.ts", output: { filename: "./tty2web-bundle.js" }, devtool: "source-map", resolve: { extensions: [".ts", ".tsx", ".js"], }, module: { rules: [ { test: /\.tsx?$/, loader: "ts-loader", exclude: /node_modules/ }, { test: /\.js$/, include: /node_modules/, loader: 'license-loader' }, { loader: 'babel-loader', test: /\.js$/, exclude: /node_modules/, } ] }, optimization: { minimize: true, minimizer: [ new TerserPlugin({ terserOptions: { ecma: 6, compress: true, output: { comments: false, beautify: false } } }) ] } }; Mahjoub-Adam/BIdderMaster const router=require('express').Router(); let User=require('../models/user.model'); const bcrypt=require('bcryptjs'); const config=require('../config'); const jwt=require('jsonwebtoken'); const auth=require('../middleware/auth'); router.route('/login').post((req,res)=>{ const username=req.body.username; const password=req.body.password; const query={username:req.body.username}; User.findOne(query).exec(function(err,user){ if(err) return res.status(400).json('Error:'+err) if(!user) return res.status(400).json('Username not found!'); bcrypt.compare(password,user.password) .then(bool=>{ if(!bool) return res.status(400).json('Wrong password!'); jwt.sign({id:user.id,},config.jwtSecret,(err,token)=>{ if(err) return res.status(400).json('Error:'+err); const listed=user.listed; const rating=user.rating; res.json({token,username,listed,rating}); }); }) .catch(err=>res.status(400).json('Error:'+err)); }); }); router.route('/signup').post((req,res)=>{ const username=req.body.username; const password=req.body.password; const name=req.body.name; const surname=req.body.surname; const email=req.body.email; const address=req.body.address; const PhoneNumber=Number(req.body.PhoneNumber); const AFM=req.body.AFM; const query={username:req.body.username}; const listed=false; const rating="Not Rated"; const number_of_ratings=0; const country=req.body.country; User.findOne(query).exec(function(err,user){ if(err) return res.status(400).json('Error:'+err); if(user) return res.status(400).json('Username already in use'); const query={email:req.body.email}; User.findOne(query).exec(function(err,user){ if(err) return res.status(400).json('Error:'+err) if(user) return res.status(400).json('Email already in use'); const newUser=new User({username,password,name,surname,email,PhoneNumber,address,AFM,listed,rating,number_of_ratings,country}); bcrypt.genSalt(10,(err,salt)=>{ if(err) return res.status(400).json('Error:'+err); bcrypt.hash(newUser.password,salt,(err,hash)=>{ if(err) return res.status(400).json('Error:'+err); newUser.password=; newUser.save() .then(user=> { jwt.sign({id:user.id,},config.jwtSecret,{expiresIn:3600},(err,token)=>{ if(err) return res.status(400).json('Error:'+err); res.json({rating,token,username,listed}); }); }) .catch(err=>res.status(400).json('Error:'+err)); }); }); }); }); }); router.route('/admin').get(auth,(req,res)=>{ const query={listed:false}; User.findById(req.id) .then(user=>{ if(user.username!=="admin") return res.status(400).json("Token not valid(not admin)!"); User.find(query) .select('-password') .then(users=>res.json(users)) .catch(err=>res.status(400).json('Error:'+err)); }) .catch(err=>res.status(400).json('Error:'+err)); }); router.route('/:id').delete(auth,(req, res) => { User.findById(req.id) .then(user=>{ if(user.username!=="admin") return res.status(400).json("Token not valid(not admin)!") User.findByIdAndDelete(req.params.id) .then(() => res.json('User deleted.')) .catch(err => res.status(400).json('Error: ' + err)); }) .catch(err=>res.status(400).json('Error:'+err)); }); router.route('/update/:id').get(auth,(req, res) => { User.findById(req.id) .then(user=>{ if(user.username!=="admin") return res.status(400).json("Token not valid(not admin)!"); User.findById(req.params.id) .then(user => { user.listed=true; user.save() .then(() => res.json('User updated!')) .catch(err => res.status(400).json('Error: ' + err)); }) .catch(err => res.status(400).json('Error: ' + err)); }) .catch(err=>res.status(400).json('Error:'+err)); }); router.get('/auth', (req, res) => { const token=req.header('x-auth-token'); if(!token) return res.json('Guest!'); try{ const decoded=jwt.verify(token,config.jwtSecret); req.id=decoded.id; } catch(e) { return res.status(400).json('Token not valid!'); } User.findById(req.id) .select('username listed rating') .then(user => { res.json(user) }) .catch(err => res.status(400).json('Error: ' + err)); }); module.exports=router;Vladislav-Boiko/browser-proxy import React, { useState } from 'react'; import cn from 'classnames'; import RequestCard from 'molecules/RequestCard/RequestCard'; import Input from 'atoms/Input/Input'; import Pagination from 'atoms/Pagination/Pagination'; import './RequestsList.css'; import { usePrevious } from 'app/hooks/usePrevious'; // TODO: refactor to Allow list const KEY_SEARCH_BLOCK_LIST = { responseType: 'responseType', }; const filterRequests = (searchRegexp, requests) => { if (!searchRegexp) { return []; } try { return requests.filter((item) => { for (let key of Object.keys(item)) { if (!(key in KEY_SEARCH_BLOCK_LIST) && searchRegexp.test(item[key])) { return true; } } return false; }); } catch (e) { // handled in validation } return []; }; const ITEMS_PER_PAGE = 20; const getPageSlice = (requests, currentPage) => requests ? [...requests].slice( ITEMS_PER_PAGE * (currentPage - 1), ITEMS_PER_PAGE * currentPage, ) : []; const RequestsList = ({ className, onSelect, onAnalyse, ...otherProps }) => { const requests = otherProps.requests ? [...otherProps.requests] : []; const [searchValue, setSearchValue] = useState(''); const [currentPage, setCurrentPage] = useState(1); let searchRegexp = null; let hasValidSearch = true; try { searchRegexp = new RegExp(searchValue); } catch (e) { hasValidSearch = false; } const sortedRequests = requests.sort( (a, b) => b?.sentTimestamp - a?.sentTimestamp, ); const lastFirstItem = usePrevious( sortedRequests?.length && sortedRequests[0]?.id, ); const currentFirstItem = sortedRequests?.length && sortedRequests[0]?.id; const shallAnimateFirstItem = lastFirstItem !== currentFirstItem; const filteredItems = filterRequests(searchRegexp, sortedRequests); const totalPages = Math.ceil( filteredItems?.length ? filteredItems?.length / ITEMS_PER_PAGE : 0, ); const displayedPage = Math.min(totalPages, Math.max(0, currentPage)); return (

      Requests

      Select a request to override

      setSearchValue(newValue)} validate={() => (!hasValidSearch ? 'Is not a valid regexp' : null)} /> {/* */}
      {requests && getPageSlice(filteredItems, displayedPage) .map((request, id) => (request.id ? request : { ...request, id })) .map((request) => ( onAnalyse(request)} searchRegexp={searchRegexp} shallAnimate={ shallAnimateFirstItem && request.id === currentFirstItem } /> ))}
      ); }; export default RequestsList; #!/usr/bin/env node const program = require("commander"); const { version } = require("../package.json"); const { create, start } = require("../scripts"); program.version(version); program .command("create [projectName]") .description("create a mock server project") .option("-y, --yarn", "use yarn") .action(create); program .command("start [cwd]") .description("start mock server") .option("-o, --open [url]", "open browser in url") .action(start); program .parse(process.argv) /** * Project: "PA IGTI - Controle de Manutenção API com Node.js & MongoDb" * * file: src/routes/routes.js * Description: Responsável pelas rotas do frontend * Data: 17/05/2021 */ import React from 'react'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; // Admin Imports import Dashboard from './pages/admin/dashboard'; import Login from './pages/admin/login'; import WhatsAppClient from './pages/admin/whatsappClient'; import WhatsAppClientInsert from './pages/admin/whatsappClient/whatsappClient.insert'; import WhatsAppClientUpdate from './pages/admin/whatsappClient/whatsappClient.update'; import Users from './pages/admin/users'; import UsersInsert from './pages/admin/users/users.insert'; import UsersUpdate from './pages/admin/users/users.update'; // Client imports import Home from './pages/client/home'; import WhatasppClientDetails from './pages/client/whatsappClient/whatsappClient.details'; // Authorization import PrivateRoute from './services/wAuth'; export default function Routes() { return ( {/* Client Route*/} {/* Admin Route*/} {/* Users Route*/} ); } assets/public/custom_js/datatable.js $(document).ready(function(){ var base_url = $(document).find('#baseurl').val(); function load_demo(index) { index = index || 0; var search = $('#search1').val(); $.post(base_url + "active_friends/" + index, { ajax: true,search:search}, function(data) { // console.log(data); $('#tbody1').html(""); $('.body_blur').hide(); var tr = ''; if(data.data.length>0){ var data1 = data.data; for(var i = 0; i< data1.length; i++){ var cur_index=parseInt(index); var imgg = (data1[i].profile_image==='')?'profile.jpg':data1[i].profile_image; var sl_no=index!=0?(cur_index+(i + 1)):(i + 1); if(data1[i].type=='club_member'){ var st='Become Club Member';}//' style="background:#aae6ab"';} else if(data1[i].type=='normal_customer'){ var st='Member';} //console.log(data1[i].profile_image); tr += ''+ ''+sl_no+''+ ''+data1[i].name+''+ ''+data1[i].mobile+''+ ''+ ''+data1[i].location+''+ ''+st+''+ ''; } $('#tbody1').html(tr); $('#search1').val(data.search); // pagination $('#pagination1').html(data.pagination); }else{ tr += ''+ 'No Data Found'+ ''; $('#tbody1').html(tr);$('#pagination1').parent().parent().hide(); } }, "json"); } //calling the function load_demo(); //pagination update $('#pagination1').on('click', '.page_test a', function(e) { e.preventDefault(); //grab the last paramter from url var link = $(this).attr("href").split(/\//g).pop(); load_demo(link); return false; }); $("#search1").keyup(function(){ load_demo(); }); ///////////////////////////////////////////////////////////// function load_demo2(index) { index = index || 0; var search = $('#search2').val(); $.post(base_url + "refered_friends/" + index, { ajax: true,search:search}, function(data) { //console.log(data); $('#tbody2').html(""); $('.body_blur').hide(); var tr = ''; if(data.data.length>0){ var data1 = data.data; for(var i = 0; i< data1.length; i++){ var cur_index=parseInt(index); var sl_no=index!=0?(cur_index+(i + 1)):(i + 1); tr += ''+ ''+sl_no+''+ ''+data1[i].name+''+ ''+data1[i].mobile+''+ ''+data1[i].location+''+ ''+ ''; } //console.log(tr); $('#tbody2').html(tr); $('#search2').val(data.search); // pagination $('#pagination2').html(data.pagination); }else{ tr += ''+ 'No Data Found'+ ''; $('#tbody2').html(tr);$('#pagination2').parent().parent().hide(); } }, "json"); } //calling the function load_demo2(); //pagination update $('#pagination2').on('click', '.page_test a', function(e) { e.preventDefault(); //grab the last paramter from url var link = $(this).attr("href").split(/\//g).pop(); load_demo2(link); return false; }); $("#search2").keyup(function(){ load_demo2(); }); //////////////////////////////////////////////////////////// function load_demo3(index) { index = index || 0; var search = $('#search3').val(); $.post(base_url + "my_channel_partners/" + index, { ajax: true,search:search}, function(data) { console.log(data); $('#tbody3').html(""); $('.body_blur').hide(); if(data.data.length>0){ var tr = ''; var data1 = data.data; for(var i = 0; i< data1.length; i++){ var cur_index=parseInt(index); var sl_no=index!=0?(cur_index+(i + 1)):(i + 1); if(data1[i].status=='JOINED'){ var st='Joined';}//' style="background:#aae6ab"';} else if(data1[i].status=='REFERED'){ var st='Refered';}//' style="background:#efc3c3"';} else if(data1[i].status=='APPROVED'){ var st='Approved';}//' style="background:blue"';} else if(data1[i].status=='NOT_APPROVED'){ var st='Not Approved';}//' style="background:grey"';} if(data1[i].status=='REFERED'||data1[i].status=='NOT_APPROVED'){ var bt = '  Edit '; }else{ var bt =' View '; } tr += ''+sl_no+''+ ''+data1[i].name+''+ // ''+ ''+data1[i].phone+''+ ''+data1[i].email+''+ ''+data1[i].pan+''+ ''+data1[i].owner_name+''+ ''+st+''+ ''+bt+''; console.log(tr); } //console.log(tr); $('#tbody3').html(tr); $('#search3').val(data.search); // pagination $('#pagination3').html(data.pagination); }else{ tr += ''+ 'No Data Found'+ ''; $('#tbody3').html(tr);$('#pagination3').parent().parent().hide(); } }, "json"); } //calling the function load_demo3(); //pagination update $('#pagination3').on('click', '.page_test a', function(e) { e.preventDefault(); //grab the last paramter from url var link = $(this).attr("href").split(/\//g).pop(); load_demo3(link); return false; }); $("#search3").keyup(function(){ load_demo3(); }); //////////////////////////////////////////////////////////// function load_demo4(index) { index = index || 0; var search = $('#search4').val(); $.post(base_url + "my_club_agents/" + index, { ajax: true,search:search}, function(data) { // console.log(data); $('#tbody4').html(""); $('.body_blur').hide(); if(data.data.length>0){ var tr = ''; var data1 = data.data; for(var i = 0; i< data1.length; i++){ var fileName = data1[i].ca_docs; if(fileName!=null){var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1); }else{var fileExtension = ''; } if((fileName!=null)&&fileExtension=='docx'){ var da=''; }else if((fileName!=null)&&fileExtension=='pdf'){ var da=''; }else{ var da="No Docs"; } var status = (data1[i].status=='approved')?'Active':'Pending'; if(data1[i].status=='approved') { var btn =''; }else{ var btn =' ); }; export default Signup; var Message = require('../message'), Validator_Reply = require('../validator/reply'); var extend = require('../utility/extend'); class Message_Reply extends Message { validateReply(reply) { Validator_Reply.validate(reply); } setTarget(target) { if (this.hasTarget()) { throw new Error('duplicate target'); } return super.setTarget(target); } /** * @returns {boolean} */ isErrorMessage() { return this.getReply().indexOf('ERR') === 0; } /** * @returns {object} */ toError() { return new Error(this.raw_message); } } extend(Message_Reply.prototype, { reply: null }); module.exports = Message_Reply; test/dropdown/main.js require.config(requireConfig); require(['dropdown.spec'], function() { 'use strict'; startJasmine(); }); var address_data = [{ "id": 1, "address": "中惠松湖城1期", "doorplate": "2栋2单元2001", "name": "宋迎宾", "sex": "0", "phone": "15625527280", "latitude": "22.981760", "longitude": "113.912910", "default_start": 0, "default_end": 0 }, { "id": 3, "address": "中惠松湖城1期", "doorplate": "2栋2单元2001", "name": "钟活动", "sex": "0", "phone": "15625527283", "latitude": "22.981760", "longitude": "113.912910", "default_start": 0, "default_end": 1 }, { "id": 2, "address": "东莞理工学院城市学院", "doorplate": "3D301", "name": "陈观花", "sex": "1", "phone": "15625527281", "latitude": "22.978630", "longitude": "113.838140", "default_start": 1, "default_end": 0 }, { "id": 4, "address": "中惠松湖城1期", "doorplate": "2栋2单元2001", "name": "丘奇幻", "sex": "0", "phone": "15625527285", "latitude": "22.981760", "longitude": "113.912910", "default_start": 0, "default_end": 0 } ] var item_type_data = [{ "id": 1, "categoryname": "餐饮", "categoryprice": 1.2, "disabled": true }, { "id": 2, "categoryname": "文件", "categoryprice": 2, "disabled": true }, { "id": 3, "categoryname": "生鲜", "categoryprice": 1.2, "disabled": false }, { "id": 4, "categoryname": "蛋糕", "categoryprice": 3, "disabled": false }, { "id": 5, "categoryname": "鲜花", "categoryprice": 4, "disabled": false }, { "id": 6, "categoryname": "钥匙", "categoryprice": 3, "disabled": false }, { "id": 7, "categoryname": "数码", "categoryprice": 2.9, "disabled": false }, { "id": 8, "categoryname": "服饰", "categoryprice": 1.9, "disabled": false }, { "id": 9, "categoryname": "其他", "categoryprice": 8, "disabled": false }] var star_data = [{ id: 1, src: "/images/icons/star_null.png" }, { id: 2, src: "/images/icons/star_null.png" }, { id: 3, src: "/images/icons/star_null.png" }, { id: 4, src: "/images/icons/star_null.png" }, { id: 5, src: "/images/icons/star_null.png" } ] module.exports = { address_data: address_data, item_type_data: item_type_data, star_data: star_data }resources/assets/js/angular/directives/scroll.js /** * Created by cube7r on 8/18/2016. */ angular.module('chat').directive('scrollBottom',function($timeout){ //qvar j= $.noConflict(); return{ controller:'chatcontroller', scope:{ list:'=scrollBottom' }, link:function($scope, $element){ $scope.$watchCollection('list',function(newValue){ if(newValue){ $timeout(function(){ $element.scrollTop($element[0].scrollHeight); }, 0); } }); } } });deskach/message-syssrc/chat/panel-items/contact.js import React, {Component, PropTypes} from "react"; import BaseItem from "./base"; const CONTACT_TYPE = {TEACHER: 1, STUDENT: 2, GROUP: 3}; export default class Contact extends BaseItem { static propTypes = { ...BaseItem.propTypes, type: PropTypes.number, }; static defaultProps = { ...BaseItem.defaultProps, type: CONTACT_TYPE.STUDENT, }; static TYPE = CONTACT_TYPE; render() { const type2style = { [Contact.TYPE.STUDENT]: 'panel-item-student', [Contact.TYPE.TEACHER]: 'panel-item-teacher', [Contact.TYPE.GROUP]: 'panel-item-teacher', }; const type2selected = { [Contact.TYPE.STUDENT]: 'panel-item-student-selected', [Contact.TYPE.TEACHER]: 'panel-item-teacher-selected', [Contact.TYPE.GROUP]: 'panel-item-teacher-selected', }; const typeStyle = type2style[this.props.type]; const selectedStyle = this.props.selected ? type2selected[this.props.type] : ''; const className = ["panel-item panel-item-contact", typeStyle, selectedStyle].join(' '); return (
      {this.props.title}
      ) } } import ImportDialog from './import-dialog.js'; import SrdCreatureList from '../../../data/srd-creature-list.js'; import { fetchFromFile } from '../../../helpers/file-helpers.js'; export default class ImportSrdDialog extends ImportDialog { static get elementName() { return 'import-srd-dialog'; } static get templatePaths() { return super.templatePaths.set( 'import-srd-dialog', 'src/html/elements/autonomous/dialogs/import-srd-dialog.html'); } constructor() { super(ImportSrdDialog.templatePaths); this.creatureSelect = this.shadowRoot.getElementById('creature-select'); this.importButton = this.shadowRoot.getElementById('import-button'); } connectedCallback() { super.connectedCallback(); this.importButton.addEventListener('click', this.onClickImportButton.bind(this)); this.isInitialized = true; } async onClickImportButton() { const creatureSlug = this.creatureSelect.value; const path = `examples/5e-srd/${creatureSlug}.json`; const text = await fetchFromFile(path); const json = JSON.parse(text); this.importCallback(json); this.closeModal(); } launch(importCallback) { super.launch(importCallback); if (this.creatureSelect.options.length === 0) { this.creatureSelect.populate( SrdCreatureList.map(creature => new Option(creature.name, creature.slug))); } this.setStatus('Choose a creature:'); this.showModal(); } }bxck75/chat_node module["exports"] = [ "Waardeloos", "Klein", "Groot", "Poepjes", "Scheel", "Pik", "Paal", "Strobaal" ]; /** * Watch for changes in the sourcecode, and rebuild vis.js on change * * Usage: * cd vis * node tools/watch.js */ var watch = require('node-watch'), child_process = require('child_process'); // constants var WATCH_FOLDER = './src'; var BUILD_COMMAND = 'jake build'; // rebuilt vis.js on change of code function rebuild() { var start = +new Date(); child_process.exec(BUILD_COMMAND, function () { var end = +new Date(); console.log('rebuilt in ' + (end - start) + ' ms'); }); } // watch for changes in the code, rebuilt vis.js automatically watch(WATCH_FOLDER, function(filename) { console.log(filename + ' changed'); rebuild(); }); rebuild(); console.log('watching for changes in the source code...'); /* * ItemStatus Messages * * This contains all the text for the EntityList component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ draft: { id: 'app.components.ItemStatus.draft', defaultMessage: 'draft', }, }); import React from 'react'; const About = (props) => { return (

      About

      This is a personal project for getting convenient access to articles posted to the arXiv in different categories of interest. The main goal is to build a dataset of arXiv articles and interested/not-interested classifications in order to build a recommendation machine learning model to suggest new articles of interest to myself given the text in the article title and abstract.

      This is not a replacement for arXiv, and the features here are very limited by comparison. The advantage of this platform is the eventual ability to send recommended articles by email based on past preferences.

      For questions please contact myself - - through GitHub page for this project.

      ) } export default About;var WispHighlight = WispHighlight || function (id, option) { const script = document.createElement('script'); script.src = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js'; document.getElementsByTagName("head")[0].appendChild(script); const link = document.createElement('link'); link.href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/github.min.css'; link.rel = 'stylesheet' document.getElementsByTagName("head")[0].appendChild(link); } WispHighlight.prototype = { append: function (obj) { obj.code_highlight_hook(function (id, code, lang) { let highlighted_code highlighted_code = hljs.highlightAuto(code, [lang]).value; return highlighted_code }); } }johanrd/ember-ganttember-cli-build.js10-100 'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { let app = new EmberAddon(defaults, { snippetPaths: ['tests/dummy/app/snippets'], 'ember-bootstrap': { 'bootstrapVersion': 4, 'importBootstrapFont': false, 'importBootstrapCSS': false }, 'ember-cli-uglify': { uglify: { compress: { collapse_vars: false } } }, }); return app.toTree(); }; client/app/account/billing/common/dateRangeSelection.js angular.module('Billing.services').service('BillingdateRangeSelection', [ '$window', function ($window) { const STORAGE_KEY_PREFIX = 'billingDateRangeSelection'; function loadDateFromStorage(dateType, defaultDate) { let date = moment($window.sessionStorage.getItem(`${STORAGE_KEY_PREFIX}_${dateType}`)); if (!date.isValid()) { date = moment(defaultDate); } return date; } let mode = $window.sessionStorage.getItem(`${STORAGE_KEY_PREFIX}_mode`); let dateFrom = loadDateFromStorage( 'dateFrom', moment() .subtract(1, 'month') .startOf('month'), ); let dateTo = loadDateFromStorage('dateTo', moment().endOf('day')); return { get mode() { return mode; }, set mode(_mode_) { if (mode !== _mode_) { mode = _mode_; $window.sessionStorage.setItem(`${STORAGE_KEY_PREFIX}_mode`, _mode_); } }, get dateFrom() { return dateFrom; }, set dateFrom(_dateFrom_) { if (dateFrom !== _dateFrom_) { dateFrom = moment(_dateFrom_); $window.sessionStorage.setItem(`${STORAGE_KEY_PREFIX}_dateFrom`, dateFrom.toISOString()); } }, get dateTo() { return dateTo; }, set dateTo(_dateTo_) { if (dateTo !== _dateTo_) { dateTo = moment(_dateTo_); $window.sessionStorage.setItem(`${STORAGE_KEY_PREFIX}_dateTo`, dateTo.toISOString()); } }, }; }, ]); Luckyaremu/react-bookstore import { v1 as uuidv1 } from 'uuid'; import books from '../../reducers/books'; import { CREATE_BOOK, REMOVE_BOOK } from '../../constants/ActionTypes'; import INITIAL_STATE from '../../constants/InitialState'; describe('books reducer', () => { const id = uuidv1(); test('should return the initial state', () => { expect(books(undefined, {})).toEqual(INITIAL_STATE); }); test('should handle CREATE_BOOK', () => { expect( books([], { type: CREATE_BOOK, book: { id, title: 'Test book', category: 'Action' }, }), ).toEqual([ { id, title: 'Test book', category: 'Action' }, ]); expect( books( INITIAL_STATE, { type: CREATE_BOOK, book: { id, title: 'Test book', category: 'Action' }, }, ), ).toEqual([ ...INITIAL_STATE, { id, title: 'Test book', category: 'Action' }, ]); }); test('should handle REMOVE_BOOK', () => { expect( books([{ id, title: 'Test book', category: 'Action' }], { type: REMOVE_BOOK, id, }), ).toEqual([]); expect( books([ ...INITIAL_STATE, { id, title: 'Test book', category: 'Action' }], { type: REMOVE_BOOK, id, }), ).toEqual([ ...INITIAL_STATE, ]); }); }); // This was taken from an example on highgraphs function getChartForData(data) {// Give the points a 3D feel by adding a radial gradient let listData = data.map((dict) => [dict.x, dict.y, dict.z]); let maxes = {x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY}; let mins = {x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY}; ['x', 'y', 'z'].forEach((axis) => data.forEach((dict) => { maxes[axis] = Math.max(maxes[axis], dict[axis]); mins[axis] = Math.min(mins[axis], dict[axis]); })); console.log(mins); console.log(maxes); Highcharts.setOptions({ colors: Highcharts.getOptions().colors.map(function (color) { return { radialGradient: {}, stops: [ [0, color], [1, Highcharts.color(color).get('rgb')] ] }; }) }); // Set up the chart var chart = new Highcharts.Chart({ chart: { renderTo: 'container', margin: 100, type: 'scatter3d', animation: false, options3d: { enabled: true, alpha: 10, beta: 30, depth: 250, viewDistance: 5, fitToPlot: false, frame: { bottom: {size: 1, color: 'rgba(0,0,0,0.02)'}, back: {size: 1, color: 'rgba(0,0,0,0.04)'}, side: {size: 1, color: 'rgba(0,0,0,0.06)'} } } }, title: { text: 'Location box' }, subtitle: { text: 'Click and drag the plot area to rotate in space' }, plotOptions: { scatter: { width: 10, height: 10, depth: 10 } }, yAxis: { min: mins.y, max: maxes.y, title: null }, xAxis: { min: mins.x, max: maxes.x, gridLineWidth: 1 }, zAxis: { min: mins.z, max: maxes.z, showFirstLabel: false }, legend: { enabled: false }, series: [{ name: 'Data', colorByPoint: true, accessibility: { exposeAsGroupOnly: true }, data: listData }] }); // Add mouse and touch events for rotation (function (H) { function dragStart(eStart) { eStart = chart.pointer.normalize(eStart); var posX = eStart.chartX, posY = eStart.chartY, alpha = chart.options.chart.options3d.alpha, beta = chart.options.chart.options3d.beta, sensitivity = 5, // lower is more sensitive handlers = []; function drag(e) { // Get e.chartX and e.chartY e = chart.pointer.normalize(e); chart.update({ chart: { options3d: { alpha: alpha + (e.chartY - posY) / sensitivity, beta: beta + (posX - e.chartX) / sensitivity } } }, undefined, undefined, false); } function unbindAll() { handlers.forEach(function (unbind) { if (unbind) { unbind(); } }); handlers.length = 0; } handlers.push(H.addEvent(document, 'mousemove', drag)); handlers.push(H.addEvent(document, 'touchmove', drag)); handlers.push(H.addEvent(document, 'mouseup', unbindAll)); handlers.push(H.addEvent(document, 'touchend', unbindAll)); } H.addEvent(chart.container, 'mousedown', dragStart); H.addEvent(chart.container, 'touchstart', dragStart); }(Highcharts)); }const arrayShift = require('../arrayShift.js'); describe('arrayShift', () => { const even = [1, 2, 3, 4]; const odd = [1, 2, 3]; const val = 333; const none = []; it('Can work with an odd count array', () => { expect(arrayShift(odd, val)).toStrictEqual([1, 2, val, 3]); }); it('Can work with an even count array', () => { expect(arrayShift(even, val)).toStrictEqual([1, 2, val, 3, 4]); }); it('Can work with an empty array', () => { expect(arrayShift(none, val)).toStrictEqual([val]); }); });Oskari.registerLocalization({ "lang": "sv", "key": "Toolbar", "value": { "buttons": { "link": { "tooltip": "Länk", "ok": "Ok", "title": "Länk till kartvyn" }, "print": { "tooltip": "Skriv ut" }, "history": { "reset": "Tillbaka till standardvyn", "back": "Föregående", "next": "Nästa" }, "pan": "Flytta kartan", "zoom": "Zooma in", "measure": { "line": "Mät avstånd", "area": "Mät areal" } }, "measure" : { "title" : "Mätningsresultat", "close" : "Avbryt", "guidance" : { "measureline" : "Peka ut sträckan som ska mätas på kartan. Sluta mätningen genom att dubbelklicka.", "measurearea" : "Peka ut området som ska mätas på kartan. Sluta mätningen genom att dubbelklicka." } } } });const clientData = require('./client.json'); const twoClients = require('./two-clients.json'); module.exports = { clientData, twoClients, }; 1-10 /** * @module UIElements/Basic */ import $ from 'jquery'; import _ from 'lodash'; import UIText from '../UIText.js'; import { mxGeometry } from '../../misc/mxExport.js'; Button.prototype = new UIText(); Button.prototype.constructor = Button; UIText.registerCodec(Button); //Global for the codec converter window.Button = Button; /** * The HTML node name * @static * @default button * @readonly */ Button.HTML_NODE_NAME = 'button'; /** * The Name in the wireframing editor * @static * @default Button * @readonly */ Button.NAME = "Button"; /** * A concrete button class representing a button ui element of the wireframe * @classdesc The Button html element * @constructor * @param {mxGeometry} [geometry=new mxGeometry(0, 0, 100, 50)] the width, height, x and y of the ui element * @extends UIText */ function Button(geometry) { /** * The default text for the label * @member {String} * @default Button */ var text = 'Button'; if (!geometry) geometry = new mxGeometry(0, 0, 100, 50); UIText.call(this, text, geometry); this.value.setAttribute('_disabled', false); this.value.setAttribute('_autofocus', false); this.value.setAttribute('_type', 'button'); this.getComboAttrMap().addComboAttr('_type', ['button', 'reset', 'submit']); /** * Crate the html input element for the button element * @return {undefined} * @override */ this.initDOM = function () { var $button = $(document.createElement('button')); $button.attr('disabled', true) .css('width', this.geometry.width) .css('height', this.geometry.height) .append( $(document.createElement('input')).css('text-align', 'center') //.css('border-radius', '12px') .css('background-color', 'transparent') .css('border-style', 'unset') .css('width', '100%') .val(text)); this.set$node($button); } /** * @override * @param {boolean} createdByLocalUser indicates if the the function was called by the local user or not * @return {undefined} */ this.createShared = function (createdByLocalUser) { UIText.prototype.createShared.call(this, createdByLocalUser); }; } Button.prototype.bindLabel = function(ytext){ var that = this; ytext.bind(this.get$node().find('input')[0]); ytext.observe(_.debounce(function(event){ that.value.setAttribute('label', event.object.toString()); $('.wfSave').click(); }, 300)); } export default Button;const {toWei} = require('web3-utils'); const {artifacts, accounts} = require('hardhat'); const DefaultNFMaskLength = 32; const { RewardsTokenInitialBalance, DayInSeconds, CycleLengthInSeconds, PeriodLengthInSeconds, PeriodLengthInCycles, RarityWeights, DefaultRewardSchedule, RewardsPool, } = require('./constants'); const {ZeroAddress} = require('@animoca/ethereum-contracts-core').constants; const {mintStakerTokens} = require('./behaviors/staking.behavior'); const [creator, staker] = accounts; async function deploy() { const registry = await artifacts.require('ForwarderRegistry').new({from: creator}); this.nftContract = await artifacts.require('ERC1155721InventoryMock').new(registry.address, ZeroAddress, DefaultNFMaskLength, {from: creator}); this.rewardsToken = await artifacts .require('ERC20Mock') .new([creator], [RewardsTokenInitialBalance], registry.address, ZeroAddress, {from: creator}); this.stakingContract = await artifacts.require('DeltaTimeStaking2021').new( CycleLengthInSeconds, PeriodLengthInCycles, this.nftContract.address, this.rewardsToken.address, RarityWeights.map((x) => x.rarity), RarityWeights.map((x) => x.weight), {from: creator} ); // for 'interface support' tests this.contract = this.stakingContract; await this.rewardsToken.approve(this.stakingContract.address, RewardsTokenInitialBalance, {from: creator}); await mintStakerTokens.bind(this)(staker); } async function start(rewardSchedule = DefaultRewardSchedule) { for (schedule of rewardSchedule) { await this.stakingContract.addRewardsForPeriods(schedule.startPeriod, schedule.endPeriod, toWei(schedule.rewardPerCycle), {from: creator}); } await this.stakingContract.start({from: creator}); this.cycle = 1; this.period = 1; } module.exports = { deploy, start, }; /** * Copyright 2013-2015 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. */ /** * Test parent/parents/parentsUntil functions */ var xQ = require('../index') function allXml(q) { return q.map(function(n) { return xQ(n).xml(); }); } /** * Test empty set */ module.exports.testEmpty = function(test) { var empty = new xQ(); test.strictEqual(empty.parent().length, 0); test.strictEqual(empty.parent('empty').length, 0); test.strictEqual(empty.parents().length, 0); test.strictEqual(empty.parents('empty').length, 0); test.strictEqual(empty.parentsUntil('empty').length, 0); test.done(); } /** * Test parent() */ module.exports.testParent = function(test) { var q = new xQ("12" + "3" + "4"); test.deepEqual(allXml(q.find('number').parent()), ["12", "12", "3", "4"]); test.deepEqual(allXml(q.find('number').parent('items')), ["12", "12", "3"]); test.deepEqual(allXml(q.find('number').parent('wrapper')), ["4"]); test.deepEqual(allXml(q.find('number').parent('nomatch')), []); test.done(); } /** * Test parents() */ module.exports.testParents = function(test) { var q = new xQ("12" + "3" + "4"); test.deepEqual(allXml(q.find('number').parents()), ["12", "12", "1234", "12", "12", "1234", "3", "1234", "4", "4", "1234"]); test.deepEqual(allXml(q.find('number').parents('items')), ["12", "12", "3", "4"]); test.deepEqual(allXml(q.find('number').parents('nomatch')), []); test.done(); } /** * Test parentsUntil() */ module.exports.testParentsUntil = function(test) { var q = new xQ("12" + "3" + "4"); test.deepEqual(allXml(q.find('number').parentsUntil('items')), ["4"]); test.deepEqual(allXml(q.find('number').parentsUntil('nomatch')), ["12", "12", "1234", "12", "12", "1234", "3", "1234", "4", "4", "1234"]); test.done(); } import { View, Text, ScrollView } from "react-native"; import { SafeAreaView } from 'react-native-safe-area-context'; import React from "react"; import HeaderChat from "../components/chat/HeaderChat"; import Messages from "../components/chat/Messages"; import TextInputBox from "../components/chat/TextInputBox"; import {messages_list} from "../components/chat/Messages"; export default function Chat({ route }) { return ( {/* Esto de route.params viene de cuando se llega al chat mediante un click en otro boton y se le pasa la info de esta manera vvvv navigation.navigate("Chat", { name: item.name, image: item.img_url, seller: item.seller price: props.price, }) */} ); } const xmlify = require('xmlify'); const WilayaPresenter = { /** * Return an Express HTTP repsonse with a status code * @param {Object} res Express reponse object * @param {Object} data Data to return * @param {String} format Response type (example: xml, json) default: JSON * @param {Number} statusCode HTTP Status code */ presentResponse: (res, data, format, xmlRootName, statusCode = 200) => { if (format === 'xml') { res.type('application/xml'); return res.status(statusCode).send(xmlify(data, xmlRootName)); } return res.status(statusCode).json({ data }); }, presentArrayResponse: (res, data, format, xmlRootName, statusCode = 200) => { if (format === 'xml') { const xmlResponse = xmlify(Array.from(data), { root: xmlRootName }); res.type('application/xml'); return res.status(statusCode).send(xmlResponse); } return res.status(statusCode).json({ data }); }, }; module.exports = WilayaPresenter; (function ($) { 'use strict'; $('#contactForm').validate({ submitHandler: function (form) { var $form = $(form), $messageSuccess = $('#contactSuccess'), $messageError = $('#contactError'), $submitButton = $(this.submitButton), $errorMessage = $('#mailErrorMessage'), submitButtonText = $submitButton.val(); $submitButton.val($submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...').attr('disabled', true); // Send with POST method $.ajax({ type: 'POST', url: $form.attr('action'), data: { name: $form.find('#name').val(), email: $form.find('#email').val(), _token: $form.find('#_token').val(), message: $form.find('#message').val() } }).always(function (data, textStatus, jqXHR) { $errorMessage.empty().hide(); if (data.response == 'success') { $messageSuccess.removeClass('hide-box'); $messageError.addClass('hide-box'); $form.find('.form-control').val('').blur().parent().removeClass('has-success').removeClass('has-danger').find('label.error').remove(); $form.find('.form-control').removeClass('error'); $submitButton.val(submitButtonText).attr('disabled', false); return; } else { $errorMessage.html(data.errorMessage).show(); } $messageError.removeClass('hide-box'); $messageSuccess.addClass('hide-box'); $form.find('.has-success').removeClass('has-success'); $submitButton.val(submitButtonText).attr('disabled', false); }); } }); }).apply(this, [jQuery]);DevFullStackJS/prisma-client-lib "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var graphql_1 = require("graphql"); function isScalar(t) { if (t instanceof graphql_1.GraphQLScalarType || t instanceof graphql_1.GraphQLEnumType) { return true; } if (t instanceof graphql_1.GraphQLObjectType || t instanceof graphql_1.GraphQLInterfaceType || t instanceof graphql_1.GraphQLUnionType || t instanceof graphql_1.GraphQLList) { return false; } var nnt = t; if (nnt instanceof graphql_1.GraphQLNonNull) { if (nnt.ofType instanceof graphql_1.GraphQLScalarType || nnt.ofType instanceof graphql_1.GraphQLEnumType) { return true; } } return false; } exports.isScalar = isScalar; function getTypeForRootFieldName(rootFieldName, operation, schema) { if (operation === 'mutation' && !schema.getMutationType()) { throw new Error("Schema doesn't have mutation type"); } if (operation === 'subscription' && !schema.getSubscriptionType()) { throw new Error("Schema doesn't have subscription type"); } var rootType = { query: function () { return schema.getQueryType(); }, mutation: function () { return schema.getMutationType(); }, subscription: function () { return schema.getSubscriptionType(); }, }[operation]() || undefined; var rootField = rootType.getFields()[rootFieldName]; if (!rootField) { throw new Error("No such root field found: " + rootFieldName); } return rootField.type; } exports.getTypeForRootFieldName = getTypeForRootFieldName; function printDocumentFromInfo(info) { var fragments = Object.keys(info.fragments).map(function (fragment) { return info.fragments[fragment]; }); var doc = { kind: graphql_1.Kind.DOCUMENT, definitions: [ { kind: graphql_1.Kind.OPERATION_DEFINITION, operation: 'query', selectionSet: info.fieldNodes[0].selectionSet, } ].concat(fragments), }; return graphql_1.print(doc); } exports.printDocumentFromInfo = printDocumentFromInfo; function lowerCaseFirst(str) { return str[0].toLowerCase() + str.slice(1); } function getExistsTypes(queryType) { var types = getTypesAndWhere(queryType); return types .map(function (_a) { var type = _a.type, where = _a.where; return " " + lowerCaseFirst(type) + ": (where?: " + where + ") => Promise"; }) .join('\n'); } exports.getExistsTypes = getExistsTypes; function getExistsFlowTypes(queryType) { var types = getTypesAndWhere(queryType); return types .map(function (_a) { var type = _a.type, where = _a.where; return lowerCaseFirst(type) + "(where?: " + where + "): Promise;"; }) .join('\n'); } exports.getExistsFlowTypes = getExistsFlowTypes; function getTypesAndWhere(queryType) { var fields = queryType.getFields(); var listFields = Object.keys(fields).reduce(function (acc, field) { var deepType = getDeepListType(fields[field]); if (deepType) { acc.push({ field: fields[field], deepType: deepType }); } return acc; }, []); return listFields.map(function (_a) { var field = _a.field, deepType = _a.deepType; return ({ type: deepType.name, pluralFieldName: field.name, where: getWhere(field), }); }); } exports.getTypesAndWhere = getTypesAndWhere; function getWhere(field) { return field.args.find(function (a) { return a.name === 'where'; }) .type.name; } exports.getWhere = getWhere; function getDeepType(type) { if (type.ofType) { return getDeepType(type.ofType); } return type; } exports.getDeepType = getDeepType; function getDeepListType(field) { var type = field.type; if (graphql_1.isListType(type)) { return type.ofType; } if (graphql_1.isWrappingType(type) && graphql_1.isListType(type.ofType)) { return type.ofType.ofType; } return null; } exports.getDeepListType = getDeepListType; //# sourceMappingURL=index.js.mapkorytovaf/SKILBOX_nodeJS_deploy_timerspublic/main.js0 /*global UIkit, Vue */ (() => { const wsProto = location.protocol === "https:" ? "wss:" : "ws:"; const client = new WebSocket(`${wsProto}//${location.host}`); const notification = (config) => UIkit.notification({ pos: "top-right", timeout: 5000, ...config, }); const info = (message) => notification({ message, status: "success", }); new Vue({ el: "#app", data: { desc: "", activeTimers: [], oldTimers: [], }, methods: { createTimer() { const description = this.desc; this.desc = ""; client.send( JSON.stringify({ type: "create_timer", description, }) ); }, stopTimer(id) { client.send( JSON.stringify({ type: "stop_timer", id, }) ); }, formatTime(ts) { return new Date(ts).toTimeString().split(" ")[0]; }, formatDuration(d) { d = Math.floor(d / 1000); const s = d % 60; d = Math.floor(d / 60); const m = d % 60; const h = Math.floor(d / 60); return [h > 0 ? h : null, m, s] .filter((x) => x !== null) .map((x) => (x < 10 ? "0" : "") + x) .join(":"); }, }, created() { client.addEventListener("message", (message) => { let data; try { data = JSON.parse(message.data); } catch (err) { return; } if (data.type === "active_timers") { this.activeTimers = data.activeTimers; } if (data.type === "all_timers") { this.activeTimers = data.activeTimers; this.oldTimers = data.oldTimers; } if (data.type === "created_timer") { this.activeTimers = data.activeTimers; this.oldTimers = data.oldTimers; info(`Created new timer "${data.description}" [${data.idCreatedTimer}]`); } if (data.type === "stop_timer") { this.activeTimers = data.activeTimers; this.oldTimers = data.oldTimers; info(`Stopped the timer [${data.updatedTimer.id}]`); } }); client.addEventListener("open", () => { client.send( JSON.stringify({ type: "all_timers", }) ); }); }, }); })(); src/Turn Tracker/Sort Turns Desc.js // ==Bookmarklet== // @name Roll20 - Sort Turns Descending // @author // ==/Bookmarklet== $(".sortlist_numericdesc").click(); import React, { Component } from 'react'; import { SemanticToastContainer } from 'react-semantic-toasts'; import { Container, Grid } from 'semantic-ui-react'; import { Navigation } from './Navigation'; export class Layout extends Component { displayName = Layout.name; render() { return ( {this.props.children} ); } } // Vendors import React from 'react'; // Material UI import Radio from '@material-ui/core/Radio'; export default (props) => { return ; }; var searchData= [ ['flush_5ftrail_82',['flush_trail',['../interfacem__journal_1_1journal.html#acdde0ed4590797094f797514820e34fc',1,'m_journal::journal::flush_trail()'],['../namespacem__journal.html#a24b891eded8ca585a6a72ab0eef7016c',1,'m_journal::flush_trail()']]], ['fmt_83',['fmt',['../namespacem__msg.html#acee9a16663cf854f68bc4e741cb6045f',1,'m_msg::fmt()'],['../namespacem__strings.html#afccf1e453a4315a639f133f2f7c0078b',1,'m_strings::fmt()']]], ['fmtdate_84',['fmtdate',['../namespacem__time.html#a2cb84c9b8af4f395b76aed76e1431328',1,'m_time']]], ['fmtdate_5fusage_85',['fmtdate_usage',['../namespacem__time.html#a914927f70fb9495af1be2e484b967111',1,'m_time']]], ['fortran_5fname_86',['fortran_name',['../namespacem__strings.html#af30a54588d1806c0d63d58740492f99b',1,'m_strings']]], ['fstop_87',['fstop',['../namespacem__verify.html#a2695833d468118d68918d6aeabab6d0b',1,'m_verify']]] ]; 0 const express = require('express'); const Weather = require('../models/weather'); const router = express.Router(); // get weather for a chosen city router.get('/:city', (req, res) => { const city = req.params.city; Weather.retrieveByCity(city, (err, weather) => { if (err) return res.json(err); return res.json(weather); }); }); module.exports = router;10-100 ;(function(root) { var Labels = function(){ var _w, _h, _color, labelHeight = 16, labelSpacing = 18, _align, _dispatch = d3.dispatch(), _dims; function chart(selection) { selection.each(function(data) { var container = d3.select(this); var labelsWrapper = container .selectAll('g.label-group') .data(data); var labelWrapper = labelsWrapper.enter() .append('g') .attr('class','label-group'); var prev = 0, cols = 0; totalLen = 0, wm = _dims.w - _dims.m.l - _dims.m.r; container .selectAll('g.label-group') .attr('transform', function(d, i){ var len = drata.utils.textToPixel(d.key, 'font-size: 14px; font-family: arial;').width + labelSpacing; totalLen += len; if(prev + len >= wm) { prev = 0; cols ++; } var ret = 'translate('+ prev +', ' + (cols * labelHeight) + ')'; prev = prev + len; return ret; //return 'translate('+ exl[i] +')'; }); _dims.m.t = Math.max(_dims.m.t, ((cols + 1) * labelHeight) + labelSpacing); var l = cols > 0 ? _dims.m.l : (_dims.w - (totalLen/(cols + 1)))/2; if(_align === 'center') { container.attr('transform', 'translate('+ l + ',' + (_dims.h - _dims.m.b) +')'); } else if(_align === 'topcenter'){ container.attr('transform', 'translate('+ l + ')'); } labelWrapper.append('text').attr('class', 'label-text'); labelWrapper.append('circle').attr('class', 'label-circle'); labelsWrapper .select('text.label-text') .attr('x', function(){ return 10; }) .attr('y', labelHeight) .attr('fill', function(d,i){ return _color(d.key,i); }) .text(function(d){ return d.key; }) .on('click', _dispatch.togglePath); labelsWrapper .select('circle.label-circle') .attr('r',4) .attr('fill', function(d, i){ return (d.disabled)? '#fff' : _color(d.key, i); }) .attr('stroke', function(d, i){ return _color(d.key, i); }) .attr('stroke-width',2) .attr('cy', function(){ return 12; }) .on('click', _dispatch.togglePath); labelsWrapper.exit().remove(); }); return chart; } chart.color = function(value){ if (!arguments.length) return _color; _color = value; return chart; }; chart.dispatch = function(value){ if (!arguments.length) return _dispatch; _dispatch = value; return chart; }; chart.width= function(value){ if (!arguments.length) return _w; _w = value; return chart; }; chart.height= function(value){ if (!arguments.length) return _h; _h = value; return chart; }; chart.align= function(value){ if (!arguments.length) return _align; _align = value; return chart; }; chart.dims= function(value){ if (!arguments.length) return _dims; _dims = value; return chart; }; return chart; }; root.drata.ns('models').extend({ labels : Labels }); })(this);0 export default { lasttime:"Last Time ", no_lasttime:"None", target:"Targets", no_target:"None Target", unknown:"Unknown", } var namespace_smart_mesh_s_d_k_1_1_ip_mgr_connector_mux_1_1_ip_mgr_subscribe = [ [ "IpMgrSubscribe", "class_smart_mesh_s_d_k_1_1_ip_mgr_connector_mux_1_1_ip_mgr_subscribe_1_1_ip_mgr_subscribe.html", "class_smart_mesh_s_d_k_1_1_ip_mgr_connector_mux_1_1_ip_mgr_subscribe_1_1_ip_mgr_subscribe" ] ];1-10 const strings = require("./strings"); /** Class String Fancy. */ class StrFancy { /** * Create a point. * * @param {String} value */ constructor(value) { this.value = String(value); this.length = this.value.length; } /** * Create new Str object. * * @param {String} value - The any strings. * @returns {StrFancy} The StrFancy object. */ static of(value) { return new StrFancy(value); } /** * Return the remainder of a string after the first occurrence of a given value. * * @param {String} search * @returns {this} */ after(search) { return new StrFancy(strings.after(this.value, search)); } /** * Return the remainder of a string after the last occurrence of a given value. * * @param {String} search * @returns {String} */ afterLast(search) { return new StrFancy(strings.afterLast(this.value, search)); } /** * Append the given values to the string. * * @param {String[]} values * @returns {String} */ append(...values) { return new StrFancy(strings.append(this.value, ...values)); } /** * Transliterate a Unicode string to ASCII. * * @returns {String} */ ascii() { return new StrFancy(strings.ascii(this.value)); } /** * Get the trailing name component of the path. * * @param {String?} suffix * @returns {String} */ basename(suffix = "") { return new StrFancy(strings.basename(this.value, suffix)); } /** * Get the portion of a string before the first occurrence of a given value. * * @param {String} search * @returns {String} */ before(search) { return new StrFancy(strings.before(this.value, search)); } /** * Get the portion of a string before the last occurrence of a given value. * * @param {String} search * @returns {String} */ beforeLast(search) { return new StrFancy(strings.beforeLast(this.value, search)); } /** * Get the portion of a string between two given values. * * @param {String} from * @param {String} to * @returns {String} */ between(from, to) { return new StrFancy(strings.between(this.value, from, to)); } /** * Convert a value to camel case. * * @returns {String} fooBar */ camel() { return new StrFancy(strings.camel(this.value)); } /** * Determine if a given string contains a given substring. * * @param {String|String[]} needles * @returns {Boolean} */ contains(needles) { return new StrFancy(strings.contains(this.value, needles)); } /** * Determine if a given string contains all array values. * * @param {String[]} needles * @returns {Boolean} */ containsAll(needles) { return new StrFancy(strings.containsAll(this.value, needles)); } /** * Get the parent directory's path. * * @param {Number} [level = 1] * @returns {String} */ dirname(level = 1) { return new StrFancy(strings.dirname(this.value, level)); } /** * Determine if a given string ends with a given substring. * * @param {String|String[]} needles * @param {Number} [length] * @returns {Boolean} */ endsWith(needles, length) { return new StrFancy(strings.endsWith(this.value, needles, length)); } /** * Determine if the string is an exact match with the given value. * * @param {String} value * @returns {Boolean} */ exactly(value) { return new StrFancy(this.value === value); } /** * Split the string into an array. * * @param {String|RegExp} separator * @param {Number} limit * @returns {String[]} */ explode(separator, limit) { return new StrFancy(this.value.split(separator, limit)); } /** * Cap a string with a single instance of a given value. * * @param {String} cap * @returns {String} */ finish(cap) { return new StrFancy(strings.finish(this.value, cap)); } /** * Determine if a given string matches a given pattern. * * @param {String|[]} pattern * @returns {Boolean} */ is(pattern) { return new StrFancy(strings.is(pattern, this.value)); } /** * Determine if a given string matches a given pattern. * * @param {String|[]} pattern * @returns {Boolean} */ isAscii() { return new StrFancy(strings.isAscii(this.value)); } /** * Determine if the given string is empty. * * @returns {Boolean} */ isEmpty() { return new StrFancy(this.value === ""); } /** * Determine if the given string is not empty. * * @returns {Boolean} */ isNotEmpty() { return new StrFancy(!this.isEmpty()); } /** * Convert a value to kebab case. * * @param {String} [delimiter = "_"] * @returns {String} foo_bar */ kebab(delimiter = "_") { return new StrFancy(strings.kebab(this.value, delimiter)); } /** * Return the length of the given string. * * @returns {Number} */ length() { return new StrFancy(this.length); } /** * Limit the number of characters in a string. * * @param {String} value * @param {Number} [limit = 100] * @param {String} [end = "..."] * @returns {String} */ limit(limit = 100, end = "...") { return new StrFancy(strings.limit(this.value, limit, end)); } /** * Convert the given string to lower-case. * * @returns {String} */ lower() { return new StrFancy(strings.lower(this.value)); } /** * Left trim the string of the given characters. * * @param {String} value * @param {String} [characters = " "] * @returns {String} */ ltrim(characters = " ") { return new StrFancy(strings.ltrim(this.value, characters)); } /** * Get the string matching the given pattern. * * @param {RegExp|String} pattern * @returns {String} */ match(pattern) { return new StrFancy(strings.match(this.value, pattern)); } /** * Get the string matching the given pattern. * * @param {RegExp|String} pattern * @returns {String} */ matchAll(pattern) { return new StrFancy(strings.matchAll(this.value, pattern)); } /** * Pad both sides of a string with another. * * @param {Number} length * @param {String} [pad = " "] * @returns {String} */ padBoth(length, pad = " ") { return new StrFancy(strings.padBoth(this.value, length, pad)); } /** * Pad the left side of a string with another. * * @param {Number} length * @param {String} [pad = " "] * @returns {String} */ padLeft(length, pad = " ") { return new StrFancy(strings.padLeft(this.value, length, pad)); } /** * Pad the right side of a string with another. * * @param {Number} length * @param {String} [pad = " "] * @returns {String} */ padRight(length, pad = " ") { return new StrFancy(strings.padRight(this.value, length, pad)); } /** * Get the plural form of an English word. * * @param {Number} [count = 2] * @param {Boolean} [inclusive = false] - Whether to prefix with the number (e.g. 3 ducks) * @returns {String} */ plural(count = 2, inclusive = false) { return new StrFancy(strings.plural(this.value, count, inclusive)); } /** * Prepend the given values to the string. * * @param {String} values * @returns {String} */ prepend(...values) { return new StrFancy(strings.prepend(this.value, ...values)); } /** * Get the singular form of an English word. * * @returns {String} */ singular() { return new StrFancy(strings.singular(this.value)); } /** * Convert a value to studly case. * * @returns {String} FooBar */ studly() { return new StrFancy(strings.studly(this.value)); } } StrFancy.prototype.toString = function () { return this.value; }; module.exports = StrFancy; import React, { Component } from 'react'; import {Switch, Route, Redirect } from 'react-router-dom'; import Gebruikers from './Gebruikers/'; import Modules from './Modules/'; import NavbarMenu from './NavbarMenu'; import Login from './Login/'; import io from 'socket.io-client'; import { Modal, ControlLabel, Button, FormGroup } from 'react-bootstrap'; import './App.css'; function withProps(Component, props) { return function(matchProps) { return } } const AlarmModal = props => (
      ALARM Module: {props.module_id} Tijdstip melding: {props.alarm_time} {props.videostream}
      ) class Main extends Component { constructor(props){ super(props); this.state = { socket_server:'http://server.zorgtotaal.com', alarm: false, alarm_module:null } } deactivate_alarm(){ const socket = io(this.state.socket_server); socket.on("connection", function(){ console.log("socket connected"); }) socket.emit('alarm_off', {id:this.state.alarm_module.id}) this.setState({alarm:false, alarm_module:null}) } reloadVideoStream(){ this.setState({videourl:'http://'+this.state.alarm_module.ip+':10088/?action=stream'}); } render(){ const socket = io(this.state.socket_server); socket.on('alarm', function(module){ this.setState({alarm:true, alarm_module:module}); }.bind(this)); let cameramodal = null; if(this.state.alarm){ var me = this; let videostream = cameramodal = } return (
      {cameramodal}
      ); } }; const LoginMain = (props) => ( ); class App extends Component { constructor(props){ super(props); var user = JSON.parse(localStorage.getItem('user')); this.state = { user:user } } setUser(user){ localStorage.setItem('user', JSON.stringify(user)); this.setState({'user':user}); } render() { let view = this.state.user ?
      : ; return (
      { view }
      ); } } export default App; import React, { Component } from 'react'; import { NavbarBrand, Nav, NavItem, NavLink } from 'reactstrap'; import './styles/App.css'; const MainNav = (user) => { const UserAvailable = () => { console.log("user available: " + user.email) return ( My account ) } const UserNotAvailable = () => { console.log("user not available: " + user.email) return ( Login ) } return (
      ) } export default MainNav var MyHome = /** @class */ (function () { function MyHome(message) { this.message = message; } return MyHome; }()); ; var newMsg = new MyHome("Hello there"); console.log(newMsg.message); console.log("Typescript"); //# sourceMappingURL=app.js.mapsrc/components/GeneralControls.js1-10 import React from "react"; import Timer from "./Timer"; import Legend from "./Legend"; import { getAspectRatio } from "../helpers"; import { THEME } from "../constants"; import { GithubOutlined } from "@ant-design/icons"; import { Button } from "antd"; import "../styles.css"; const GeneralControls = ({ start, resetFields, running, finished, playgroundsContainerSize, }) => (
      { const tab = window.open( "https://github.com/jakubtelec/stay-home-sim", "_blank" ); tab.focus(); }} style={{ color: THEME.GITHUB_LINK }} className="git-icon" />
      ); export default GeneralControls; Xcallibur232/the-blue-alliance-pwa /* eslint-env jest */ // Mocks useRouter const useRouter = jest.spyOn(require("next/router"), "useRouter"); /** * mockNextUseRouter * Mocks the useRouter React hook from Next.js on a test-case by test-case basis */ export default function mockNextUseRouter({ route, pathname, query, asPath }) { useRouter.mockImplementation(() => ({ route, pathname, query, asPath, })); } /** * @param {string} s * @param {string[]} wordDict * @return {boolean} */ var wordBreak = function (s, wordDict) { let sLength = s.length; let dp = new Array(sLength + 1).fill(false); dp[0] = true; let set = new Set(wordDict); for (let end = 1; end <= sLength; end++) { for (let start = 0; start < end; start++) { let word = s.slice(start, end); if (dp[start] && set.has(word)) { dp[end] = true; break; } } } return dp[sLength]; }; /** * * @param {string} s * @param {number} index * @param {string[]} wordDict */ const backtrace = (s, index, wordDict) => { if (index === s.length) { return true; } for (let i = 0; i < wordDict.length; i++) { const word = wordDict[i]; const end = index + word.length; if (s.slice(index, end) === word) { let result = backtrace(s, end, wordDict); if (result) return true; } } return false; } // TEST: let s = "leetcode", wordDict = ["leet", "code"]; console.log(wordBreak(s, wordDict)) s = "applepenapple", wordDict = ["apple", "pen"] console.log(wordBreak(s, wordDict)) s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] console.log(wordBreak(s, wordDict)); s = "bb", wordDict = ["a", "b", "bbb", "bbbb"] console.log(wordBreak(s, wordDict)) s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", wordDict = ["a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"] console.log(wordBreak(s, wordDict)) /** * determine the (sub-)categories a particular instance appears in * in particular, we need to know which subcategory caused the instance to be included * REMARK : readline not able to parse long strings (not able to catch error to skip those entries) */ import Fs from 'fs'; import Path from 'path'; import Readline from 'readline'; import Config from './../config/config' ; // general configuration const cfg = { // source file source: Config.rawData, }; // parse command line arguments if( process.argv.length < 4 ) { console.error( `Usage: npm debug:instance2cat [instance] [category1] [category2] ...\nfound only ${process.argv.length-2} argument(s); need at least two` ); process.exit(); } const instance = process.argv[ 2 ]; const categories = new Set( process.argv.slice( 3 ) ); const entityRegexp = /^Q\d+$/; if( !entityRegexp.test(instance) ) { console.error( `Instance must be of form Qxx - found ${instance}` ); process.exit(); } for( const cat of categories ) { if( !entityRegexp.test(cat) ) { console.error( `Categories must be of form Qxx - found ${cat}` ); process.exit(); } } (async function(){ // read-interface to the source file const rl = Readline.createInterface({ input: Fs.createReadStream( cfg.source ), }); // walk through the file line by line let entry; const out = []; // collect the output, so we can add some stuff later on let label = '[unknown]'; // label of the instance we are looking for; only available within the data for await (const line of rl) { // parse the line try { entry = JSON.parse( line.slice( 0, -1) ); } catch(e) { // skip partial entries // e.g., first line with just an [ continue; } // skip everything that's not our target categories if( !categories.has( entry.queryID ) ){ continue; } categories.delete( entry.queryID ); out.push( `Category (${entry.queryID}): ${entry.query}` ); // shortcut const relResults = entry?.relevant?.wikipedia; if( relResults === null ) { continue; } for( const type of ['targetType', 'noType', 'noTargetType', 'noWikidataID' ] ) { for( const resultSet of relResults ) { // check, if our instance is included here const match = resultSet[ type ]?.find( (el) => el.iri == instance ); if( !match ) { continue; } // memorize the instance label label = match.iriLabel; // print all sources out.push( ` matches in ${type}` ); for( const sourceCat of match.source ) { out.push( ` * (${sourceCat.lang}) ${sourceCat.cat}` ); out.push( ` https://${sourceCat.lang}.wikipedia.org/wiki/${encodeURIComponent(sourceCat.cat)}` ); } } } // we can stop once all categories have been found if( categories.size < 1 ) { break; } } // print console.log( `Looking for (${instance}): ${label}\n` ); console.log( out.join( '\n' ) ); })().catch( (e) => console.error(e) ); 'use strict'; require('dotenv').config(); const host = process.env.HOST || 'localhost'; const port = process.env.PORT || 3000; const io = require('socket.io-client'); const capsNameSpace = io.connect(`http://${host}:${port}/caps`); capsNameSpace.on('pickup', order => onPickup(order)); function onPickup(order) { setTimeout(() => { console.log(`DRIVER: picked up ${order.orderID}`); capsNameSpace.emit('in-transit', order); }, 1000); setTimeout(() => { console.log(`DRIVER: delivered ${order.orderID}`); capsNameSpace.emit('delivered', order); }, 3000); } module.exports.onPickup = onPickup;0 const { Controller } = WebCardinal.controllers; const { DataSource } = WebCardinal.dataSources; async function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } class RWDataSource extends DataSource { constructor(...props) { super(...props); this.setRecordsNumber(9 * 9 + 2); this.setPageSize(9); } /** * @override */ async getPageDataAsync(startOffset, dataLengthForCurrentPage) { await sleep(500); return [...Array(dataLengthForCurrentPage).keys()].map(index => { const id = startOffset + index; return { image: { source: `https://www.gravatar.com/avatar/${id}?d=robohash` }, name: `Robo #${id}`, role: 'Role' } }); } } export default class extends Controller { constructor(...props) { super(...props); this.model = { dataSource: new RWDataSource() } } }var m = require('mithril'); module.exports = m.trust(''); // CANVAS ========================================================= const canvas = document.querySelector("#game__board"); canvas.width = 300; canvas.height = 300; const context = canvas.getContext("2d"); // background context.fillStyle = "#fff"; // backgrou color context.fillRect(0, 0, canvas.height, canvas.width); // fill background // border context.lineWidth = 2; // border width context.strokeStyle = "#000"; // border color context.strokeRect(0, 0, canvas.width, canvas.height); // fill border // SNAKE ================================================ // set snake position let snake = [ { x: 150, y: 150 }, { x: 140, y: 150 }, { x: 130, y: 150 }, { x: 120, y: 150 }, { x: 110, y: 150 }, ]; // draw snake parts const drawSnakeParts = (parts) => { context.fillStyle = "#90EE90"; context.strokestyle = "#006400"; context.fillRect(parts.x, parts.y, 10, 10); context.strokeRect(parts.x, parts.y, 10, 10); }; // draw snake function drawSnake() { snake.forEach(drawSnakeParts); } // clear old snake trails function clearCanvas() { context.fillStyle = "#fff"; context.strokeStyle = "#000"; context.fillRect(0, 0, canvas.width, canvas.height); context.strokeRect(0, 0, canvas.width, canvas.height); } // snake next position let dx = 10; let dy = 0; // FOOD ========================================================= // generate a random number from min to max by 10s function randomTens(min, max) { return Math.round((Math.random() * (max - min) + min) / 10) * 10; } // set food next position const foodPosition = { x: randomTens(0, canvas.width - 10), y: randomTens(0, canvas.height - 10), }; // create food function createFood() { foodPosition.x = randomTens(0, canvas.width - 10); foodPosition.y = randomTens(0, canvas.height - 10); // check if snake ate a food let foodIsOnSnake = snake.some((pos) => pos === foodPosition); // create next food if (foodIsOnSnake) createFood(); } // draw food to canvas function drawFood() { context.fillStyle = "#f00"; context.strokestyle = "#8b00"; context.fillRect(foodPosition.x, foodPosition.y, 10, 10); context.strokeRect(foodPosition.x, foodPosition.y, 10, 10); } // MOVEMENTS ================================================= // game score let score = 0; // set snake move position function advanceSnake(dx, dy) { // set next snake head position const head = { x: snake[0].x + dx, y: snake[0].y + dy }; // add next snake head position snake.unshift(head); // check if snake ate a food const didEatFood = snake[0].x === foodPosition.x && snake[0].y === foodPosition.y; if (didEatFood) { // then create food createFood(); // add score score += 10; // set score on ui document.querySelector(".score").innerText = score; } else { // else remove tail snake.pop(); } } // set changing direction status let changingDirection = false; // change snake direction function changeDirection(event) { // set snake move status if (changingDirection) return; changingDirection = true; // key press by user const keyPressed = event.keyCode; // set keyboard key code const LEFT_KEY = 37; const RIGHT_KEY = 39; const UP_KEY = 38; const DOWN_KEY = 40; // snake direction const goingUp = dy === -10; const goingDown = dy === 10; const goingRight = dx === 10; const goingLeft = dx === -10; // move up if (keyPressed === UP_KEY && !goingDown) { dx = 0; dy = -10; } // move down if (keyPressed === DOWN_KEY && !goingUp) { dx = 0; dy = 10; } // move left if (keyPressed === LEFT_KEY && !goingRight) { dx = -10; dy = 0; } // move right if (keyPressed === RIGHT_KEY && !goingLeft) { dx = 10; dy = 0; } } // move snake function move() { // return if game over if (didGameEnd()) return; setTimeout(function onTick() { // set changing direction to false changingDirection = false; // clear old snake position clearCanvas(); // draw food drawFood(); // move snake position advanceSnake(dx, dy); // draw snake drawSnake(); // recusion move(); }, 100); } // GAME OVER ================================================ function didGameEnd() { for (let i = 4; i < snake.length; i++) { const didCollide = snake[i].x === snake[0].x && snake[i].y === snake[0].y; if (didCollide) return true; } const hitLeftWall = snake[0].x < 0; const hitRightWall = snake[0].x > canvas.width - 10; const hitToptWall = snake[0].y < 0; // 0; const hitBottomWall = snake[0].y > canvas.height - 10; return hitLeftWall || hitRightWall || hitToptWall || hitBottomWall; } // start game move(); // add event listener on keypress document.addEventListener("keydown", changeDirection); 0 import React, { Component } from 'react'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import { Provider } from 'react-redux'; import store from '../Redux'; import Home from '../App/Components/Home'; import Convert from '../App/Components/Convert'; import Stat from '../App/Components/Stat'; import NotFound from '../App/Components/NotFound'; class App extends Component { render() { return ( ); } } export default App; import xss from 'xss'; var whiteList = { a: ['target', 'href', 'title', 'style'], button: ['class', 'data-cohort', 'data-bookmark'], abbr: ['title', 'style'], address: ['style'], area: ['shape', 'coords', 'href', 'alt', 'style'], article: ['style'], aside: ['style'], audio: ['autoplay', 'controls', 'loop', 'preload', 'src', 'style'], b: ['style'], bdi: ['dir', 'style'], bdo: ['dir', 'style'], big: ['style'], blockquote: ['cite', 'style'], br: ['style'], caption: ['style'], center: ['style'], cite: ['style'], code: ['style'], col: ['align', 'valign', 'span', 'width', 'style'], colgroup: ['align', 'valign', 'span', 'width', 'style'], dd: ['style'], del: ['datetime', 'style'], details: ['open', 'style'], div: ['style'], dl: ['style'], dt: ['style'], em: ['style'], figure: ['style'], figcaption: ['style'], font: ['color', 'size', 'face', 'style'], footer: ['style'], h1: ['style'], h2: ['style'], h3: ['style'], h4: ['style'], h5: ['style'], h6: ['style'], header: ['style'], hr: ['style'], i: ['style'], iframe: ['src', 'width', 'height', 'frameborder', 'allowfullscreen'], img: ['src', 'alt', 'title', 'width', 'height', 'style'], ins: ['datetime', 'style'], li: ['style'], mark: ['style'], nav: ['style'], ol: ['style'], p: ['style'], pre: ['style'], s: ['style'], section: ['style'], small: ['style'], span: ['style'], sub: ['style'], sup: ['style'], strong: ['style'], table: ['width', 'border', 'align', 'valign', 'style'], tbody: ['align', 'valign', 'style'], td: ['width', 'rowspan', 'colspan', 'align', 'valign', 'style'], tfoot: ['align', 'valign', 'style'], th: ['width', 'rowspan', 'colspan', 'align', 'valign', 'style'], thead: ['align', 'valign', 'style'], tr: ['rowspan', 'align', 'valign', 'style'], tt: ['style'], u: ['style'], ul: ['style'], video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'style'] }; var filter = new xss.FilterXSS({whiteList}); export default html => filter.process(html); Vyraax/VulkanLab var structfunction__call = [ [ "function_call", "structfunction__call.html#a7e92652f2171a83f7d690f57983c1631", null ], [ "args", "structfunction__call.html#ae77a8a65a8ae5ebbbd2eb17bc9ff54d3", null ], [ "args_convert", "structfunction__call.html#aef756a1f9206af0d2e3fdb684b2d6b5f", null ], [ "args_ref", "structfunction__call.html#a13ff878b84d1c7a41c0f28c62db36925", null ], [ "func", "structfunction__call.html#afadf98c8478fd2c1958003cedefa38d7", null ], [ "init_self", "structfunction__call.html#a8f9e4659cf3ca4be507d2220420b9c00", null ], [ "kwargs_ref", "structfunction__call.html#a1ae7a6c18887e3c791b6cb16b2cc98c0", null ], [ "parent", "structfunction__call.html#a72923821447a70a799f862a501eee20d", null ] ];import React, { Component } from "react"; import EditUserForm from "../Components/EditUserForm"; import { createUser } from "../API"; import { SuccessMsg, FailureMsg } from "../Components/ResponseMessage"; import { toggleLoader } from "../Reducers/Effects"; import { connect } from "react-redux"; class CreateUser extends Component { constructor(props) { super(props); this.state = { showSuccess: false, success_Msg: "", failure_Msg: "", showFailure: false }; } onSubmit(e) { e.preventDefault(); this.props.loaderToggler(true); createUser(e).then(res => { this.props.loaderToggler(false); console.log(res); if (res.status === 201) { this.helperMethod(); } else { this.setState({ showFailure: true, failure_Msg: res.message }); setTimeout(() => { this.setState({ showFailure: false, failure_Msg: "" }); }, 2000); } }); } helperMethod() { this.setState({ showSuccess: true, success_Msg: "User Created Successfully!" }); setTimeout(() => { this.props.history.push("/user/all"); }, 1000); } render() { return (

      Create Account

      {this.state.showSuccess ? ( ) : null} {this.state.showFailure ? ( ) : null}
      ); } } const mapDispatchToProps = (dispatch, ownProps) => ({ loaderToggler: option => dispatch(toggleLoader(option)) }); export default connect(null, mapDispatchToProps)(CreateUser); const inquirer = require('inquirer') const benchmark = require('./benchmark') const chooseSubjects = require('../../helpers/choose-subjects') const printer = require('../../helpers/printer') const benchmarkTypes = require('../../../settings/benchmark-types') const defaults = require('../../../settings/defaults') module.exports = async () => { const options = await askForOptions() const type = await askForType() const subjectsList = await askForSubjectsList(type) return async () => { printer.info('Benchmark', `"${type}"`, 'Started', '\r\n') const results = await benchmark( subjectsList, Object.assign(options, benchmarkTypes[type]) ) printer.info('Benchmark', `"${type}"`, 'Completed') printer.resultTable(results) } } function askForOptions() { return inquirer.prompt([ { type: 'input', name: 'connections', message: 'Specify the number of connections:', default: defaults.connections, validate(value) { return !Number.isNaN(parseFloat(value)) || 'Please enter a number' }, filter: Number }, { type: 'input', name: 'pipelining', message: 'Specify the number of pipelines:', default: defaults.pipelining, validate(value) { return !Number.isNaN(parseFloat(value)) || 'Please enter a number' }, filter: Number }, { type: 'input', name: 'duration', message: 'Specify the duration:', default: defaults.duration, validate(value) { return !Number.isNaN(parseFloat(value)) || 'Please enter a number' }, filter: Number } ]) } async function askForType() { const { type } = await inquirer.prompt({ type: 'list', name: 'type', message: 'Specify the benchmark type:', choices: Object.keys(benchmarkTypes) }) return type } async function askForSubjectsList(type) { return await chooseSubjects((subject) => subject.supports.includes(type)) } joaosantos15/hypercerts-1 import Core from './hc-core.js' import datIPFS from './ipfsstorage.js' // I'm at the point where I realised there is no FS library in the browser, // and need to change the way files are added to IPFS datIPFS.addItem('12345', 'claim:hello') async function userLogin(email, password) { const newState = { loginFailed: true, toDashboard: false, error: false } try { let response = await fetch('https://wilderness.42.us.org/auth/sign_in', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ email: email, password: password, uid: email, }) }); let res = await response.text(); if (response.status >= 200 && response.status < 300) { let accessToken = res; console.log(accessToken); localStorage.setItem('access_token', accessToken); newState.loginFailed = false newState.toDashboard = true return newState } else { let error = res; newState.loginFailed = true console.log(newState) throw error; } } catch (error) { newState.error = error newState.loginFailed = true console.log("error: " + error); return newState } } accounts-service/src/helpers/ApplicationStatusCodes.js0 module.exports= { ACCOUNT_NO_NOT_FOUND_001: 001, NO_ACCOUNT_FOUND_002: 002, S2S_KEY_INVALID_003: 003, FROM_ACCOUNT_ID_INVALID_004: 004, NOT_ENOUGH_BALANCE_005:005, TO_ACCOUNT_ID_INVALID_006:006, CURRENCY_CODE_NOT_FOUND_007:007, CURRENCY_TRANSFER_NOT_SUPPORTED_008:008 }import pkg from 'chai' import filter from '../src/filter.js' var { assert, expect, should } = pkg; const users = [ { 'user': 'Diego', 'active': true }, { 'user': 'fred', 'active': false }, { 'user': 'Bob', 'active': false }, { 'user': 'Bananaman', 'active': true } ] describe('9. filter', function() { describe('9.1. Filter with boolean value (users, ({ active }) => active)', function() { it('Should return Diego and Bananaman', function() { assert.deepEqual(filter(users, ({ active }) => active), [ { 'user': 'Diego', 'active': true }, { 'user': 'Bananaman', 'active': true } ]); }); }); describe('9.2. Filter with non-boolean attribute (users, ({ user }) => "Diego")', function() { it('Should return Diego', function() { assert.deepEqual(filter(users, ({ user }) => 'Diego'), [ { 'user': 'Diego', 'active': true } ]); }); }); describe('9.3. Filter with attribute that doesnt exist (users, ({ powerlevel }) => 9001), [[]])', function() { it('Should return empty list', function() { assert.deepEqual(filter(users, ({ powerlevel }) => 9001), [[]]); }); }); describe('9.4. Filter a null-value (null, ({ active }) => active), [[]])', function() { it('Should return empty list', function() { assert.deepEqual(filter(null, ({ active }) => active), [[]]); }); }); }); require("dotenv").config(); const withPlugins = require("next-compose-plugins"); const withSass = require("@zeit/next-sass"); const { stringify } = require("querystring"); const ACCOUNTS_URL = "https://accounts.spotify.com"; const SCOPES = [ "user-read-private", "user-read-email", "user-top-read", "playlist-read-private", "playlist-read-collaborative", "playlist-modify-private", "playlist-modify-public", ]; module.exports = withPlugins([withSass], { env: { DOMAIN: "https://spotify-playlist-plus.now.sh", REPO_URL: "https://github.com/stuart-williams/spotify-playlist-plus", CLIENT_ID: process.env.CLIENT_ID, CLIENT_SECRET: process.env.CLIENT_SECRET, REDIRECT_URI: process.env.REDIRECT_URI, AUTHORIZE_URL: `${ACCOUNTS_URL}/authorize?${stringify({ client_id: process.env.CLIENT_ID, response_type: "code", redirect_uri: process.env.REDIRECT_URI, scope: SCOPES.join(" "), })}`, TOKEN_COOKIE: "spp_token", API_URL: "https://api.spotify.com/v1", OPEN_SPOTIFY_URL: "https://open.spotify.com", ACCOUNTS_API_URL: `${ACCOUNTS_URL}/api`, GA_TRACKING_ID: "UA-163843172-1", GA_DEBUG: process.env.GA_DEBUG, REDUX_DEBUG: process.env.REDUX_DEBUG, }, }); doc/php/user__get__settings_8php.js var user__get__settings_8php = [ [ "$database_connection", "user__get__settings_8php.html#a357949b78a2b8a08cdd638ac4dd62057", null ], [ "$result", "user__get__settings_8php.html#a112ef069ddc0454086e3d1e6d8d55d07", null ], [ "$select_player_query", "user__get__settings_8php.html#aa547d85f3706a3e5a2748556f7819393", null ], [ "$statement", "user__get__settings_8php.html#a776dc234d8e2b257550d9444ddf5d399", null ], [ "$styles", "user__get__settings_8php.html#a920c320068535c09e154c6707eb42ded", null ] ];1-10 (function () { "use strict"; // [it] ItemCfct var itemCfctApp = angular.module("it.ItemCfct", ["it.ItemCfct.controller", "it.ItemCfct.service"]); angular.module("it.ItemCfct.controller", [] ); angular.module("it.ItemCfct.service", [] ); itemCfctApp.config(["$stateProvider", function ($stateProvider) { $stateProvider.state("app.itItemCfct", { url : "/02it/itItemCfct?menu", views : { contentView : { templateUrl : "app/contents/02it/it01ItemCfct/templates/it.ItemCfct.tpl.html", controller : "it.ItemCfctCtrl", resolve : { resData: ["AuthSvc", "$q", "UtilSvc",function (AuthSvc, $q, UtilSvc) { var defer = $q.defer(), resData = {}; AuthSvc.isAccess().then(function (result) { resData.access = result[0]; var mngMrkParam = { procedureParam: "USP_IT_01ITEMCFCT_MNGMRK_GET" } $q.all([ UtilSvc.getList(mngMrkParam).then(function (res) { return res.data.results[0]; }) ]).then(function (result) { resData.mngMrkList = result[0]; defer.resolve( resData ); }); }); return defer.promise; }] } } } }); }]); }()); client/src/components/InputItems/DocumentType.js import { Form, Select } from 'antd'; const { Option } = Select; function DocumentType({ setState }) { const onSelect = (value) => { setState({ document_type: value }); }; return ( ) } export default DocumentType;/* */ //Vanilla javascript function detectmob() { if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ) { return true; } else { return false; } } var device = detectmob(); if (!device) { console.log('Desktop detected'); NProgress.start(); } else { console.log('Mobile detected'); } //jquery $(document).ready(function() { detectmob(); NProgress.done(); // on load finished $(window).load(function() { // select element and fade it out $('.overlay').fadeOut(); }); $(".button-collapse").sideNav(); }); // Import the screens import { createBottomTabNavigator, createStackNavigator, } from 'react-navigation'; import tabBarIcon from './components/tabBarIcon'; import FeedScreen from './screens/FeedScreen'; import NewPostScreen from './screens/NewPostScreen'; import SelectPhotoScreen from './screens/SelectPhotoScreen'; // Import React Navigation const navigator = createBottomTabNavigator( { Feed: { screen: FeedScreen, navigationOptions: { tabBarIcon: tabBarIcon('home'), tabBarLabel: null, }, }, Photo: { screen: SelectPhotoScreen, navigationOptions: { tabBarIcon: tabBarIcon('add-circle'), }, }, }, { tabBarOptions: { showLabel: false, activeTintColor: 'black', inactiveTintColor: 'gray', }, }, ); const uploadNavigator = createStackNavigator({ Main: { screen: navigator, navigationOptions: () => ({ title: 'Instaham 🐷' }), }, NewPost: NewPostScreen, }); // Export it as the root component export default uploadNavigator; export { default as PageContent } from './PageContent' export { default as PageHeader } from './PageHeader' export { default as PageToolbar } from './PageToolbar'problem-a/src/About.js import React from 'react'; function AboutPage() { return (

      About Us

      Here is some information about us. Lorem ipsum dolor sit amet, consectetur adipisicing.

      Curabitur blandit tempus porttitor. Nullam quis risus eget urna mollis ornare vel eu leo. Nullam id dolor id nibh ultricies vehicula ut id elit.

      Veniam dolorem cupiditate tenetur placeat nulla repellat dicta maxime architecto blanditiis non facere nesciunt quae animi quam quidem ullam, suscipit nisi ipsam voluptatem accusamus necessitatibus itaque autem in, sunt similique.

      In mollitia cumque sapiente ducimus quo labore magni qui quas aperiam, voluptatibus nesciunt dicta enim dignissimos doloribus tempora iusto commodi alias recusandae tempore beatae atque? Totam cum et, perferendis itaque.

      Etiam porta sem malesuada magna mollis euismod. Cras mattis consectetur purus sit amet fermentum. Aenean lacinia bibendum nulla sed consectetur.

      ); } function ResourcesPage() { return ( ); } export default AboutPage; export {AboutPage, ResourcesPage };RagOfJoes/spoonfed-client import * as yup from 'yup'; export const schema = yup.object().shape({ avatar: yup.string().ensure().url('Must be a valid url'), bio: yup.string().max(120, 'Must not exceed 120 characters'), username: yup .string() .ensure() .strict(true) .required('* Required') .trim('Cannot contain spaces') .min(4, 'Must have atleast 4 characters') .max(16, 'Must not exceed 16 characters') .matches(/^[a-zA-Z0-9-]{4,16}$/, { message: 'Cannot contain special characters' }), }); require('./Define') const lodash = require('lodash') /** * Assigns own and inherited enumerable string keyed properties of source objects to the destination object for all destination properties that resolve to undefined. Source objects are applied from left to right. Once a property is set, additional values of the same property are ignored. * @global * @function Merge * @param {(object|array)} target * @param {...(object|array)} sources * @return {(object|array)} target */ Define(global, 'Merge', lodash.defaults) 'use strict'; var Backbone = require('backbone'); var dataStore = require('../lib/data-store'); var Item = require('./inventory'); var Armor = require('./armor'); var Weapon = require('./weapon'); var InventorySet = Backbone.Model.extend({ urlRoot: '/inventorset', schema: { weapon: function(){ return ['manyToMany', Weapon]; }, armor: function(){ return ['manyToMany', Armor]; }, item: function(){ return ['manyToMany', Item]; } } }); InventorySet.prototype.sync = dataStore(InventorySet); module.exports = InventorySet;1-10 var BlacksmithFilters = angular.module('BlacksmithFilters'); BlacksmithFilters.filter('projects', function() { function filter(projects, arg) { var i, j; var isOK; var out = []; var filter; if(arg !== null && typeof arg === 'object') { filter = arg; } else { filter = {}; } for(i in projects) { isOK = true; for(j in filter) { if(filter[j] != projects[i][j]) { isOK = false; break; } } if(isOK) { out.push(projects[i]); } } return out; }; return function(input, type, category) { var arg = {}; if(type) { arg.type = type; } if(category) { arg.category = category; } return filter(input, arg); } }); BlacksmithFilters.filter('jenkins', function(projectsFilter) { return function(input, category) { return projectsFilter(input, "jenkins", category); } }); BlacksmithFilters.filter('sonar', function(projectsFilter) { return function(input, category) { return projectsFilter(input, "sonar", category); } }); Anandsagar1/IBMServices-github var _24 = { elem: 'svg', attrs: { xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 24 24', width: 24, height: 24, }, content: [ { elem: 'path', attrs: { d: 'M6.8 11.2c-1.8 0-3.2 1.7-3.2 3.3 0 1.5 1.5 3.2 3.2 3.2H10v1.5H6.8C4.6 19.2 2 17 2 14.5s2-4.8 4.8-4.8h12.4l-3-3 1.1-1.1 4.8 4.8-4.8 4.8-1.1-1.1 3-3H6.8z', }, }, ], name: 'redo', size: 24, }; export default _24; const {resolve} = require('path'); const root = resolve(__dirname, '../../'); module.exports = { collectCoverage: true, globalSetup: '/jest/test-setup.ts', rootDir: root, testMatch: ['/src/**/*.test.ts'], testPathIgnorePatterns: ['/src/tests-with-chain'], testEnvironment: 'jsdom', preset: 'ts-jest', transform: { '^.+\\.ts$': 'ts-jest' }, globals: { GIT_VERSION: 'jest-GIT_VERSION', GIT_COMMIT_HASH: 'jest-GIT_COMMIT_HASH', GIT_BRANCH: 'jest-GIT_BRANCH' } }; 0 import React from 'react' import { List } from 'semantic-ui-react' const AnswerItem = (props) => ( {props.answer} ) export default AnswerItem /*! * remark (http://getbootstrapadmin.com/remark) * Copyright 2015 amazingsurge * Licensed under the Themeforest Standard Licenses */ (function(document, window, $) { 'use strict'; var Site = window.Site; $(document).ready(function($) { Site.run(); Waves.attach('.list-group > a:not(.disabled)', ['waves-block', 'waves-classic']); }); })(document, window, jQuery); import React from "react" import Layout from "../components/Layout" import Particle from "../components/Particle" import IntroContent from "../elements/introContent"; import Portfolio from "../components/Portfolio"; import Footer from "../components/Footer"; const IndexPage = () => ( <>