�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  �<   �� ����,�,�P<�<R<R<��a<hB���%+29AIPX`gnu|�����������������%-4;CKS[bjpx�����������������#+19@GOV]dkqy������������������#*2:BHPX`gnu}�����������������%-5=CIQX`gow�����������������&-4<CKSZaiqy�����������������$,3;CJRZ`how~����������������#)17?GOW^fnv~����������������� '/6=DLT\dkrz�����������������   " ) 0 7 ? G N V ] d l r z � � � � � � � � � � � � � � � � �     % , 4 ; C K R Z a h o v } � � � � � � � � � � � � � � � � �    ! ( 0 6 = E M U [ c j r y � � � � � � � � � � � � � � � � � �    ! ( / 6 > F N V ] e l s z � � � � � � � � � � � � � � � � �    ! ) 1 7 ? F M T [ b j r y � � � � � � � � � � � � � � � � � � '.5=DKQYahpx����������������� !(07>FNV^dls{������������������$,3:BJRYafnv~�����������������%,49@HOV^emu{������������������$,19AIQX_gnt{������������������$,4;CKS[cjrz~����������������� "*19AHNV]cks{�����������������  '.5<DKRZaipw���������������� &-3;CKRZbjrz������������������ #+3:BIQX`hpx������������������$,4;BJRYaiqx����������������� &.6>EMU]emu}������������������ ")/7>ELS[biqy������������������&-5<CKS[bgow}�����������������  '.6>ELT[bipx������������������2556610250675916516613113336706682018956319347477720051351100378112897358460513613011321103787968628133668625811435786638666181168229335570156278483670990117842917408780924167363274161667074815704763129579211441454417143264140162901939015248520441510192018387327114606711446479711642812214788710850562568450957139011600991116188469186713021371531343195611277946691900613910063462561614922979392702551758691422513065853881810365416037844941666415387456704809382347612089924351441224201551748221847124467728802759238899705642059284927934265772422654127764514990681043795585150248008122184465636539315137319523221111924228221402150794284189161453094874279741222404810051251142017571270231771214841739538412005454145010709639250996610816657324350721352922493241879069169138156571774480078686322805961830752074892321219196112318887149773297825441847145014652684165006788151343805493963824511176210466071382947716171158283838232902561484738469435681883420494818124147098122499501074347414742224712417113157575761467019900442979181862589113024270921973810279031621201011525703182977351382708264679293901717095302132186217214642916511511066195169741551232621313163880919062204907099859612006691248629315432275820269719824334136105901993640033613267216677157203141559246311438165151003461928927914973154183103331668491919032514238045363206311389703350373991026149013898146702007477073271961338910485139134408181432269119763845151719405578987342862549921761894882435187893114686635355163858421230037325377221587174918242214132640616760081128981928370914487618060158241998926871607091658095636240291452145112982722954568318343446184401807589811423726270367931169814394014761983010021018831383301537600961486891297862034956729176879671592401914001388114337521498895319414733282886516140563155814084598230171802978609459074157568788570154546755141300720342497812869778184535561969752613610932229175215451656161607071247251517228773154387307198737371300710471845123960213680771213858513782128472882853112195591583977344916116023464301176949433883228777889892349881730689343104861316887993258331787384917102666236560939284008107675184566561373089017217213136410914645589566123712172065167856915856571855967415664352421389419053212181813473035417172830441858300816332394131937451563721128130157271287121949121505561217695759133934313202585141755565567874649183519469194424695150937881602987371516521907095394842988157067143339641211571095084510732441113228451780494478879516560405239967212631486620205141659061613107063442888059266137657375799477100836207352627165998464739539130704408785209872739918453529380692732478261303578763891271463233918553807107158412763041212172934766353701964353669276832045076413709919778466901491632815125702171126876107981338813492951384128276539414616488710466436311081631679688055503281393055513323730198259061865395410874989381497012664051113508355193635694711323902016652129109594249868431199413551784901110648889232681943421672212872763051402826542433271578224526043239917821826095746915021300825312879274819713211989011419663418715544114874327476646782647519782116354699487779061084034497128136811582759531477714215455937179675891277801362878271920282271752685859037427094817403162121918811415896217182192174022561509529211680991348424513617297142804513103930129253821121802222256611707543126296338758390125459502804450190604227434112481038159232891146338196399017035281396717964547205607725277724479790111869027017752176104787074296459743655079104170612271732273187423513427881172864536712685785996046941796628134623681473766414784525222333361377031091786343416473231625140268114059880157113781827326726201016106308129333461471918780665942550613707627143515285149086128891381751645197819021507381412051846218261364958853130351905391312446623061485108854968383185425611275330771376922482130652380761517083976001201333187518101129158382692356632189100535136727173200349660661463137812447265117955101754618512069449805792147892173141774188800411093545819309023114816294266106272077022214134799259647952897495513542750163552941637046239279502479511685576818071038478350828358341931720719046179692690701744518086253182497094240839956321916610669163686141120941927482811493839074227183669261018105517775288152225447056932909643615686735568258141332037692136196295611756996336016369507697484938896109109049774099856911215265433381420663154609031894772096749031656575768010797705604186169471166995791311849659314858097504264169382604090344175335531048657181787214914650173123016468229393637515019215478519105887369955181160836955704287957951432285510560519144849236858508665712039741141202622329167501216482915445536174196132642241259434524312194634851032641211530626140088192479024184431816034616103782769772079022623881340186583552541865175013857594401359439418099331162797941732526175530076573838239550345366021470465647527978809694728284284753281729245778877181022564859847121999808174218521604978874950281959762019042309170869521310699018930921229257710380968182673821073122880237116613157739427314476176289725873971215342217015195821280836961227462261250309611771570277057086744291398714584133971749623118326126144487491239245230396461315733581141781621575018625377833111288609618591070682401960816819183899164719731142569244522461019225318651180172108241050749826922797934421752247515031795558507278248321914908113155505171113409103044111612092356798641776114247402127299764799662297676081425548972250485035837904771574598535692065532294150610756484567131684575846900755576113707107108313017758995448627310912819133068821268764128325551038306018181225193972631576263883582751297988062854752559842114738771673425416193658796515613292481461347380385507477727314571183731681743395616860202323932718020764150190781923078719063945134860573156373143303643048138156989502248720166645004466474155497602979664148908713870056706147593482919372090882496614165466922197230291518272925750178121679161195420711104110103400401657065210461121145534780834031065941586597741793333811245368187817791007010719428751260588814195611303858145792339736113140114199706492158975856694139721560419592855100760191693920715099115766633613777261603737017653378105065436420042137515692972771834637014614746356181118716911020029216946807803629016455741117267551681258811506231052239615822050151070536135893100521281867886454529638738446194498221089848713727186137890751347014613717426208637012357135806031772016615936858180344491305851252004110787301145262716447963105937643464886106776261006821615052478107212161164420215407846105796741946757983364849833799228077581892704211865601650798708832956184206364649471439732410741115238763237476912547978123624501369707583248328662756139612691172228758739089993857749553170850418344945666924762128141335619117729412008114849317010518408136758461642889519091623145570453645217606609785367716015641964133126869401060563019407786199350755131292108119619196234985921788201701385382188146431532055413498126189306731589939792269201770431733235823460600130800281173722517777551124909412917125538721748693591731869532384028122188392771301857113938971758256612229003826543191131002535579357418217456491126024465260555113815713894861154693735642259994014320809416827698138903314405563354992716429709158470465381889404006817790879300659689700945868157443911416154997153396669132155157834498786423159095521489796531893017183221075765173697654894208674996036273551528404412472765850267333226913977805���7L�PR�U�[^�g�h�m�o������<�����*�+�G_CF�IUZYFc�e�g�ncu���Z���N�����%�������� ��'�-c4�8nB6H~OCRV�\he�i�j�~����c�P���~���}�+4�<�GKI8K^T\ ]e�fr$wT�:�ņx���X�ݤs������9���/g   ]-3/�0W:�<g>5A�M�aH�ϩ��G�f�'���;�'K�h6�8�S;\r^Ttu�{y���2�?�P����z�����@�DuHN�W>�ҷQ�����t��� / \�)�-�;qP0WQ`�` q�waz ��ۑ�����B�+�F���X���� `+ !3 {4 6 �@ EH �� � �� E� � �� �� c� ?� e� S� �� �� '� q� M  Q � � s �5 O7 <9 oQ �R �\ �a M� �� 9� �� Q� v! �: jL rb �d k� �� �� *� +� �� � �) �8 < G �e �~ �� � �� p� �� � H� �� ?� �� M  9 %$  &��fr5�K�{-}Ǒ���r�������E�r�<�������m�7� �ة��>���\�9�4�)������G3+�3�6EU�]�j�y�������z���P�O�U���b��E: :�g�N  $)�<�G]O�P�S=ZK](_�pw�w�-���A����9�J�P�aJl�n���ْD���{�ʨ�����m�O�^�����?����f�$� 3�9�:%C|I�M"R"8�B�I\�j5}�څǐ������Q�����;�F��$Z26*J�RO������� ��'�p�o���'�^!�%3*_0�:�=y@�E�I�MYY_g�l�����G�V�d��� �����������a�2���Z�3r2E.G0�3:9�CzD�Qa�jzmpw} ~q�����s���?������f������S&����IFJ�L+�r�%������.��jtz�|�c���������+�=�u v S u x �� � � � �� X� �� �� � =� �� �� �� >� �� 1!�!�!�(!AA!�K!�Z!]!��!�!��!z�!i""'C"�H"�J"O"�O"cS"�b"�k"Tq"�"l�"t�"`�"��"}�"V�"W�"B�"�"��"��"��"��"88#S;#>?#RC#rI#6j#�r#r�#�#ҧ#��#e�#V�#:�#��#"�#��#��#h$�$�$ '$/$�1$�4$O:$ p$�$��$Õ$�$=�$��$D%�%f %Q%l%41%hK%wN%�P%�T%̔%��%��%��%J�%�%x�%1�%e�%W�%�%�&�&� &M'&y?&�4'�='F'0N'T]'�e'�o'�v'��'��'z�'�'k�']�'=�'��'��'��'��'L�'��'(m2(�3(D4('9(>N(AO(��(Ì(b�)ϖ)Η)J�)̹))�)�)��))�)6�)D�)R�)'�)�)��)��)��)*�*] *#*-'*n:*R;*?*!B*�G*�J*FX*'�*e�*��*�*9�*j�*��*��*�*i�*��*��*��*�++�2+�7+�9+�E+�H+�u+؅+_�+�+է+��+U�+��+��+U�+��+0�+��+�+k ,�,�,�,�,,�3,S@,fD,WF,TK,�L,�N,�Q,�^,�i,�l,p,�v,�},�,;�,,�,I�,&�,>�,8�,��,��,��,!�,�-H-�A-�D-T-�a-�p-g�-��.R�.V�.��.��.4�.t�.��.�/L /W./.8/�D/BU/^/�^/�c/2�/��/t�/��/��/��/��/��/60�0@'0j/0�50�K0�M0�[0sb0�0w�1ԇ1U�1 �1}�1��1H�1�1~�1I�1��1+�1��1�1�1j 2�2X$2�L2�P2oU2�2�2��2��2�2��2C�2k�2R�2w�2{�2y3 3363�:3,C3HP3,V3�W3l}3G�3/�3F�3�3�3��3(�3��3��3��3h�3��3�3�4O 4>4�-4Q84�94\4�e4�h42j4�l4]w4y4J65�95o<5�A5eK5P5��5��5��5�5��5��5ȶ5d�5��5��5��5�5?�5�5��566O6 !6�.6�/6�26�365A6F6�e6�k6��6��6v�6��6Ш6��6��6��6�7(77�7��7W�7��7�7�7��7��7��7��7sE8F8gf8wi8a�8�8��8K�8W�8~9�949�9� 9�99�9�59�A9jO94W9d9�e9qf9�t9�{9!|9�|9�9|�9f�9��9��9��9��9�9��9'�9 �9::�:F:�:�):PJ:EX:0\:�g:}q:�:��:_�:�:��:�:q�:ۨ:a�:~�: �:r�:��: �:z�:��:�;E;� ;� ;B;~%;F+;�,;�-;�.;U/;�/;�@;P;�];�`;�m;�p;��;��;��;�;�;ՙ;ң;߶;��;Һ;��;��;��;t�;�;��;��; <� <� <�<src/main/java/org/usfirst/frc3711/deepspace/commands/util/Commands.java0 package org.usfirst.frc3711.deepspace.commands.util; import com.ctre.phoenix.motorcontrol.ControlMode; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.CommandGroup; import edu.wpi.first.wpilibj.command.InstantCommand; import edu.wpi.first.wpilibj.command.Subsystem; import org.usfirst.frc3711.deepspace.Robot; import org.usfirst.frc3711.deepspace.subsystems.TalonSubsystem; import java.util.function.BooleanSupplier; public class Commands { public static Command setpointCommand(final String name, final TalonSubsystem subsystem, final double setpoint, final ControlMode mode) { return new SetpointCommand(name, subsystem, setpoint, mode); } public static Command positionSetpointCommand(String name, TalonSubsystem subsystem, double setpoint) { return new SetpointCommand(name, subsystem, setpoint, ControlMode.Position); } // public static Command motionMagicSetpointSetpointCommand(String name, TalonSubsystem subsystem, double setpoint) { // return new SetpointCommand(name, subsystem, setpoint, ControlMode.MotionMagic); // } static class SetpointCommand extends TalonSubsystemCommand { final double setpoint; final ControlMode mode; SetpointCommand(String name, TalonSubsystem subsystem, double setpoint, ControlMode mode) { super(name, subsystem); this.setpoint = setpoint; this.mode = mode; } @Override protected void initialize() { if (ControlMode.MotionMagic.equals(mode)) { subsystem.talon.selectProfileSlot(0, 0); } else if (ControlMode.Position.equals(mode)) { subsystem.talon.selectProfileSlot(1, 0); } } @Override protected void execute() { subsystem.talon.set(mode, setpoint); } } public static Command enableCurrentLimitCommand(TalonSubsystem subsystem) { return new CurrentLimit(subsystem, true); } public static Command disableCurrentLimitCommand(final TalonSubsystem subsystem) { return new CurrentLimit(subsystem, false); } private static class CurrentLimit extends InstantCommand { final TalonSubsystem subsystem; final boolean enable; CurrentLimit(TalonSubsystem subsystem, boolean enable) { super(subsystem.getName() + "CurrentLimit" + enable); requires(subsystem); this.subsystem = subsystem; this.enable = enable; } @Override protected void initialize() { if (enable) subsystem.enableCurrentLimiting(); else subsystem.disableCurrentLimiting(); } } public static Command disableAll() { return new InstantCommand("Disable All") { { setRunWhenDisabled(true); for(Subsystem s : Robot.subsystems){ requires(s); } } @Override protected void execute() { Robot.disableAll(); } }; } public static Command disableCommand(final TalonSubsystem subsystem) { return new DisableTalon(subsystem); } static class DisableTalon extends InstantCommand { final TalonSubsystem subsystem; DisableTalon(TalonSubsystem subsystem) { super(subsystem.getName() + "Disable"); this.subsystem = subsystem; requires(subsystem); setRunWhenDisabled(true); } @Override protected void initialize() { subsystem.disable(); } } public static Command runWhenTrue(Command c, BooleanSupplier guard){ return new Command(){ @Override protected boolean isFinished() { return guard.getAsBoolean(); } @Override protected void end() { c.start(); } }; } public static Command delayUntil(String name,BooleanSupplier guard){ return new Command(name) { @Override protected boolean isFinished() { return guard.getAsBoolean(); } }; } public static Command delayUntil(BooleanSupplier guard){ return delayUntil("DelayUntil",guard); } public static Command constantOutput(TalonSubsystem subsystem, double output){ return new ConstantOutput(subsystem, output); } static class ConstantOutput extends Command { final TalonSubsystem subsystem; final double output; ConstantOutput(TalonSubsystem subsystem, double output) { super(subsystem.getName() + "Hold"); this.subsystem = subsystem; this.output = output; requires(subsystem); } // Called just before this Command runs the first time @Override protected void initialize() { } // Called repeatedly when this Command is scheduled to run @Override protected void execute() { subsystem.talon.set(ControlMode.PercentOutput, output); } // Make this return true when this Command no longer needs to run execute() @Override protected boolean isFinished() { return false; } // Called once after isFinished returns true @Override protected void end() { } } } package edu.mayo.mprc.scaffold.report; import com.google.common.base.Joiner; import edu.mayo.mprc.MprcException; import java.io.Serializable; import java.util.Comparator; final class LineComparator implements Comparator, Serializable { private static final long serialVersionUID = 20101221L; private static final String ASCENDING = "a"; private static final String INTEGER = "i"; private int[] positions; private String[] directions; /** * Initialize the comparator to compare given items of the list in given order. * * @param columnsRead Names of the columns as they are being read * @param columns List of column names to be compared to each other. * @param directions Direction of the comparison, 'a' stands for ascending, 'd' stands for descending. */ LineComparator(final String[] columnsRead, final String[] columns, final String[] directions) { if (columns.length != directions.length) { throw new MprcException("The list comparator is not set up correctly."); } this.directions = directions.clone(); positions = new int[columns.length]; for (int i = 0; i < columns.length; i++) { boolean found = false; for (int j = 0; j < columnsRead.length; j++) { if (columnsRead[j].equals(columns[i])) { positions[i] = j; found = true; break; } } if (!found) { throw new MprcException("Sorted column " + columns[i] + " is not present in the list of columns being read: " + Joiner.on(',').join(columnsRead)); } } } @Override public int compare(final String[] o1, final String[] o2) { for (int i = 0; i < positions.length; i++) { final int index = positions[i]; final int comparison; if (directions[i].endsWith(INTEGER)) { // Numeric comparison = Integer.valueOf(o1[index]).compareTo(Integer.valueOf(o2[index])); } else { comparison = o1[index].compareTo(o2[index]); } if (comparison != 0) { return directions[i].startsWith(ASCENDING) ? comparison : -comparison; } } return 0; } } JamesHare/RabbitMQ package com.jamesmhare.rabbitmqsubscriber.BasicReceiver; /** * This is a class to hold the constants for the {@link BasicReceiverImpl} * class. * * @author * */ public class BasicReceiverConstants { public final static String QUEUE_NAME = "hello"; public final static String HOST_NAME = "localhost"; } 0 /* * blanco Framework * Copyright (C) 2004-2010 * * This library 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 2.1 of the License, or (at your option) any later version. */ package blanco.restautotest; import blanco.cg.BlancoCgObjectFactory; import blanco.cg.BlancoCgSupportedLang; import blanco.cg.valueobject.BlancoCgClass; import blanco.cg.valueobject.BlancoCgSourceFile; import blanco.restautotest.constants.BlancoRestAutotestConstants; import blanco.restautotest.message.BlancoRestAutotestMessage; import blanco.restautotest.resourcebundle.BlancoRestAutotestResourceBundle; import blanco.restautotest.valueobject.BlancoRestAutotestInputResultFieldStructure; import blanco.restautotest.valueobject.BlancoRestAutotestTestCaseData; import blanco.restautotest.valueobject.BlancoRestAutotestTestCaseFieldStructure; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.util.DefaultIndenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * バリューオブジェクト用中間XMLファイルから Javaソースコードを自動生成するクラス。 *

* blancoValueObjectの主たるクラスのひとつです。 * * @author * @author 2017.09.01 */ public class BlancoRestAutotestXml2JavaClass { /** * メッセージ。 */ private final BlancoRestAutotestMessage fMsg = new BlancoRestAutotestMessage(); /** * blancoValueObjectのリソースバンドルオブジェクト。 */ private final BlancoRestAutotestResourceBundle fBundle = new BlancoRestAutotestResourceBundle(); /** * 入力シートに期待するプログラミング言語 */ private int fSheetLang = BlancoCgSupportedLang.JAVA; /** * 内部的に利用するblancoCg用ファクトリ。 */ private BlancoCgObjectFactory fCgFactory = null; /** * 内部的に利用するblancoCg用ソースファイル情報。 */ private BlancoCgSourceFile fCgSourceFile = null; /** * 内部的に利用するblancoCg用クラス情報。 */ private BlancoCgClass fCgClass = null; /** * 自動生成するソースファイルの文字エンコーディング。 */ private String fEncoding = null; public void setEncoding(final String argEncoding) { fEncoding = argEncoding; } private boolean fIsXmlRootElement = false; /** * ソースコード生成先ディレクトリのスタイル */ private boolean fTargetStyleAdvanced = false; public void setTargetStyleAdvanced(boolean argTargetStyleAdvanced) { this.fTargetStyleAdvanced = argTargetStyleAdvanced; } public boolean isTargetStyleAdvanced() { return this.fTargetStyleAdvanced; } private boolean fVerbose = false; public void setVerbose(boolean argVerbose) { this.fVerbose = argVerbose; } public boolean isVerbose() { return this.fVerbose; } private int testcaseMax = 0; /** * バリューオブジェクトを表現する中間XMLファイルから、Javaソースコードを自動生成します。 * * @param argDirectoryTarget ソースコード生成先ディレクトリ * @throws IOException 入出力例外が発生した場合 */ public void process( final File argDirectoryTarget, final List argAllTestCaseData) throws IOException { // 得られた情報からJavaソースコードを生成します。 if (BlancoRestAutotestUtil.isOutputJson) { testCaseData2Json(argDirectoryTarget, argAllTestCaseData); } } public void testCaseData2Json( final File argDirectoryTarget, final List argAllTestCaseData ) throws JsonProcessingException { // 従来と互換性を持たせるため、/mainサブフォルダに出力します。 final File fileBlancoMain = new File(argDirectoryTarget.getAbsolutePath()); /* tueda DEBUG */ System.out.println("testCaseData2Json : " + fileBlancoMain.getAbsolutePath()); System.out.println("targetFilePath: " + argDirectoryTarget.getAbsolutePath()); for (BlancoRestAutotestTestCaseData testCaseData : argAllTestCaseData) { ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); DefaultPrettyPrinter printer = new DefaultPrettyPrinter(); printer.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE); String requestJson = mapper.writer(printer).writeValueAsString(testCaseData.getInput()); System.out.println("### " + testCaseData.getExpect()); String responseJson = mapper.writer(printer).writeValueAsString(testCaseData.getExpect()); String requestFileName = testCaseData.getSimpleInputId() + "-" + testCaseData.getCaseId() + ".json"; String responseFileName = testCaseData.getSimpleExpectId() + "-" + testCaseData.getCaseId() + ".json"; makeJsonFiles(requestFileName, argDirectoryTarget, requestJson); makeJsonFiles(responseFileName, argDirectoryTarget, responseJson); System.out.println("JSON: " + requestJson); System.out.println("JSON: " + responseJson); } } public void makeJsonFiles(String fileName, File argDirectoryTarget, String jsonData) { File file = new File(argDirectoryTarget.getAbsolutePath()); if (!file.exists()) { file.mkdirs(); System.out.println("新規ディレクトリを作成しました。 FilePath : " + file.getAbsolutePath()); } try { File jsonFile = new File(argDirectoryTarget.getAbsolutePath() + "/" + fileName); PrintWriter printWriter = new PrintWriter(new BufferedWriter( new OutputStreamWriter(new FileOutputStream(jsonFile), BlancoRestAutotestUtil.fileEncoding))); printWriter.print(jsonData); printWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } jahmm/src/jahmm/calculators/InputForwardBackwardScaledCalculatorBase.java package jahmm.calculators; import jahmm.InputHmm; import jahmm.observables.InputObservationTuple; import jahmm.observables.Observation; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import jutils.probability.ProbabilityUtils; import jutlis.tuples.Tuple3; import jutlis.tuples.Tuple3Base; public final class InputForwardBackwardScaledCalculatorBase> extends InputForwardBackwardCalculatorBase { private static final Logger LOG = Logger.getLogger(InputForwardBackwardScaledCalculatorBase.class.getName()); public static final InputForwardBackwardScaledCalculatorBase Instance = new InputForwardBackwardScaledCalculatorBase(); private InputForwardBackwardScaledCalculatorBase() { } private double computeProbability(double[] ctFactors) { double lnProbability = 0.; int T = ctFactors.length; for (int t = 0; t < T; t++) { lnProbability += Math.log(ctFactors[t]); } return Math.exp(lnProbability); } /** * Computes the probability of occurrence of an observation sequence given a * Hidden Markov Model. The algorithms implemented use scaling to avoid * underflows. * * @param hmm A Hidden Markov Model; * @param oseq An observations sequence. * @param flags How the computation should be done. See the * {@link ForwardBackwardCalculator.ComputationType}. The alpha array is * always computed. * @return The probability of the given sequence of observations. */ @Override public double computeProbability(THmm hmm, Collection flags, List> oseq) { if (oseq.isEmpty()) { throw new IllegalArgumentException(); } int t = oseq.size(); double[] ctFactors = new double[t]; double[][] alpha = null, beta = null; alpha = computeAlpha(hmm, oseq, ctFactors); if (flags.contains(ComputationType.BETA)) { beta = computeBeta(hmm, oseq, ctFactors); } return computeProbability(ctFactors); } /* Computes the content of the scaled alpha array */ /** * * @param * @param hmm * @param oseq * @return */ public double[][] computeAlpha(THmm hmm, Collection> oseq, double... ctFactors) { int T = ctFactors.length; int s = hmm.nbStates(); Iterator> seqIterator = oseq.iterator(); double[][] alpha = new double[T][s]; if (seqIterator.hasNext()) { InputObservationTuple observation = seqIterator.next(); for (int i = 0x00; i < s; i++) { alpha[0x00][i] = hmm.getPi(i) * hmm.getOpdf(i, observation.getInput()).probability(observation.getObservation()); } ctFactors[0x00] = ProbabilityUtils.scale(alpha[0x00]); for (int t = 1; t < T; t++) { observation = seqIterator.next(); for (int i = 0; i < s; i++) { double sum = 0.0d; for (int j = 0; j < s; j++) { sum += alpha[t - 1][j] * hmm.getAixj(j, observation.getItem1(), i); } alpha[t][i] = sum * hmm.getOpdf(i, observation.getInput()).probability(observation.getObservation()); } ctFactors[t] = ProbabilityUtils.scale(alpha[t]); } } return alpha; } /* Computes the content of the scaled beta array. The scaling factors are those computed for alpha. */ public double[][] computeBeta(THmm hmm, List> oseq, double... ctFactors) { int T = ctFactors.length; int s = hmm.nbStates(); double[][] beta = new double[T][s]; for (int i = 0; i < s; i++) { beta[T - 1][i] = 1.0d / ctFactors[T - 1]; } for (int t = T - 2; t >= 0; t--) { InputObservationTuple observation = oseq.get(t + 1); for (int i = 0; i < s; i++) { double sum = 0.; for (int j = 0; j < s; j++) { sum += beta[t + 1][j] * hmm.getAixj(i, observation.getItem1(), j) * hmm.getOpdf(j, observation.getInput()).probability(observation.getObservation()); } beta[t][i] = sum; beta[t][i] /= ctFactors[t]; } } return beta; } @Override public Tuple3 computeAll(THmm hmm, List> oseq) { if (oseq.isEmpty()) { throw new IllegalArgumentException(); } int t = oseq.size(); double[] ctFactors = new double[t]; double[][] alpha = computeAlpha(hmm, oseq, ctFactors); double[][] beta = computeBeta(hmm, oseq, ctFactors); double probability = computeProbability(ctFactors); return new Tuple3Base<>(alpha, beta, probability); } } package org.opensha.sha.cybershake.plot; import java.util.ArrayList; import java.util.NoSuchElementException; public enum PlotType { PDF("pdf"), PNG("png"), JPG("jpg"), JPEG("jpeg"), TXT("txt"), CSV("csv"); private String extension; private PlotType(String extention) { this.extension = extention; } public String getExtension() { return extension; } public static PlotType fromExtension(String extension) { extension = extension.toLowerCase(); for (PlotType t : PlotType.values()) if (t.getExtension().equals(extension)) return t; throw new NoSuchElementException("Unknown extension: "+extension); } public static ArrayList fromExtensions(ArrayList extensions) { return fromExtensions(extensions, null); } public static ArrayList fromExtensions(ArrayList extensions, ArrayList allowed) { ArrayList types = new ArrayList(); for (String extension : extensions) { PlotType type = fromExtension(extension); if (allowed == null || allowed.contains(type)) types.add(type); else throw new IllegalArgumentException("Type not allowed: "+type.getExtension()); } return types; } }package io.mateu.ui.core.client.views; import io.mateu.ui.core.shared.Data; import io.mateu.ui.core.shared.GridData; import io.mateu.ui.core.shared.UserData; public interface RPCView { GridData rpc() throws Throwable; default Data get(UserData user, Object id) throws Throwable { return null; } default String getViewTitle() { return null; } } package com.stumi.safesparsearray; import android.util.SparseBooleanArray; import org.junit.Assert; import org.junit.Test; import static org.hamcrest.core.Is.is; /** * @author stumpfb on 29/12/2016. */ public class SafeSparseBooleanArrayTest { @Test public void testEquals() throws Exception { SafeSparseBooleanArray safeSparseBooleanArray = new SafeSparseBooleanArray(); SafeSparseBooleanArray safeSparseBooleanArray2 = new SafeSparseBooleanArray(); Assert.assertThat(safeSparseBooleanArray.equals(safeSparseBooleanArray2), is(true)); } @Test public void testEqualsOld() throws Exception { SparseBooleanArray sparseBooleanArray = new SparseBooleanArray(); SparseBooleanArray sparseBooleanArray2 = new SparseBooleanArray(); Assert.assertThat(sparseBooleanArray.equals(sparseBooleanArray2), is(false)); } }package com.stanwind.wmqtt.auth.beans; import java.io.Serializable; /** * AuthBean 鉴权基础数据包装 * * @author : Stan * @version : 1.0 * @date : 2020-11-11 15:42 **/ public class AuthBean implements Serializable { private String instanceId; private String accessKey; private String secretKey; private String clientId; private String username; private String password; public String getInstanceId() { return instanceId; } public AuthBean setInstanceId(String instanceId) { this.instanceId = instanceId; return this; } public String getAccessKey() { return accessKey; } public AuthBean setAccessKey(String accessKey) { this.accessKey = accessKey; return this; } public String getSecretKey() { return secretKey; } public AuthBean setSecretKey(String secretKey) { this.secretKey = secretKey; return this; } public String getClientId() { return clientId; } public AuthBean setClientId(String clientId) { this.clientId = clientId; return this; } public String getUsername() { return username; } public AuthBean setUsername(String username) { this.username = username; return this; } public String getPassword() { return password; } public AuthBean setPassword(String password) { this.password = password; return this; } } src/main/java/com/cloudberry/cloudberry/topology/model/filtering/FilterExpression.java package com.cloudberry.cloudberry.topology.model.filtering; import com.cloudberry.cloudberry.topology.model.operators.LogicalOperator; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor public class FilterExpression { private LogicalOperator operator; private List expressions; // may be empty private List predicates; } package com.blamejared.crafttweaker.impl.recipe.handler.type.vanilla; import com.blamejared.crafttweaker.api.ingredient.IIngredient; import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler; import com.blamejared.crafttweaker.api.recipe.handler.IReplacementRule; import com.blamejared.crafttweaker.api.recipe.handler.helper.ReplacementHandlerHelper; import com.blamejared.crafttweaker.api.recipe.manager.base.IRecipeManager; import com.blamejared.crafttweaker.api.util.ItemStackUtil; import com.blamejared.crafttweaker.api.util.StringUtils; import com.blamejared.crafttweaker.platform.Services; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.ShapelessRecipe; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; @IRecipeHandler.For(ShapelessRecipe.class) public final class ShapelessRecipeHandler implements IRecipeHandler { @Override public String dumpToCommandString(final IRecipeManager manager, final ShapelessRecipe recipe) { return String.format( "craftingTable.addShapeless(%s, %s, %s);", StringUtils.quoteAndEscape(recipe.getId()), ItemStackUtil.getCommandString(recipe.getResultItem()), recipe.getIngredients().stream() .map(IIngredient::fromIngredient) .map(IIngredient::getCommandString) .collect(Collectors.joining(", ", "[", "]")) ); } @Override public Optional> replaceIngredients(final IRecipeManager manager, final ShapelessRecipe recipe, final List rules) { return ReplacementHandlerHelper.replaceNonNullIngredientList( recipe.getIngredients(), Ingredient.class, recipe, rules, newIngredients -> id -> new ShapelessRecipe(id, recipe.getGroup(), recipe.getResultItem(), newIngredients) ); } @Override public > boolean doesConflict(final IRecipeManager manager, final ShapelessRecipe firstRecipe, final U secondRecipe) { return Services.PLATFORM.doCraftingTableRecipesConflict(manager, firstRecipe, secondRecipe); } } java/java-tests/testData/psi/types/rawTypeInMethodArg/A.java1-10 import test.*; class A { public void method() { List l = new List(); List l1 = new List(); l1.putAll(l); } } 0 package com.cjs.threadTest; /** * 实现Runnable接口则很容易实现资源共享 */ public class ThreadTest3 implements Runnable { private String threadName; private int count=5; public ThreadTest3(String threadName) { this.threadName = threadName; } public void run() { for(int i=0; i<5; i++) { System.out.println(this.threadName + "线程正在执行 count=" + count--); try { Thread.sleep((int)Math.random() * 10); } catch(InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { ThreadTest3 threadTest1 = new ThreadTest3("thread1"); Thread thread1 = new Thread(threadTest1); Thread thread2 = new Thread(threadTest1); thread1.start(); thread2.start(); } /** * 从结果可以看出,两个线程不仅有同样的名字,还共享了count变量。实际上,在调用两个线程的start方法时, * 都是去调用 ThreadTest3实例的run方法,线程实例本身是没有run方法的,这样很轻松的就完成了资源共享。 * 需要注意的是,在实例化这两个线程实例时,必须传入同一个ThreadTest3实例,否则结果就和继承Thread类 * 的结果一样了。 */ } chengc017/brave package com.github.kristofa.brave.httpclient; import org.apache.http.HttpResponse; import com.github.kristofa.brave.ClientResponseAdapter; class ApacheClientResponseAdapter implements ClientResponseAdapter { private final HttpResponse response; public ApacheClientResponseAdapter(final HttpResponse response) { this.response = response; } @Override public int getStatusCode() { return response.getStatusLine().getStatusCode(); } } /* * Copyright (c) 2016 Couchbase, 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.couchbase.client.scala.transformers; import com.couchbase.client.core.deps.com.fasterxml.jackson.core.JsonGenerator; import com.couchbase.client.core.deps.com.fasterxml.jackson.core.JsonParser; import com.couchbase.client.core.deps.com.fasterxml.jackson.core.JsonToken; import com.couchbase.client.core.deps.com.fasterxml.jackson.core.Version; import com.couchbase.client.core.deps.com.fasterxml.jackson.databind.*; import com.couchbase.client.core.deps.com.fasterxml.jackson.databind.module.SimpleModule; import com.couchbase.client.scala.json.JsonArray; import com.couchbase.client.scala.json.JsonObject; import scala.collection.Iterator; import java.io.IOException; /** Tells Jackson how to produce [[JsonObject]] and [[JsonArray]]. */ public class JacksonTransformers { public static final ObjectMapper MAPPER = new ObjectMapper(); public static final SimpleModule JSON_VALUE_MODULE = new SimpleModule("JsonValueModule", new Version(1, 0, 0, null, null, null)); private JacksonTransformers() {} static { JSON_VALUE_MODULE.addSerializer(JsonObject.class, new JacksonTransformers.JsonObjectSerializer()); JSON_VALUE_MODULE.addSerializer(JsonArray.class, new JacksonTransformers.JsonArraySerializer()); JSON_VALUE_MODULE.addDeserializer(JsonObject.class, new JacksonTransformers.JsonObjectDeserializer()); JSON_VALUE_MODULE.addDeserializer(JsonArray.class, new JacksonTransformers.JsonArrayDeserializer()); MAPPER.registerModule(JacksonTransformers.JSON_VALUE_MODULE); } static class JsonObjectSerializer extends JsonSerializer { @Override public void serialize(JsonObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException { Iterator it = value.names().iterator(); jgen.writeStartObject(); while (it.hasNext()) { String name = it.next(); Object o = value.get(name); jgen.writeObjectField(name, o); } jgen.writeEndObject(); } } static class JsonArraySerializer extends JsonSerializer { @Override public void serialize(JsonArray value, JsonGenerator jgen, SerializerProvider provider) throws IOException { Iterator it = value.iterator(); jgen.writeStartArray(); while (it.hasNext()) { Object o = it.next(); jgen.writeObject(o); } jgen.writeEndArray(); } } static abstract class AbstractJsonValueDeserializer extends JsonDeserializer { private final boolean decimalForFloat; public AbstractJsonValueDeserializer() { decimalForFloat = Boolean.parseBoolean( System.getProperty("com.couchbase.json.decimalForFloat", "false") ); } protected JsonObject decodeObject(final JsonParser parser, final JsonObject target) throws IOException { JsonToken current = parser.nextToken(); String field = null; while(current != null && current != JsonToken.END_OBJECT) { if (current == JsonToken.START_OBJECT) { target.put(field, decodeObject(parser, JsonObject.create())); } else if (current == JsonToken.START_ARRAY) { target.put(field, decodeArray(parser, JsonArray.create())); } else if (current == JsonToken.FIELD_NAME) { field = parser.getCurrentName(); } else { switch(current) { case VALUE_TRUE: case VALUE_FALSE: target.put(field, parser.getBooleanValue()); break; case VALUE_STRING: target.put(field, parser.getValueAsString()); break; case VALUE_NUMBER_INT: case VALUE_NUMBER_FLOAT: Number numberValue = parser.getNumberValue(); if (numberValue instanceof Double && decimalForFloat) { numberValue = parser.getDecimalValue(); } target.put(field, numberValue); break; case VALUE_NULL: target.put(field, (JsonObject) null); break; default: throw new IllegalStateException("Could not decode JSON token: " + current); } } current = parser.nextToken(); } return target; } protected JsonArray decodeArray(final JsonParser parser, final JsonArray target) throws IOException { JsonToken current = parser.nextToken(); while (current != null && current != JsonToken.END_ARRAY) { if (current == JsonToken.START_OBJECT) { target.add(decodeObject(parser, JsonObject.create())); } else if (current == JsonToken.START_ARRAY) { target.add(decodeArray(parser, JsonArray.create())); } else { switch(current) { case VALUE_TRUE: case VALUE_FALSE: target.add(parser.getBooleanValue()); break; case VALUE_STRING: target.add(parser.getValueAsString()); break; case VALUE_NUMBER_INT: case VALUE_NUMBER_FLOAT: Number numberValue = parser.getNumberValue(); if (numberValue instanceof Double && decimalForFloat) { numberValue = parser.getDecimalValue(); } target.add(numberValue); break; case VALUE_NULL: target.add((JsonObject) null); break; default: throw new IllegalStateException("Could not decode JSON token."); } } current = parser.nextToken(); } return target; } } static class JsonArrayDeserializer extends AbstractJsonValueDeserializer { @Override public JsonArray deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { if (jp.getCurrentToken() == JsonToken.START_ARRAY) { return decodeArray(jp, JsonArray.create()); } else { throw new IllegalStateException("Expecting Array as root level object, " + "was: " + jp.getCurrentToken()); } } } static class JsonObjectDeserializer extends AbstractJsonValueDeserializer { @Override public JsonObject deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { if (jp.getCurrentToken() == JsonToken.START_OBJECT) { return decodeObject(jp, JsonObject.create()); } else { throw new IllegalStateException("Expecting Object as root level object, " + "was: " + jp.getCurrentToken()); } } } public static JsonObject stringToJsonObject(String input) throws Exception { return MAPPER.readValue(input, JsonObject.class); } public static JsonArray stringToJsonArray(String input) throws Exception { return MAPPER.readValue(input, JsonArray.class); } public static JsonArray bytesToJsonArray(byte[] input) throws Exception { return MAPPER.readValue(input, JsonArray.class); } public static JsonObject bytesToJsonObject(byte[] input) throws Exception { return MAPPER.readValue(input, JsonObject.class); } } wilsonvargas/ARMixareApp package org.ar.mgr.location; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; /** * This class will be used to start each location provider for 20 seconds * and they will then listen for locations. This class will check for updates for * the observer. * Using this method: http://stackoverflow.com/questions/3145089/ * * @author */ public class LocationResolver implements LocationListener { private String provider; private LocationMgrImpl locationMgrImpl; private LocationManager lm; public LocationResolver(LocationManager lm, String provider, LocationMgrImpl locationMgrImpl) { this.lm = lm; this.provider = provider; this.locationMgrImpl = locationMgrImpl; } @Override public void onLocationChanged(Location location) { lm.removeUpdates(this); locationMgrImpl.locationCallback(provider); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } } gburd/wave1-10 /** * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.wave.api.robot; /** * Checked exception when a robot cannot be reached via HTTP. * */ public class RobotConnectionException extends Exception { private final int statusCode; /** * Constructor with a detail message. * * @param message detail message for this exception. */ public RobotConnectionException(String message) { super(message); this.statusCode = 0; } /** * Constructor with a detail message and cause. * * @param message detail message for this exception. * @param cause the exception that caused this. */ public RobotConnectionException(String message, Throwable cause) { super(message, cause); this.statusCode = 0; } /** * Constructor with a detail message and status code. * * @param message detail message for this exception. * @param statusCode the status code returned by the robot. */ public RobotConnectionException(String message, int statusCode) { super(message); this.statusCode = statusCode; } /** @return the status code returned by the robot. */ public int getStatusCode() { return statusCode; } } src/main/java/com/shz/gift/utils/NotLeaderException.java package com.shz.gift.utils; import com.shz.gift.preps.IMember; public class NotLeaderException extends RuntimeException { private static final long serialVersionUID = -9199331764286009275L; //used for redirecting private IMember actualLeader; public NotLeaderException(IMember actualLeader) { super(); this.actualLeader = actualLeader; } public NotLeaderException() { super(); } public NotLeaderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public NotLeaderException(String message, Throwable cause) { super(message, cause); } public NotLeaderException(String message) { super(message); } public NotLeaderException(Throwable cause) { super(cause); } public IMember getActualLeader() { return actualLeader; } } slusek/OG-Platform /** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.component.factory.engine; import java.util.Map; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import com.opengamma.component.ComponentInfo; import com.opengamma.component.ComponentRepository; import com.opengamma.engine.marketdata.NamedMarketDataSpecificationRepository; import com.opengamma.financial.view.rest.RemoteNamedMarketDataSpecificationRepository; /** * */ @BeanDefinition public class RemoteNamedMarketDataSpecificationRepositoryComponentFactory extends AbstractRemoteComponentServerComponentFactory { @Override protected void initComponent(ComponentRepository repo, ComponentInfo info) { if (NamedMarketDataSpecificationRepository.class.isAssignableFrom(info.getType())) { NamedMarketDataSpecificationRepository repository = new RemoteNamedMarketDataSpecificationRepository(info.getUri()); repo.registerComponent(info, repository); if (isPublishRest()) { repo.getRestComponents().republish(info); } } } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code RemoteNamedMarketDataSpecificationRepositoryComponentFactory}. * @return the meta-bean, not null */ public static RemoteNamedMarketDataSpecificationRepositoryComponentFactory.Meta meta() { return RemoteNamedMarketDataSpecificationRepositoryComponentFactory.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(RemoteNamedMarketDataSpecificationRepositoryComponentFactory.Meta.INSTANCE); } @Override public RemoteNamedMarketDataSpecificationRepositoryComponentFactory.Meta metaBean() { return RemoteNamedMarketDataSpecificationRepositoryComponentFactory.Meta.INSTANCE; } @Override protected Object propertyGet(String propertyName, boolean quiet) { return super.propertyGet(propertyName, quiet); } @Override protected void propertySet(String propertyName, Object newValue, boolean quiet) { super.propertySet(propertyName, newValue, quiet); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { return super.equals(obj); } return false; } @Override public int hashCode() { int hash = 7; return hash ^ super.hashCode(); } //----------------------------------------------------------------------- /** * The meta-bean for {@code RemoteNamedMarketDataSpecificationRepositoryComponentFactory}. */ public static class Meta extends AbstractRemoteComponentServerComponentFactory.Meta { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-properties. */ private final Map> _metaPropertyMap$ = new DirectMetaPropertyMap( this, (DirectMetaPropertyMap) super.metaPropertyMap()); /** * Restricted constructor. */ protected Meta() { } @Override public BeanBuilder builder() { return new DirectBeanBuilder(new RemoteNamedMarketDataSpecificationRepositoryComponentFactory()); } @Override public Class beanType() { return RemoteNamedMarketDataSpecificationRepositoryComponentFactory.class; } @Override public Map> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- } package org.caotc.unit4j.core.constant; import com.google.common.collect.ImmutableSet; import lombok.experimental.UtilityClass; import org.caotc.unit4j.core.Alias; import org.caotc.unit4j.core.unit.BasePrefixUnit; import org.caotc.unit4j.core.unit.BaseStandardUnit; import org.caotc.unit4j.core.unit.CompositeStandardUnit; import org.caotc.unit4j.core.unit.Prefix; import org.caotc.unit4j.core.unit.type.BaseUnitType; /** * 单位常量类 * * @author caotc * @date 2019-04-28 * @since 1.0.0 */ @UtilityClass public class UnitConstant { /** * 米 最初(1793年):从北极至赤道经过巴黎的子午线长度的一千万分之一。法 过渡(1960年):氪-86原子在2p10和5d5量子能级之间跃迁所发出的电磁波在真空中的波长的1,650,763.73倍。 * 目前(1983年):光在1299,792,458秒内在真空中行进的距离。 */ public static final BaseStandardUnit METER = BaseStandardUnit .create(Alias.METER_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 克,实际上国际单位制中应该为千克 最初(1793年):最初法文名为grave,定义为在冰点下体积为一立方分米的纯水的重量(质量)/1000。 * 目前(1889年):国际千克原器的质量/1000。 */ public static final BaseStandardUnit GRAM = BaseStandardUnit .create(Alias.GRAM_ENGLISH_NAME.value(), BaseUnitType.MASS); /** * 秒 最初(中世纪):一天时长的86,400分之一。 过渡(1956年):1900年1月0日历书时12时算起的回归年时长的131,556,925.9747。 * 目前(1967年):铯-133原子基态的两个超精细能级之间跃迁所对应的辐射周期时长的9,192,631,770倍。 */ public static final BaseStandardUnit SECOND = BaseStandardUnit .create(Alias.SECOND_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 安培 最初(1881年):CGS电磁单位制中电流单位的十分之一。CGS电流单位的定义是,在半径为1厘米、长度为1厘米的圆弧上流通,并在圆心产生1奥斯特电场的电流。 * 目前(1946年):在真空中相距1米的两根横截面为圆形、粗度可忽略不计的无限长平行直导线,各通上相等的恒定电流,当两根导线之间每米长度所受力为2×10−7牛顿时,各导线上的电流定义为1安培。 */ public static final BaseStandardUnit AMPERE = BaseStandardUnit .create(Alias.AMPERE_ENGLISH_NAME.value(), BaseUnitType.ELECTRIC_CURRENT); /** * 开尔文 最初(1743年):摄氏温标将0 °C和100 °C分别定义为水的熔点和沸点。 过渡(1954年):273.16 K定义为水的三相点(0.01 °C)。 * 目前(1967年):水的三相点热力学温度的1/273.16。 */ public static final BaseStandardUnit KELVIN = BaseStandardUnit .create(Alias.KELVIN_ENGLISH_NAME.value(), BaseUnitType.TEMPERATURE); /** * 摩尔 最初(1900年):物质的克数等于其分子量时的数量。原 目前(1967年):物质所含的粒子数量相等于0.012千克碳-12所含的原子数量。 */ public static final BaseStandardUnit MOLE = BaseStandardUnit .create(Alias.MOLE_ENGLISH_NAME.value(), BaseUnitType.SUBSTANCE_AMOUNT); /** * 坎德拉 最初(1946年):整个辐射体在铂凝固温度下的亮度,定义为60新坎德拉每平方厘米。 目前(1979年):频率为5.4×1014赫兹的单色光源在特定方向辐射强度为1683W/sr时的发光强度。 */ public static final BaseStandardUnit CANDELA = BaseStandardUnit .create(Alias.CANDELA_ENGLISH_NAME.value(), BaseUnitType.LUMINOUS_INTENSITY); /** * 摄氏度 K */ public static final BaseStandardUnit CELSIUS_DEGREE = BaseStandardUnit .create(Alias.CELSIUS_DEGREE_ENGLISH_NAME.value(), BaseUnitType.TEMPERATURE); /** * 华氏度 K */ public static final BaseStandardUnit FAHRENHEIT_DEGREE = BaseStandardUnit .create(Alias.FAHRENHEIT_DEGREE_ENGLISH_NAME.value(), BaseUnitType.TEMPERATURE); /** * 1里=500米 */ public static final BaseStandardUnit CHINESE_MILE = BaseStandardUnit .create(Alias.CHINESE_MILE_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 一堂为10里 */ public static final BaseStandardUnit TANG = BaseStandardUnit .create(Alias.TANG_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 1里=150丈 */ public static final BaseStandardUnit ZHANG = BaseStandardUnit .create(Alias.ZHANG_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 1引=10丈 */ public static final BaseStandardUnit YIN = BaseStandardUnit .create(Alias.YIN_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 1丈=10尺 */ public static final BaseStandardUnit CHI = BaseStandardUnit .create(Alias.CHI_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 1尺=10寸 */ public static final BaseStandardUnit CUN = BaseStandardUnit .create(Alias.CUN_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 1寸=10分 */ public static final BaseStandardUnit FEN = BaseStandardUnit .create(Alias.FEN_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 1分=10厘 */ public static final BaseStandardUnit LI = BaseStandardUnit .create(Alias.LI_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 英寸 in */ public static final BaseStandardUnit INCH = BaseStandardUnit .create(Alias.INCH_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 英尺 ft */ public static final BaseStandardUnit FOOT = BaseStandardUnit .create(Alias.FOOT_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 码 yd */ public static final BaseStandardUnit YARD = BaseStandardUnit .create(Alias.YARD_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 英寻 fm */ public static final BaseStandardUnit FATHOM = BaseStandardUnit .create(Alias.FATHOM_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 链,锁 */ public static final BaseStandardUnit CHAIN = BaseStandardUnit .create(Alias.CHAIN_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 浪 */ public static final BaseStandardUnit FURLONG = BaseStandardUnit .create(Alias.FURLONG_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 英里 mi */ public static final BaseStandardUnit MILE = BaseStandardUnit .create(Alias.MILE_ENGLISH_NAME.value(), BaseUnitType.LENGTH); /** * 吨 */ public static final BaseStandardUnit TONNE = BaseStandardUnit .create(Alias.TONNE_ENGLISH_NAME.value(), BaseUnitType.MASS); /** * 分钟 */ public static final BaseStandardUnit MINUTE = BaseStandardUnit .create(Alias.MINUTE_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 小时 */ public static final BaseStandardUnit HOUR = BaseStandardUnit .create(Alias.HOUR_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 天,24小时 */ public static final BaseStandardUnit DAY = BaseStandardUnit .create(Alias.DAY_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 半天,12小时 */ public static final BaseStandardUnit HALF_DAY = BaseStandardUnit .create(Alias.HALF_DAY_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 周,星期,7天 */ public static final BaseStandardUnit WEEK = BaseStandardUnit .create(Alias.WEEK_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 年,以31556952秒为标准年 */ public static final BaseStandardUnit YEAR = BaseStandardUnit .create(Alias.YEAR_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 月,12分之一年 */ public static final BaseStandardUnit MONTH = BaseStandardUnit .create(Alias.MONTH_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 10年 */ public static final BaseStandardUnit DECADE = BaseStandardUnit .create(Alias.DECADE_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 100年 */ public static final BaseStandardUnit CENTURY = BaseStandardUnit .create(Alias.CENTURY_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 1000年 */ public static final BaseStandardUnit MILLENNIUM = BaseStandardUnit .create(Alias.MILLENNIUM_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 时代,1,000,000,000 Years */ public static final BaseStandardUnit ERA = BaseStandardUnit .create(Alias.ERA_ENGLISH_NAME.value(), BaseUnitType.TIME); /** * 千克 */ public static final BasePrefixUnit KILOGRAM = BasePrefixUnit .create(Prefix.KILO, UnitConstant.GRAM); /** * 埃米 10−8m 不是国际制单位 Å */ public static final BasePrefixUnit ANGSTROM_METER = BasePrefixUnit.create(Prefix.ANGSTROM, METER); /** * 忽米 10−5m cmm */ public static final BasePrefixUnit CENTIMILLI_METER = BasePrefixUnit .create(Prefix.CENTIMILLI, METER); /** * 弧度 m·m−1 平面角 球面度 m2·m−2 立体角 */ public static final CompositeStandardUnit NON = CompositeStandardUnit.builder().build(); /** * 赫兹 s−1 */ public static final CompositeStandardUnit HERTZ = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.SECOND, -1).build(); /** * 牛顿 kg·m·s−2 力 重量 */ public static final CompositeStandardUnit NEWTON = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, 1).unitComponentToExponent( UnitConstant.METER, 1) .unitComponentToExponent(UnitConstant.SECOND, -2).build(); /** * 帕斯卡 N/m2 kg·m−1·s−2 压强 应力 */ public static final CompositeStandardUnit PASCAL = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, 1).unitComponentToExponent( UnitConstant.METER, -1) .unitComponentToExponent(UnitConstant.SECOND, -2).build(); /** * 焦耳 N·m kg·m2·s−2 能量 功 热量 */ public static final CompositeStandardUnit JOULE = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, 1).unitComponentToExponent( UnitConstant.METER, 2) .unitComponentToExponent(UnitConstant.SECOND, -2).build(); /** * 瓦特 J/s kg·m2·s−3 功率 辐射通量 */ public static final CompositeStandardUnit WATT = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, 1).unitComponentToExponent( UnitConstant.METER, 2) .unitComponentToExponent(UnitConstant.SECOND, -3).build(); /** * 库仑 s·A 电荷 */ public static final CompositeStandardUnit COULOMB = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.SECOND, 1) .unitComponentToExponent(UnitConstant.AMPERE, 1) .build(); /** * 伏特 W/A kg·m2·s−3·A−1 电压(电势差) 电动势 */ public static final CompositeStandardUnit VOLT = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, 1).unitComponentToExponent( UnitConstant.METER, 2) .unitComponentToExponent(UnitConstant.SECOND, -3) .unitComponentToExponent(UnitConstant.AMPERE, -1).build(); /** * 法拉 C/V kg−1·m−2·s4·A2 电容 */ public static final CompositeStandardUnit FARAD = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, -1).unitComponentToExponent( UnitConstant.METER, -2) .unitComponentToExponent(UnitConstant.SECOND, 4) .unitComponentToExponent(UnitConstant.AMPERE, 2) .build(); /** * 欧姆 V/A kg·m2·s−3·A−2 电阻、阻抗、电抗 */ public static final CompositeStandardUnit OHM = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, 1).unitComponentToExponent( UnitConstant.METER, 2) .unitComponentToExponent(UnitConstant.SECOND, -3) .unitComponentToExponent(UnitConstant.AMPERE, -2).build(); /** * 西门子 A/V kg−1·m−2·s3·A2 电导 */ public static final CompositeStandardUnit SIEMENS = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, -1).unitComponentToExponent( UnitConstant.METER, -2) .unitComponentToExponent(UnitConstant.SECOND, 3) .unitComponentToExponent(UnitConstant.AMPERE, 2) .build(); /** * 韦伯 V·s kg·m2·s−2·A−1 磁通量 */ public static final CompositeStandardUnit WEBER = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, 1).unitComponentToExponent( UnitConstant.METER, 2) .unitComponentToExponent(UnitConstant.SECOND, -2) .unitComponentToExponent(UnitConstant.AMPERE, -1).build(); /** * 特斯拉 Wb/m2 kg·s−2·A−1 磁通量密度(磁场) */ public static final CompositeStandardUnit TESLA = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, 1).unitComponentToExponent( UnitConstant.SECOND, -2) .unitComponentToExponent(UnitConstant.AMPERE, -1).build(); /** * 亨利 Wb/A kg·m2·s−2·A−2 电感 */ public static final CompositeStandardUnit HENRY = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.KILOGRAM, 1).unitComponentToExponent( UnitConstant.METER, 2) .unitComponentToExponent(UnitConstant.SECOND, -2) .unitComponentToExponent(UnitConstant.AMPERE, -2).build(); /** * 流明 cd·sr cd 光通量 */ public static final CompositeStandardUnit LUMEN = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.CANDELA, 1) .unitComponentToExponent(NON, 1) .build(); /** * 勒克斯 lm/m2 m−2·cd 照度 */ public static final CompositeStandardUnit LUX = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.METER, -2) .unitComponentToExponent(UnitConstant.SECOND, -2).unitComponentToExponent( UnitConstant.CANDELA, 1).build(); //TODO 单位拥有多个名字时处理 // /** // * 贝克勒尔 s−1 放射性活度 // */ // public static final CompositeStandardUnit BECQUEREL = CompositeStandardUnit.builder() // .unitComponentToExponent(UnitConstant.SECOND, -1).build(); /** * 戈瑞 J/kg m2·s−2 致电离辐射的吸收剂量 */ public static final CompositeStandardUnit GRAY = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.METER, 2) .unitComponentToExponent(UnitConstant.SECOND, -2) .build(); //TODO 单位拥有多个名字时处理 // /** // * 希沃特 J/kg m2·s−2 致电离辐射等效剂量 // */ // public static final CompositeStandardUnit SIEVERT = CompositeStandardUnit.builder() // .unitComponentToExponent(UnitConstant.METER, 2) // .unitComponentToExponent(UnitConstant.SECOND, -2) // .build(); /** * 开特 mol·s−1 催化活度 */ public static final CompositeStandardUnit KATAL = CompositeStandardUnit.builder() .unitComponentToExponent(UnitConstant.MOLE, 1) .unitComponentToExponent(UnitConstant.SECOND, -1) .build(); /** * 国际单位制7个基本标准单位不可变集合 */ public static final ImmutableSet SI_BASE_STANDARD_UNITS = ImmutableSet .of(UnitConstant.METER, UnitConstant.GRAM, UnitConstant.SECOND, UnitConstant.AMPERE, UnitConstant.KELVIN, UnitConstant.MOLE, UnitConstant.CANDELA); /** * 古代东亚长度标准单位不可变集合 */ public static final ImmutableSet EAST_ASIA_OLD_LENGTH_STANDARD_UNITS = ImmutableSet .of(UnitConstant.CHINESE_MILE, UnitConstant.TANG, UnitConstant.ZHANG, UnitConstant.YIN, UnitConstant.CHI, UnitConstant.CUN, UnitConstant.FEN, UnitConstant.LI); /** * 英制长度标准单位不可变集合 */ public static final ImmutableSet ENGLISH_LENGTH_STANDARD_UNITS = ImmutableSet .of(UnitConstant.INCH, UnitConstant.FOOT, UnitConstant.YARD, UnitConstant.FATHOM, UnitConstant.CHAIN, UnitConstant.FURLONG, UnitConstant.MILE); /** * 默认时间标准单位不可变集合 */ public static final ImmutableSet DEFAULT_TIME_STANDARD_UNITS = ImmutableSet .of(UnitConstant.SECOND, UnitConstant.MINUTE, UnitConstant.HOUR, UnitConstant.DAY, UnitConstant.HALF_DAY, UnitConstant.WEEK, UnitConstant.YEAR, UnitConstant.MONTH, UnitConstant.DECADE, UnitConstant.CENTURY, UnitConstant.MILLENNIUM, UnitConstant.ERA); } package april.vis; import javax.media.opengl.*; import javax.media.opengl.glu.*; import com.sun.opengl.util.*; import april.jmat.geom.*; import java.awt.*; import java.util.*; import java.io.*; import java.nio.*; import lcm.lcm.*; /** VisObject representing a robot. **/ public class VisRobot implements VisObject, VisSerializable { public Color color = new Color(40, 40, 100); public Color outlineColor = new Color(40, 40, 255); int selectedState; // 0 = none, 1 = hover, 2 = select public VisRobot() { } public VisRobot(Color color, Color outlineColor) { this.color = color; this.outlineColor = outlineColor; } public VisRobot(Color color) { this.color = color; this.outlineColor = color.brighter(); } public void setSelectedState(int v) { this.selectedState = v; } public void render(VisContext vc, GL gl, GLU glu) { double length = 0.6; double width = .35; if (selectedState == 1) { VisUtil.setColor(gl, VisUtil.hoverColor); } else if (selectedState == 2) { VisUtil.setColor(gl, VisUtil.pickColor); } if (selectedState > 0) { gl.glBegin(gl.GL_QUADS); gl.glVertex2d(-length, -width); gl.glVertex2d(-length, width); gl.glVertex2d(length, width); gl.glVertex2d(length, -width); gl.glEnd(); } gl.glLineWidth(1f); VisUtil.setColor(gl, color); gl.glBegin(gl.GL_TRIANGLES); gl.glVertex2d(-length/2, width/2); gl.glVertex2d(length/2, 0); gl.glVertex2d(-length/2, -width/2); gl.glEnd(); VisUtil.setColor(gl, outlineColor); gl.glBegin(gl.GL_LINE_LOOP); gl.glVertex2d(-length/2, width/2); gl.glVertex2d(length/2, 0); gl.glVertex2d(-length/2, -width/2); gl.glEnd(); } public void serialize(LCMDataOutputStream out) throws IOException { out.writeInt(color.getRGB()); out.writeInt(outlineColor.getRGB()); out.writeInt(selectedState); } public void unserialize(LCMDataInputStream in) throws IOException { color = new Color(in.readInt(), true); outlineColor = new Color(in.readInt(), true); selectedState = in.readInt(); } } package de.techdev.springtest.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * @author */ @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private Integer salary; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } } src/main/java/gew/filesystem/client/model/FileOperation.java package gew.filesystem.client.model; /** * @author Jason/GeW * @since 2019-03-24 */ public enum FileOperation { READ, WRITE, APPEND, OVERWRITE, DELETE_SOURCE, DELETE_RECURSIVE, } 1-10 // Decompiled by Jad v1.5.8g. Copyright 2001 . // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v7.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.view.*; import android.util.AttributeSet; import android.util.SparseArray; import android.view.*; import android.widget.OverScroller; // Referenced classes of package android.support.v7.widget: // DecorContentParent, DecorToolbar, Toolbar, ActionBarContainer, // ViewUtils, ContentFrameLayout public class ActionBarOverlayLayout extends ViewGroup implements DecorContentParent, NestedScrollingParent { public static interface ActionBarVisibilityCallback { public abstract void enableContentAnimations(boolean flag); public abstract void hideForSystem(); public abstract void onContentScrollStarted(); public abstract void onContentScrollStopped(); public abstract void onWindowVisibilityChanged(int i); public abstract void showForSystem(); } public static class LayoutParams extends android.view.ViewGroup.MarginLayoutParams { public LayoutParams(int i, int j) { super(i, j); // 0 0:aload_0 // 1 1:iload_1 // 2 2:iload_2 // 3 3:invokespecial #11 // 4 6:return } public LayoutParams(Context context, AttributeSet attributeset) { super(context, attributeset); // 0 0:aload_0 // 1 1:aload_1 // 2 2:aload_2 // 3 3:invokespecial #15 // 4 6:return } public LayoutParams(android.view.ViewGroup.LayoutParams layoutparams) { super(layoutparams); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #18 // 3 5:return } public LayoutParams(android.view.ViewGroup.MarginLayoutParams marginlayoutparams) { super(marginlayoutparams); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #21 // 3 5:return } } public ActionBarOverlayLayout(Context context) { this(context, ((AttributeSet) (null))); // 0 0:aload_0 // 1 1:aload_1 // 2 2:aconst_null // 3 3:invokespecial #86 // 4 6:return } public ActionBarOverlayLayout(Context context, AttributeSet attributeset) { super(context, attributeset); // 0 0:aload_0 // 1 1:aload_1 // 2 2:aload_2 // 3 3:invokespecial #87 mWindowVisibility = 0; // 4 6:aload_0 // 5 7:iconst_0 // 6 8:putfield #89 mBaseContentInsets = new Rect(); // 7 11:aload_0 // 8 12:new #91 // 9 15:dup // 10 16:invokespecial #93 // 11 19:putfield #95 mLastBaseContentInsets = new Rect(); // 12 22:aload_0 // 13 23:new #91 // 14 26:dup // 15 27:invokespecial #93 // 16 30:putfield #97 mContentInsets = new Rect(); // 17 33:aload_0 // 18 34:new #91 // 19 37:dup // 20 38:invokespecial #93 // 21 41:putfield #99 mBaseInnerInsets = new Rect(); // 22 44:aload_0 // 23 45:new #91 // 24 48:dup // 25 49:invokespecial #93 // 26 52:putfield #101 mInnerInsets = new Rect(); // 27 55:aload_0 // 28 56:new #91 // 29 59:dup // 30 60:invokespecial #93 // 31 63:putfield #103 mLastInnerInsets = new Rect(); // 32 66:aload_0 // 33 67:new #91 // 34 70:dup // 35 71:invokespecial #93 // 36 74:putfield #105 ACTION_BAR_ANIMATE_DELAY = 600; // 37 77:aload_0 // 38 78:sipush 600 // 39 81:putfield #107 mTopAnimatorListener = ((AnimatorListenerAdapter) (new AnimatorListenerAdapter() { public void onAnimationCancel(Animator animator) { mCurrentActionBarTopAnimator = null; // 0 0:aload_0 // 1 1:getfield #12 // 2 4:aconst_null // 3 5:putfield #22 mAnimatingForFling = false; // 4 8:aload_0 // 5 9:getfield #12 // 6 12:iconst_0 // 7 13:putfield #26 // 8 16:return } public void onAnimationEnd(Animator animator) { mCurrentActionBarTopAnimator = null; // 0 0:aload_0 // 1 1:getfield #12 // 2 4:aconst_null // 3 5:putfield #22 mAnimatingForFling = false; // 4 8:aload_0 // 5 9:getfield #12 // 6 12:iconst_0 // 7 13:putfield #26 // 8 16:return } final ActionBarOverlayLayout this$0; { this$0 = ActionBarOverlayLayout.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #12 super(); // 3 5:aload_0 // 4 6:invokespecial #15 // 5 9:return } } )); // 40 84:aload_0 // 41 85:new #10 // 42 88:dup // 43 89:aload_0 // 44 90:invokespecial #110 // 45 93:putfield #112 mRemoveActionBarHideOffset = new Runnable() { public void run() { haltActionBarHideOffsetAnimations(); // 0 0:aload_0 // 1 1:getfield #14 // 2 4:invokevirtual #22 mCurrentActionBarTopAnimator = mActionBarTop.animate().translationY(0.0F).setListener(((android.animation.Animator.AnimatorListener) (mTopAnimatorListener))); // 3 7:aload_0 // 4 8:getfield #14 // 5 11:aload_0 // 6 12:getfield #14 // 7 15:getfield #26 // 8 18:invokevirtual #32 // 9 21:fconst_0 // 10 22:invokevirtual #38 // 11 25:aload_0 // 12 26:getfield #14 // 13 29:getfield #42 // 14 32:invokevirtual #46 // 15 35:putfield #50 // 16 38:return } final ActionBarOverlayLayout this$0; { this$0 = ActionBarOverlayLayout.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #14 super(); // 3 5:aload_0 // 4 6:invokespecial #17 // 5 9:return } } ; // 46 96:aload_0 // 47 97:new #12 // 48 100:dup // 49 101:aload_0 // 50 102:invokespecial #113 // 51 105:putfield #115 mAddActionBarHideOffset = new Runnable() { public void run() { haltActionBarHideOffsetAnimations(); // 0 0:aload_0 // 1 1:getfield #14 // 2 4:invokevirtual #22 mCurrentActionBarTopAnimator = mActionBarTop.animate().translationY(-mActionBarTop.getHeight()).setListener(((android.animation.Animator.AnimatorListener) (mTopAnimatorListener))); // 3 7:aload_0 // 4 8:getfield #14 // 5 11:aload_0 // 6 12:getfield #14 // 7 15:getfield #26 // 8 18:invokevirtual #32 // 9 21:aload_0 // 10 22:getfield #14 // 11 25:getfield #26 // 12 28:invokevirtual #36 // 13 31:ineg // 14 32:i2f // 15 33:invokevirtual #42 // 16 36:aload_0 // 17 37:getfield #14 // 18 40:getfield #46 // 19 43:invokevirtual #50 // 20 46:putfield #54 // 21 49:return } final ActionBarOverlayLayout this$0; { this$0 = ActionBarOverlayLayout.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #14 super(); // 3 5:aload_0 // 4 6:invokespecial #17 // 5 9:return } } ; // 52 108:aload_0 // 53 109:new #14 // 54 112:dup // 55 113:aload_0 // 56 114:invokespecial #116 // 57 117:putfield #118 init(context); // 58 120:aload_0 // 59 121:aload_1 // 60 122:invokespecial #121 mParentHelper = new NestedScrollingParentHelper(((ViewGroup) (this))); // 61 125:aload_0 // 62 126:new #123 // 63 129:dup // 64 130:aload_0 // 65 131:invokespecial #126 // 66 134:putfield #128 // 67 137:return } private void addActionBarHideOffset() { haltActionBarHideOffsetAnimations(); // 0 0:aload_0 // 1 1:invokevirtual #132 mAddActionBarHideOffset.run(); // 2 4:aload_0 // 3 5:getfield #118 // 4 8:invokeinterface #137 // 5 13:return } private boolean applyInsets(View view, Rect rect, boolean flag, boolean flag1, boolean flag2, boolean flag3) { boolean flag5 = false; // 0 0:iconst_0 // 1 1:istore 8 view = ((View) ((LayoutParams)view.getLayoutParams())); // 2 3:aload_1 // 3 4:invokevirtual #145 // 4 7:checkcast #19 // 5 10:astore_1 boolean flag4 = flag5; // 6 11:iload 8 // 7 13:istore 7 if(flag) //* 8 15:iload_3 //* 9 16:ifeq 45 { flag4 = flag5; // 10 19:iload 8 // 11 21:istore 7 if(((LayoutParams) (view)).leftMargin != rect.left) //* 12 23:aload_1 //* 13 24:getfield #148 //* 14 27:aload_2 //* 15 28:getfield #151 //* 16 31:icmpeq 45 { flag4 = true; // 17 34:iconst_1 // 18 35:istore 7 view.leftMargin = rect.left; // 19 37:aload_1 // 20 38:aload_2 // 21 39:getfield #151 // 22 42:putfield #148 } } flag = flag4; // 23 45:iload 7 // 24 47:istore_3 if(flag1) //* 25 48:iload 4 //* 26 50:ifeq 77 { flag = flag4; // 27 53:iload 7 // 28 55:istore_3 if(((LayoutParams) (view)).topMargin != rect.top) //* 29 56:aload_1 //* 30 57:getfield #154 //* 31 60:aload_2 //* 32 61:getfield #157 //* 33 64:icmpeq 77 { flag = true; // 34 67:iconst_1 // 35 68:istore_3 view.topMargin = rect.top; // 36 69:aload_1 // 37 70:aload_2 // 38 71:getfield #157 // 39 74:putfield #154 } } flag1 = flag; // 40 77:iload_3 // 41 78:istore 4 if(flag3) //* 42 80:iload 6 //* 43 82:ifeq 110 { flag1 = flag; // 44 85:iload_3 // 45 86:istore 4 if(((LayoutParams) (view)).rightMargin != rect.right) //* 46 88:aload_1 //* 47 89:getfield #160 //* 48 92:aload_2 //* 49 93:getfield #163 //* 50 96:icmpeq 110 { flag1 = true; // 51 99:iconst_1 // 52 100:istore 4 view.rightMargin = rect.right; // 53 102:aload_1 // 54 103:aload_2 // 55 104:getfield #163 // 56 107:putfield #160 } } flag = flag1; // 57 110:iload 4 // 58 112:istore_3 if(flag2) //* 59 113:iload 5 //* 60 115:ifeq 142 { flag = flag1; // 61 118:iload 4 // 62 120:istore_3 if(((LayoutParams) (view)).bottomMargin != rect.bottom) //* 63 121:aload_1 //* 64 122:getfield #166 //* 65 125:aload_2 //* 66 126:getfield #169 //* 67 129:icmpeq 142 { flag = true; // 68 132:iconst_1 // 69 133:istore_3 view.bottomMargin = rect.bottom; // 70 134:aload_1 // 71 135:aload_2 // 72 136:getfield #169 // 73 139:putfield #166 } } return flag; // 74 142:iload_3 // 75 143:ireturn } private DecorToolbar getDecorToolbar(View view) { if(view instanceof DecorToolbar) //* 0 0:aload_1 //* 1 1:instanceof #173 //* 2 4:ifeq 12 return (DecorToolbar)view; // 3 7:aload_1 // 4 8:checkcast #173 // 5 11:areturn if(view instanceof Toolbar) //* 6 12:aload_1 //* 7 13:instanceof #175 //* 8 16:ifeq 27 return ((Toolbar)view).getWrapper(); // 9 19:aload_1 // 10 20:checkcast #175 // 11 23:invokevirtual #179 // 12 26:areturn else throw new IllegalStateException((new StringBuilder()).append("Can't make a decor toolbar out of ").append(((Object) (view)).getClass().getSimpleName()).toString()); // 13 27:new #181 // 14 30:dup // 15 31:new #183 // 16 34:dup // 17 35:invokespecial #184 // 18 38:ldc1 #186 // 19 40:invokevirtual #190 // 20 43:aload_1 // 21 44:invokevirtual #196 // 22 47:invokevirtual #202 // 23 50:invokevirtual #190 // 24 53:invokevirtual #205 // 25 56:invokespecial #208 // 26 59:athrow } private void init(Context context) { TypedArray typedarray = getContext().getTheme().obtainStyledAttributes(ATTRS); // 0 0:aload_0 // 1 1:invokevirtual #212 // 2 4:invokevirtual #218 // 3 7:getstatic #80 // 4 10:invokevirtual #224 // 5 13:astore_3 mActionBarHeight = typedarray.getDimensionPixelSize(0, 0); // 6 14:aload_0 // 7 15:aload_3 // 8 16:iconst_0 // 9 17:iconst_0 // 10 18:invokevirtual #230 // 11 21:putfield #232 mWindowContentOverlay = typedarray.getDrawable(1); // 12 24:aload_0 // 13 25:aload_3 // 14 26:iconst_1 // 15 27:invokevirtual #236 // 16 30:putfield #238 boolean flag; if(mWindowContentOverlay == null) //* 17 33:aload_0 //* 18 34:getfield #238 //* 19 37:ifnonnull 45 flag = true; // 20 40:iconst_1 // 21 41:istore_2 else //* 22 42:goto 47 flag = false; // 23 45:iconst_0 // 24 46:istore_2 setWillNotDraw(flag); // 25 47:aload_0 // 26 48:iload_2 // 27 49:invokevirtual #242 typedarray.recycle(); // 28 52:aload_3 // 29 53:invokevirtual #245 if(context.getApplicationInfo().targetSdkVersion < 19) //* 30 56:aload_1 //* 31 57:invokevirtual #249 //* 32 60:getfield #254 //* 33 63:bipush 19 //* 34 65:icmpge 73 flag = true; // 35 68:iconst_1 // 36 69:istore_2 else //* 37 70:goto 75 flag = false; // 38 73:iconst_0 // 39 74:istore_2 mIgnoreWindowContentOverlay = flag; // 40 75:aload_0 // 41 76:iload_2 // 42 77:putfield #256 mFlingEstimator = new OverScroller(context); // 43 80:aload_0 // 44 81:new #258 // 45 84:dup // 46 85:aload_1 // 47 86:invokespecial #260 // 48 89:putfield #262 // 49 92:return } private void postAddActionBarHideOffset() { haltActionBarHideOffsetAnimations(); // 0 0:aload_0 // 1 1:invokevirtual #132 postDelayed(mAddActionBarHideOffset, 600L); // 2 4:aload_0 // 3 5:aload_0 // 4 6:getfield #118 // 5 9:ldc2w #264 // 6 12:invokevirtual #269 // 7 15:pop // 8 16:return } private void postRemoveActionBarHideOffset() { haltActionBarHideOffsetAnimations(); // 0 0:aload_0 // 1 1:invokevirtual #132 postDelayed(mRemoveActionBarHideOffset, 600L); // 2 4:aload_0 // 3 5:aload_0 // 4 6:getfield #115 // 5 9:ldc2w #264 // 6 12:invokevirtual #269 // 7 15:pop // 8 16:return } private void removeActionBarHideOffset() { haltActionBarHideOffsetAnimations(); // 0 0:aload_0 // 1 1:invokevirtual #132 mRemoveActionBarHideOffset.run(); // 2 4:aload_0 // 3 5:getfield #115 // 4 8:invokeinterface #137 // 5 13:return } private boolean shouldHideActionBarOnFling(float f, float f1) { mFlingEstimator.fling(0, 0, 0, (int)f1, 0, 0, 0x80000000, 0x7fffffff); // 0 0:aload_0 // 1 1:getfield #262 // 2 4:iconst_0 // 3 5:iconst_0 // 4 6:iconst_0 // 5 7:fload_2 // 6 8:f2i // 7 9:iconst_0 // 8 10:iconst_0 // 9 11:ldc2 #274 // 10 14:ldc2 #275 // 11 17:invokevirtual #279 return mFlingEstimator.getFinalY() > mActionBarTop.getHeight(); // 12 20:aload_0 // 13 21:getfield #262 // 14 24:invokevirtual #283 // 15 27:aload_0 // 16 28:getfield #285 // 17 31:invokevirtual #290 // 18 34:icmple 39 // 19 37:iconst_1 // 20 38:ireturn // 21 39:iconst_0 // 22 40:ireturn } public boolean canShowOverflowMenu() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 return mDecorToolbar.canShowOverflowMenu(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #299 // 5 13:ireturn } protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams layoutparams) { return layoutparams instanceof LayoutParams; // 0 0:aload_1 // 1 1:instanceof #19 // 2 4:ireturn } public void dismissPopups() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.dismissPopupMenus(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #305 // 5 13:return } public void draw(Canvas canvas) { super.draw(canvas); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #309 if(mWindowContentOverlay != null && !mIgnoreWindowContentOverlay) //* 3 5:aload_0 //* 4 6:getfield #238 //* 5 9:ifnull 86 //* 6 12:aload_0 //* 7 13:getfield #256 //* 8 16:ifne 86 { int i; if(mActionBarTop.getVisibility() == 0) //* 9 19:aload_0 //* 10 20:getfield #285 //* 11 23:invokevirtual #312 //* 12 26:ifne 54 i = (int)((float)mActionBarTop.getBottom() + mActionBarTop.getTranslationY() + 0.5F); // 13 29:aload_0 // 14 30:getfield #285 // 15 33:invokevirtual #315 // 16 36:i2f // 17 37:aload_0 // 18 38:getfield #285 // 19 41:invokevirtual #319 // 20 44:fadd // 21 45:ldc2 #320 // 22 48:fadd // 23 49:f2i // 24 50:istore_2 else //* 25 51:goto 56 i = 0; // 26 54:iconst_0 // 27 55:istore_2 mWindowContentOverlay.setBounds(0, i, getWidth(), mWindowContentOverlay.getIntrinsicHeight() + i); // 28 56:aload_0 // 29 57:getfield #238 // 30 60:iconst_0 // 31 61:iload_2 // 32 62:aload_0 // 33 63:invokevirtual #323 // 34 66:aload_0 // 35 67:getfield #238 // 36 70:invokevirtual #328 // 37 73:iload_2 // 38 74:iadd // 39 75:invokevirtual #332 mWindowContentOverlay.draw(canvas); // 40 78:aload_0 // 41 79:getfield #238 // 42 82:aload_1 // 43 83:invokevirtual #333 } // 44 86:return } protected boolean fitSystemWindows(Rect rect) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 if((ViewCompat.getWindowSystemUiVisibility(((View) (this))) & 0x100) == 0); // 2 4:aload_0 // 3 5:invokestatic #341 // 4 8:sipush 256 // 5 11:iand // 6 12:ifeq 18 //* 7 15:goto 18 boolean flag = applyInsets(((View) (mActionBarTop)), rect, true, true, false, true); // 8 18:aload_0 // 9 19:aload_0 // 10 20:getfield #285 // 11 23:aload_1 // 12 24:iconst_1 // 13 25:iconst_1 // 14 26:iconst_0 // 15 27:iconst_1 // 16 28:invokespecial #343 // 17 31:istore_2 mBaseInnerInsets.set(rect); // 18 32:aload_0 // 19 33:getfield #101 // 20 36:aload_1 // 21 37:invokevirtual #347 ViewUtils.computeFitSystemWindows(((View) (this)), mBaseInnerInsets, mBaseContentInsets); // 22 40:aload_0 // 23 41:aload_0 // 24 42:getfield #101 // 25 45:aload_0 // 26 46:getfield #95 // 27 49:invokestatic #353 if(!mLastBaseContentInsets.equals(((Object) (mBaseContentInsets)))) //* 28 52:aload_0 //* 29 53:getfield #97 //* 30 56:aload_0 //* 31 57:getfield #95 //* 32 60:invokevirtual #357 //* 33 63:ifne 79 { flag = true; // 34 66:iconst_1 // 35 67:istore_2 mLastBaseContentInsets.set(mBaseContentInsets); // 36 68:aload_0 // 37 69:getfield #97 // 38 72:aload_0 // 39 73:getfield #95 // 40 76:invokevirtual #347 } if(flag) //* 41 79:iload_2 //* 42 80:ifeq 87 requestLayout(); // 43 83:aload_0 // 44 84:invokevirtual #360 return true; // 45 87:iconst_1 // 46 88:ireturn } protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(-1, -1); // 0 0:new #19 // 1 3:dup // 2 4:iconst_m1 // 3 5:iconst_m1 // 4 6:invokespecial #365 // 5 9:areturn } protected volatile android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() { return ((android.view.ViewGroup.LayoutParams) (generateDefaultLayoutParams())); // 0 0:aload_0 // 1 1:invokevirtual #367 // 2 4:areturn } public LayoutParams generateLayoutParams(AttributeSet attributeset) { return new LayoutParams(getContext(), attributeset); // 0 0:new #19 // 1 3:dup // 2 4:aload_0 // 3 5:invokevirtual #212 // 4 8:aload_1 // 5 9:invokespecial #370 // 6 12:areturn } public volatile android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attributeset) { return ((android.view.ViewGroup.LayoutParams) (generateLayoutParams(attributeset))); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokevirtual #373 // 3 5:areturn } protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams layoutparams) { return ((android.view.ViewGroup.LayoutParams) (new LayoutParams(layoutparams))); // 0 0:new #19 // 1 3:dup // 2 4:aload_1 // 3 5:invokespecial #377 // 4 8:areturn } public int getActionBarHideOffset() { if(mActionBarTop != null) //* 0 0:aload_0 //* 1 1:getfield #285 //* 2 4:ifnull 17 return -(int)mActionBarTop.getTranslationY(); // 3 7:aload_0 // 4 8:getfield #285 // 5 11:invokevirtual #319 // 6 14:f2i // 7 15:ineg // 8 16:ireturn else return 0; // 9 17:iconst_0 // 10 18:ireturn } public int getNestedScrollAxes() { return mParentHelper.getNestedScrollAxes(); // 0 0:aload_0 // 1 1:getfield #128 // 2 4:invokevirtual #381 // 3 7:ireturn } public CharSequence getTitle() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 return mDecorToolbar.getTitle(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #385 // 5 13:areturn } void haltActionBarHideOffsetAnimations() { removeCallbacks(mRemoveActionBarHideOffset); // 0 0:aload_0 // 1 1:aload_0 // 2 2:getfield #115 // 3 5:invokevirtual #389 // 4 8:pop removeCallbacks(mAddActionBarHideOffset); // 5 9:aload_0 // 6 10:aload_0 // 7 11:getfield #118 // 8 14:invokevirtual #389 // 9 17:pop if(mCurrentActionBarTopAnimator != null) //* 10 18:aload_0 //* 11 19:getfield #391 //* 12 22:ifnull 32 mCurrentActionBarTopAnimator.cancel(); // 13 25:aload_0 // 14 26:getfield #391 // 15 29:invokevirtual #396 // 16 32:return } public boolean hasIcon() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 return mDecorToolbar.hasIcon(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #399 // 5 13:ireturn } public boolean hasLogo() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 return mDecorToolbar.hasLogo(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #402 // 5 13:ireturn } public boolean hideOverflowMenu() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 return mDecorToolbar.hideOverflowMenu(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #405 // 5 13:ireturn } public void initFeature(int i) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 switch(i) //* 2 4:iload_1 { //* 3 5:lookupswitch 3: default 40 // 2: 41 // 5: 51 // 109: 61 default: return; // 4 40:return case 2: // '\002' mDecorToolbar.initProgress(); // 5 41:aload_0 // 6 42:getfield #297 // 7 45:invokeinterface #410 return; // 8 50:return case 5: // '\005' mDecorToolbar.initIndeterminateProgress(); // 9 51:aload_0 // 10 52:getfield #297 // 11 55:invokeinterface #413 return; // 12 60:return case 109: // 'm' setOverlayMode(true); // 13 61:aload_0 // 14 62:iconst_1 // 15 63:invokevirtual #416 break; } // 16 66:return } public boolean isHideOnContentScrollEnabled() { return mHideOnContentScroll; // 0 0:aload_0 // 1 1:getfield #419 // 2 4:ireturn } public boolean isInOverlayMode() { return mOverlayMode; // 0 0:aload_0 // 1 1:getfield #422 // 2 4:ireturn } public boolean isOverflowMenuShowPending() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 return mDecorToolbar.isOverflowMenuShowPending(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #425 // 5 13:ireturn } public boolean isOverflowMenuShowing() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 return mDecorToolbar.isOverflowMenuShowing(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #428 // 5 13:ireturn } protected void onConfigurationChanged(Configuration configuration) { super.onConfigurationChanged(configuration); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #432 init(getContext()); // 3 5:aload_0 // 4 6:aload_0 // 5 7:invokevirtual #212 // 6 10:invokespecial #121 ViewCompat.requestApplyInsets(((View) (this))); // 7 13:aload_0 // 8 14:invokestatic #436 // 9 17:return } protected void onDetachedFromWindow() { super.onDetachedFromWindow(); // 0 0:aload_0 // 1 1:invokespecial #439 haltActionBarHideOffsetAnimations(); // 2 4:aload_0 // 3 5:invokevirtual #132 // 4 8:return } protected void onLayout(boolean flag, int i, int j, int k, int l) { j = getChildCount(); // 0 0:aload_0 // 1 1:invokevirtual #444 // 2 4:istore_3 k = getPaddingLeft(); // 3 5:aload_0 // 4 6:invokevirtual #447 // 5 9:istore 4 getPaddingRight(); // 6 11:aload_0 // 7 12:invokevirtual #450 // 8 15:pop l = getPaddingTop(); // 9 16:aload_0 // 10 17:invokevirtual #453 // 11 20:istore 5 getPaddingBottom(); // 12 22:aload_0 // 13 23:invokevirtual #456 // 14 26:pop for(i = 0; i < j; i++) //* 15 27:iconst_0 //* 16 28:istore_2 //* 17 29:iload_2 //* 18 30:iload_3 //* 19 31:icmpge 121 { View view = getChildAt(i); // 20 34:aload_0 // 21 35:iload_2 // 22 36:invokevirtual #460 // 23 39:astore 10 if(view.getVisibility() != 8) //* 24 41:aload 10 //* 25 43:invokevirtual #461 //* 26 46:bipush 8 //* 27 48:icmpeq 114 { LayoutParams layoutparams = (LayoutParams)view.getLayoutParams(); // 28 51:aload 10 // 29 53:invokevirtual #145 // 30 56:checkcast #19 // 31 59:astore 11 int i1 = view.getMeasuredWidth(); // 32 61:aload 10 // 33 63:invokevirtual #464 // 34 66:istore 6 int j1 = view.getMeasuredHeight(); // 35 68:aload 10 // 36 70:invokevirtual #467 // 37 73:istore 7 int k1 = k + layoutparams.leftMargin; // 38 75:iload 4 // 39 77:aload 11 // 40 79:getfield #148 // 41 82:iadd // 42 83:istore 8 int l1 = l + layoutparams.topMargin; // 43 85:iload 5 // 44 87:aload 11 // 45 89:getfield #154 // 46 92:iadd // 47 93:istore 9 view.layout(k1, l1, k1 + i1, l1 + j1); // 48 95:aload 10 // 49 97:iload 8 // 50 99:iload 9 // 51 101:iload 8 // 52 103:iload 6 // 53 105:iadd // 54 106:iload 9 // 55 108:iload 7 // 56 110:iadd // 57 111:invokevirtual #470 } } // 58 114:iload_2 // 59 115:iconst_1 // 60 116:iadd // 61 117:istore_2 //* 62 118:goto 29 // 63 121:return } protected void onMeasure(int i, int j) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 int k = 0; // 2 4:iconst_0 // 3 5:istore_3 measureChildWithMargins(((View) (mActionBarTop)), i, 0, j, 0); // 4 6:aload_0 // 5 7:aload_0 // 6 8:getfield #285 // 7 11:iload_1 // 8 12:iconst_0 // 9 13:iload_2 // 10 14:iconst_0 // 11 15:invokevirtual #475 Object obj = ((Object) ((LayoutParams)mActionBarTop.getLayoutParams())); // 12 18:aload_0 // 13 19:getfield #285 // 14 22:invokevirtual #476 // 15 25:checkcast #19 // 16 28:astore 9 int i2 = Math.max(0, mActionBarTop.getMeasuredWidth() + ((LayoutParams) (obj)).leftMargin + ((LayoutParams) (obj)).rightMargin); // 17 30:iconst_0 // 18 31:aload_0 // 19 32:getfield #285 // 20 35:invokevirtual #477 // 21 38:aload 9 // 22 40:getfield #148 // 23 43:iadd // 24 44:aload 9 // 25 46:getfield #160 // 26 49:iadd // 27 50:invokestatic #482 // 28 53:istore 8 int l1 = Math.max(0, mActionBarTop.getMeasuredHeight() + ((LayoutParams) (obj)).topMargin + ((LayoutParams) (obj)).bottomMargin); // 29 55:iconst_0 // 30 56:aload_0 // 31 57:getfield #285 // 32 60:invokevirtual #483 // 33 63:aload 9 // 34 65:getfield #154 // 35 68:iadd // 36 69:aload 9 // 37 71:getfield #166 // 38 74:iadd // 39 75:invokestatic #482 // 40 78:istore 7 int k1 = View.combineMeasuredStates(0, mActionBarTop.getMeasuredState()); // 41 80:iconst_0 // 42 81:aload_0 // 43 82:getfield #285 // 44 85:invokevirtual #486 // 45 88:invokestatic #489 // 46 91:istore 6 boolean flag; if((ViewCompat.getWindowSystemUiVisibility(((View) (this))) & 0x100) != 0) //* 47 93:aload_0 //* 48 94:invokestatic #341 //* 49 97:sipush 256 //* 50 100:iand //* 51 101:ifeq 110 flag = true; // 52 104:iconst_1 // 53 105:istore 4 else //* 54 107:goto 113 flag = false; // 55 110:iconst_0 // 56 111:istore 4 if(flag) //* 57 113:iload 4 //* 58 115:ifeq 158 { int i1 = mActionBarHeight; // 59 118:aload_0 // 60 119:getfield #232 // 61 122:istore 5 k = i1; // 62 124:iload 5 // 63 126:istore_3 if(mHasNonEmbeddedTabs) //* 64 127:aload_0 //* 65 128:getfield #491 //* 66 131:ifeq 178 { k = i1; // 67 134:iload 5 // 68 136:istore_3 if(mActionBarTop.getTabContainer() != null) //* 69 137:aload_0 //* 70 138:getfield #285 //* 71 141:invokevirtual #495 //* 72 144:ifnull 155 k = i1 + mActionBarHeight; // 73 147:iload 5 // 74 149:aload_0 // 75 150:getfield #232 // 76 153:iadd // 77 154:istore_3 } } else //* 78 155:goto 178 if(mActionBarTop.getVisibility() != 8) //* 79 158:aload_0 //* 80 159:getfield #285 //* 81 162:invokevirtual #312 //* 82 165:bipush 8 //* 83 167:icmpeq 178 k = mActionBarTop.getMeasuredHeight(); // 84 170:aload_0 // 85 171:getfield #285 // 86 174:invokevirtual #483 // 87 177:istore_3 mContentInsets.set(mBaseContentInsets); // 88 178:aload_0 // 89 179:getfield #99 // 90 182:aload_0 // 91 183:getfield #95 // 92 186:invokevirtual #347 mInnerInsets.set(mBaseInnerInsets); // 93 189:aload_0 // 94 190:getfield #103 // 95 193:aload_0 // 96 194:getfield #101 // 97 197:invokevirtual #347 if(!mOverlayMode && !flag) //* 98 200:aload_0 //* 99 201:getfield #422 //* 100 204:ifne 251 //* 101 207:iload 4 //* 102 209:ifne 251 { obj = ((Object) (mContentInsets)); // 103 212:aload_0 // 104 213:getfield #99 // 105 216:astore 9 obj.top = ((Rect) (obj)).top + k; // 106 218:aload 9 // 107 220:aload 9 // 108 222:getfield #157 // 109 225:iload_3 // 110 226:iadd // 111 227:putfield #157 obj = ((Object) (mContentInsets)); // 112 230:aload_0 // 113 231:getfield #99 // 114 234:astore 9 obj.bottom = ((Rect) (obj)).bottom + 0; // 115 236:aload 9 // 116 238:aload 9 // 117 240:getfield #169 // 118 243:iconst_0 // 119 244:iadd // 120 245:putfield #169 } else //* 121 248:goto 287 { obj = ((Object) (mInnerInsets)); // 122 251:aload_0 // 123 252:getfield #103 // 124 255:astore 9 obj.top = ((Rect) (obj)).top + k; // 125 257:aload 9 // 126 259:aload 9 // 127 261:getfield #157 // 128 264:iload_3 // 129 265:iadd // 130 266:putfield #157 obj = ((Object) (mInnerInsets)); // 131 269:aload_0 // 132 270:getfield #103 // 133 273:astore 9 obj.bottom = ((Rect) (obj)).bottom + 0; // 134 275:aload 9 // 135 277:aload 9 // 136 279:getfield #169 // 137 282:iconst_0 // 138 283:iadd // 139 284:putfield #169 } applyInsets(((View) (mContent)), mContentInsets, true, true, true, true); // 140 287:aload_0 // 141 288:aload_0 // 142 289:getfield #497 // 143 292:aload_0 // 144 293:getfield #99 // 145 296:iconst_1 // 146 297:iconst_1 // 147 298:iconst_1 // 148 299:iconst_1 // 149 300:invokespecial #343 // 150 303:pop if(!mLastInnerInsets.equals(((Object) (mInnerInsets)))) //* 151 304:aload_0 //* 152 305:getfield #105 //* 153 308:aload_0 //* 154 309:getfield #103 //* 155 312:invokevirtual #357 //* 156 315:ifne 340 { mLastInnerInsets.set(mInnerInsets); // 157 318:aload_0 // 158 319:getfield #105 // 159 322:aload_0 // 160 323:getfield #103 // 161 326:invokevirtual #347 mContent.dispatchFitSystemWindows(mInnerInsets); // 162 329:aload_0 // 163 330:getfield #497 // 164 333:aload_0 // 165 334:getfield #103 // 166 337:invokevirtual #502 } measureChildWithMargins(((View) (mContent)), i, 0, j, 0); // 167 340:aload_0 // 168 341:aload_0 // 169 342:getfield #497 // 170 345:iload_1 // 171 346:iconst_0 // 172 347:iload_2 // 173 348:iconst_0 // 174 349:invokevirtual #475 obj = ((Object) ((LayoutParams)mContent.getLayoutParams())); // 175 352:aload_0 // 176 353:getfield #497 // 177 356:invokevirtual #503 // 178 359:checkcast #19 // 179 362:astore 9 k = Math.max(i2, mContent.getMeasuredWidth() + ((LayoutParams) (obj)).leftMargin + ((LayoutParams) (obj)).rightMargin); // 180 364:iload 8 // 181 366:aload_0 // 182 367:getfield #497 // 183 370:invokevirtual #504 // 184 373:aload 9 // 185 375:getfield #148 // 186 378:iadd // 187 379:aload 9 // 188 381:getfield #160 // 189 384:iadd // 190 385:invokestatic #482 // 191 388:istore_3 int l = Math.max(l1, mContent.getMeasuredHeight() + ((LayoutParams) (obj)).topMargin + ((LayoutParams) (obj)).bottomMargin); // 192 389:iload 7 // 193 391:aload_0 // 194 392:getfield #497 // 195 395:invokevirtual #505 // 196 398:aload 9 // 197 400:getfield #154 // 198 403:iadd // 199 404:aload 9 // 200 406:getfield #166 // 201 409:iadd // 202 410:invokestatic #482 // 203 413:istore 4 int j1 = View.combineMeasuredStates(k1, mContent.getMeasuredState()); // 204 415:iload 6 // 205 417:aload_0 // 206 418:getfield #497 // 207 421:invokevirtual #506 // 208 424:invokestatic #489 // 209 427:istore 5 k1 = getPaddingLeft(); // 210 429:aload_0 // 211 430:invokevirtual #447 // 212 433:istore 6 l1 = getPaddingRight(); // 213 435:aload_0 // 214 436:invokevirtual #450 // 215 439:istore 7 l = Math.max(l + (getPaddingTop() + getPaddingBottom()), getSuggestedMinimumHeight()); // 216 441:iload 4 // 217 443:aload_0 // 218 444:invokevirtual #453 // 219 447:aload_0 // 220 448:invokevirtual #456 // 221 451:iadd // 222 452:iadd // 223 453:aload_0 // 224 454:invokevirtual #509 // 225 457:invokestatic #482 // 226 460:istore 4 setMeasuredDimension(View.resolveSizeAndState(Math.max(k + (k1 + l1), getSuggestedMinimumWidth()), i, j1), View.resolveSizeAndState(l, j, j1 << 16)); // 227 462:aload_0 // 228 463:iload_3 // 229 464:iload 6 // 230 466:iload 7 // 231 468:iadd // 232 469:iadd // 233 470:aload_0 // 234 471:invokevirtual #512 // 235 474:invokestatic #482 // 236 477:iload_1 // 237 478:iload 5 // 238 480:invokestatic #516 // 239 483:iload 4 // 240 485:iload_2 // 241 486:iload 5 // 242 488:bipush 16 // 243 490:ishl // 244 491:invokestatic #516 // 245 494:invokevirtual #519 // 246 497:return } public boolean onNestedFling(View view, float f, float f1, boolean flag) { if(!mHideOnContentScroll || !flag) //* 0 0:aload_0 //* 1 1:getfield #419 //* 2 4:ifeq 12 //* 3 7:iload 4 //* 4 9:ifne 14 return false; // 5 12:iconst_0 // 6 13:ireturn if(shouldHideActionBarOnFling(f, f1)) //* 7 14:aload_0 //* 8 15:fload_2 //* 9 16:fload_3 //* 10 17:invokespecial #523 //* 11 20:ifeq 30 addActionBarHideOffset(); // 12 23:aload_0 // 13 24:invokespecial #525 else //* 14 27:goto 34 removeActionBarHideOffset(); // 15 30:aload_0 // 16 31:invokespecial #527 mAnimatingForFling = true; // 17 34:aload_0 // 18 35:iconst_1 // 19 36:putfield #529 return true; // 20 39:iconst_1 // 21 40:ireturn } public boolean onNestedPreFling(View view, float f, float f1) { return false; // 0 0:iconst_0 // 1 1:ireturn } public void onNestedPreScroll(View view, int i, int j, int ai[]) { // 0 0:return } public void onNestedScroll(View view, int i, int j, int k, int l) { mHideOnContentScrollReference = mHideOnContentScrollReference + j; // 0 0:aload_0 // 1 1:aload_0 // 2 2:getfield #536 // 3 5:iload_3 // 4 6:iadd // 5 7:putfield #536 setActionBarHideOffset(mHideOnContentScrollReference); // 6 10:aload_0 // 7 11:aload_0 // 8 12:getfield #536 // 9 15:invokevirtual #539 // 10 18:return } public void onNestedScrollAccepted(View view, View view1, int i) { mParentHelper.onNestedScrollAccepted(view, view1, i); // 0 0:aload_0 // 1 1:getfield #128 // 2 4:aload_1 // 3 5:aload_2 // 4 6:iload_3 // 5 7:invokevirtual #543 mHideOnContentScrollReference = getActionBarHideOffset(); // 6 10:aload_0 // 7 11:aload_0 // 8 12:invokevirtual #545 // 9 15:putfield #536 haltActionBarHideOffsetAnimations(); // 10 18:aload_0 // 11 19:invokevirtual #132 if(mActionBarVisibilityCallback != null) //* 12 22:aload_0 //* 13 23:getfield #547 //* 14 26:ifnull 38 mActionBarVisibilityCallback.onContentScrollStarted(); // 15 29:aload_0 // 16 30:getfield #547 // 17 33:invokeinterface #550 // 18 38:return } public boolean onStartNestedScroll(View view, View view1, int i) { if((i & 2) == 0 || mActionBarTop.getVisibility() != 0) //* 0 0:iload_3 //* 1 1:iconst_2 //* 2 2:iand //* 3 3:ifeq 16 //* 4 6:aload_0 //* 5 7:getfield #285 //* 6 10:invokevirtual #312 //* 7 13:ifeq 18 return false; // 8 16:iconst_0 // 9 17:ireturn else return mHideOnContentScroll; // 10 18:aload_0 // 11 19:getfield #419 // 12 22:ireturn } public void onStopNestedScroll(View view) { if(mHideOnContentScroll && !mAnimatingForFling) //* 0 0:aload_0 //* 1 1:getfield #419 //* 2 4:ifeq 39 //* 3 7:aload_0 //* 4 8:getfield #529 //* 5 11:ifne 39 if(mHideOnContentScrollReference <= mActionBarTop.getHeight()) //* 6 14:aload_0 //* 7 15:getfield #536 //* 8 18:aload_0 //* 9 19:getfield #285 //* 10 22:invokevirtual #290 //* 11 25:icmpgt 35 postRemoveActionBarHideOffset(); // 12 28:aload_0 // 13 29:invokespecial #555 else //* 14 32:goto 39 postAddActionBarHideOffset(); // 15 35:aload_0 // 16 36:invokespecial #557 if(mActionBarVisibilityCallback != null) //* 17 39:aload_0 //* 18 40:getfield #547 //* 19 43:ifnull 55 mActionBarVisibilityCallback.onContentScrollStopped(); // 20 46:aload_0 // 21 47:getfield #547 // 22 50:invokeinterface #560 // 23 55:return } public void onWindowSystemUiVisibilityChanged(int i) { if(android.os.Build.VERSION.SDK_INT >= 16) //* 0 0:getstatic #566 //* 1 3:bipush 16 //* 2 5:icmplt 13 super.onWindowSystemUiVisibilityChanged(i); // 3 8:aload_0 // 4 9:iload_1 // 5 10:invokespecial #568 pullChildren(); // 6 13:aload_0 // 7 14:invokevirtual #295 int j = mLastSystemUiVisibility; // 8 17:aload_0 // 9 18:getfield #570 // 10 21:istore 4 mLastSystemUiVisibility = i; // 11 23:aload_0 // 12 24:iload_1 // 13 25:putfield #570 boolean flag; if((i & 4) == 0) //* 14 28:iload_1 //* 15 29:iconst_4 //* 16 30:iand //* 17 31:ifne 39 flag = true; // 18 34:iconst_1 // 19 35:istore_2 else //* 20 36:goto 41 flag = false; // 21 39:iconst_0 // 22 40:istore_2 boolean flag1; if((i & 0x100) != 0) //* 23 41:iload_1 //* 24 42:sipush 256 //* 25 45:iand //* 26 46:ifeq 54 flag1 = true; // 27 49:iconst_1 // 28 50:istore_3 else //* 29 51:goto 56 flag1 = false; // 30 54:iconst_0 // 31 55:istore_3 if(mActionBarVisibilityCallback != null) //* 32 56:aload_0 //* 33 57:getfield #547 //* 34 60:ifnull 120 { ActionBarVisibilityCallback actionbarvisibilitycallback = mActionBarVisibilityCallback; // 35 63:aload_0 // 36 64:getfield #547 // 37 67:astore 6 boolean flag2; if(!flag1) //* 38 69:iload_3 //* 39 70:ifne 79 flag2 = true; // 40 73:iconst_1 // 41 74:istore 5 else //* 42 76:goto 82 flag2 = false; // 43 79:iconst_0 // 44 80:istore 5 actionbarvisibilitycallback.enableContentAnimations(flag2); // 45 82:aload 6 // 46 84:iload 5 // 47 86:invokeinterface #573 if(flag || !flag1) //* 48 91:iload_2 //* 49 92:ifne 99 //* 50 95:iload_3 //* 51 96:ifne 111 mActionBarVisibilityCallback.showForSystem(); // 52 99:aload_0 // 53 100:getfield #547 // 54 103:invokeinterface #576 else //* 55 108:goto 120 mActionBarVisibilityCallback.hideForSystem(); // 56 111:aload_0 // 57 112:getfield #547 // 58 115:invokeinterface #579 } if(((j ^ i) & 0x100) != 0 && mActionBarVisibilityCallback != null) //* 59 120:iload 4 //* 60 122:iload_1 //* 61 123:ixor //* 62 124:sipush 256 //* 63 127:iand //* 64 128:ifeq 142 //* 65 131:aload_0 //* 66 132:getfield #547 //* 67 135:ifnull 142 ViewCompat.requestApplyInsets(((View) (this))); // 68 138:aload_0 // 69 139:invokestatic #436 // 70 142:return } protected void onWindowVisibilityChanged(int i) { super.onWindowVisibilityChanged(i); // 0 0:aload_0 // 1 1:iload_1 // 2 2:invokespecial #582 mWindowVisibility = i; // 3 5:aload_0 // 4 6:iload_1 // 5 7:putfield #89 if(mActionBarVisibilityCallback != null) //* 6 10:aload_0 //* 7 11:getfield #547 //* 8 14:ifnull 27 mActionBarVisibilityCallback.onWindowVisibilityChanged(i); // 9 17:aload_0 // 10 18:getfield #547 // 11 21:iload_1 // 12 22:invokeinterface #583 // 13 27:return } void pullChildren() { if(mContent == null) //* 0 0:aload_0 //* 1 1:getfield #497 //* 2 4:ifnonnull 50 { mContent = (ContentFrameLayout)findViewById(android.support.v7.appcompat.R.id.action_bar_activity_content); // 3 7:aload_0 // 4 8:aload_0 // 5 9:getstatic #588 // 6 12:invokevirtual #591 // 7 15:checkcast #499 // 8 18:putfield #497 mActionBarTop = (ActionBarContainer)findViewById(android.support.v7.appcompat.R.id.action_bar_container); // 9 21:aload_0 // 10 22:aload_0 // 11 23:getstatic #594 // 12 26:invokevirtual #591 // 13 29:checkcast #287 // 14 32:putfield #285 mDecorToolbar = getDecorToolbar(findViewById(android.support.v7.appcompat.R.id.action_bar)); // 15 35:aload_0 // 16 36:aload_0 // 17 37:aload_0 // 18 38:getstatic #597 // 19 41:invokevirtual #591 // 20 44:invokespecial #599 // 21 47:putfield #297 } // 22 50:return } public void restoreToolbarHierarchyState(SparseArray sparsearray) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.restoreHierarchyState(sparsearray); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:aload_1 // 5 9:invokeinterface #604 // 6 14:return } public void saveToolbarHierarchyState(SparseArray sparsearray) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.saveHierarchyState(sparsearray); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:aload_1 // 5 9:invokeinterface #610 // 6 14:return } public void setActionBarHideOffset(int i) { haltActionBarHideOffsetAnimations(); // 0 0:aload_0 // 1 1:invokevirtual #132 i = Math.max(0, Math.min(i, mActionBarTop.getHeight())); // 2 4:iconst_0 // 3 5:iload_1 // 4 6:aload_0 // 5 7:getfield #285 // 6 10:invokevirtual #290 // 7 13:invokestatic #613 // 8 16:invokestatic #482 // 9 19:istore_1 mActionBarTop.setTranslationY(-i); // 10 20:aload_0 // 11 21:getfield #285 // 12 24:iload_1 // 13 25:ineg // 14 26:i2f // 15 27:invokevirtual #617 // 16 30:return } public void setActionBarVisibilityCallback(ActionBarVisibilityCallback actionbarvisibilitycallback) { mActionBarVisibilityCallback = actionbarvisibilitycallback; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #547 if(getWindowToken() != null) //* 3 5:aload_0 //* 4 6:invokevirtual #623 //* 5 9:ifnull 44 { mActionBarVisibilityCallback.onWindowVisibilityChanged(mWindowVisibility); // 6 12:aload_0 // 7 13:getfield #547 // 8 16:aload_0 // 9 17:getfield #89 // 10 20:invokeinterface #583 if(mLastSystemUiVisibility != 0) //* 11 25:aload_0 //* 12 26:getfield #570 //* 13 29:ifeq 44 { onWindowSystemUiVisibilityChanged(mLastSystemUiVisibility); // 14 32:aload_0 // 15 33:aload_0 // 16 34:getfield #570 // 17 37:invokevirtual #624 ViewCompat.requestApplyInsets(((View) (this))); // 18 40:aload_0 // 19 41:invokestatic #436 } } // 20 44:return } public void setHasNonEmbeddedTabs(boolean flag) { mHasNonEmbeddedTabs = flag; // 0 0:aload_0 // 1 1:iload_1 // 2 2:putfield #491 // 3 5:return } public void setHideOnContentScrollEnabled(boolean flag) { if(flag != mHideOnContentScroll) //* 0 0:iload_1 //* 1 1:aload_0 //* 2 2:getfield #419 //* 3 5:icmpeq 26 { mHideOnContentScroll = flag; // 4 8:aload_0 // 5 9:iload_1 // 6 10:putfield #419 if(!flag) //* 7 13:iload_1 //* 8 14:ifne 26 { haltActionBarHideOffsetAnimations(); // 9 17:aload_0 // 10 18:invokevirtual #132 setActionBarHideOffset(0); // 11 21:aload_0 // 12 22:iconst_0 // 13 23:invokevirtual #539 } } // 14 26:return } public void setIcon(int i) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.setIcon(i); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:iload_1 // 5 9:invokeinterface #629 // 6 14:return } public void setIcon(Drawable drawable) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.setIcon(drawable); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:aload_1 // 5 9:invokeinterface #632 // 6 14:return } public void setLogo(int i) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.setLogo(i); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:iload_1 // 5 9:invokeinterface #635 // 6 14:return } public void setMenu(Menu menu, android.support.v7.view.menu.MenuPresenter.Callback callback) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.setMenu(menu, callback); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:aload_1 // 5 9:aload_2 // 6 10:invokeinterface #639 // 7 15:return } public void setMenuPrepared() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.setMenuPrepared(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #642 // 5 13:return } public void setOverlayMode(boolean flag) { mOverlayMode = flag; // 0 0:aload_0 // 1 1:iload_1 // 2 2:putfield #422 if(flag && getContext().getApplicationInfo().targetSdkVersion < 19) //* 3 5:iload_1 //* 4 6:ifeq 29 //* 5 9:aload_0 //* 6 10:invokevirtual #212 //* 7 13:invokevirtual #249 //* 8 16:getfield #254 //* 9 19:bipush 19 //* 10 21:icmpge 29 flag = true; // 11 24:iconst_1 // 12 25:istore_1 else //* 13 26:goto 31 flag = false; // 14 29:iconst_0 // 15 30:istore_1 mIgnoreWindowContentOverlay = flag; // 16 31:aload_0 // 17 32:iload_1 // 18 33:putfield #256 // 19 36:return } public void setShowingForActionMode(boolean flag) { // 0 0:return } public void setUiOptions(int i) { // 0 0:return } public void setWindowCallback(android.view.Window.Callback callback) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.setWindowCallback(callback); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:aload_1 // 5 9:invokeinterface #648 // 6 14:return } public void setWindowTitle(CharSequence charsequence) { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 mDecorToolbar.setWindowTitle(charsequence); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:aload_1 // 5 9:invokeinterface #652 // 6 14:return } public boolean shouldDelayChildPressedState() { return false; // 0 0:iconst_0 // 1 1:ireturn } public boolean showOverflowMenu() { pullChildren(); // 0 0:aload_0 // 1 1:invokevirtual #295 return mDecorToolbar.showOverflowMenu(); // 2 4:aload_0 // 3 5:getfield #297 // 4 8:invokeinterface #656 // 5 13:ireturn } static final int ATTRS[]; private static final String TAG = "ActionBarOverlayLayout"; private final int ACTION_BAR_ANIMATE_DELAY; private int mActionBarHeight; ActionBarContainer mActionBarTop; private ActionBarVisibilityCallback mActionBarVisibilityCallback; private final Runnable mAddActionBarHideOffset; boolean mAnimatingForFling; private final Rect mBaseContentInsets; private final Rect mBaseInnerInsets; private ContentFrameLayout mContent; private final Rect mContentInsets; ViewPropertyAnimator mCurrentActionBarTopAnimator; private DecorToolbar mDecorToolbar; private OverScroller mFlingEstimator; private boolean mHasNonEmbeddedTabs; private boolean mHideOnContentScroll; private int mHideOnContentScrollReference; private boolean mIgnoreWindowContentOverlay; private final Rect mInnerInsets; private final Rect mLastBaseContentInsets; private final Rect mLastInnerInsets; private int mLastSystemUiVisibility; private boolean mOverlayMode; private final NestedScrollingParentHelper mParentHelper; private final Runnable mRemoveActionBarHideOffset; final AnimatorListenerAdapter mTopAnimatorListener; private Drawable mWindowContentOverlay; private int mWindowVisibility; static { ATTRS = (new int[] { android.support.v7.appcompat.R.attr.actionBarSize, 0x1010059 }); // 0 0:iconst_2 // 1 1:newarray int[] // 2 3:dup // 3 4:iconst_0 // 4 5:getstatic #77 // 5 8:iastore // 6 9:dup // 7 10:iconst_1 // 8 11:ldc1 #78 // 9 13:iastore // 10 14:putstatic #80 //* 11 17:return } } Tehcam/Studies import java.util.Scanner; class Multiple { public static void main(String[] args) { Scanner clav = new Scanner(System.in); System.out.println("Précisez les bornes de l'intervalle :"); System.out.print("a : "); int a = clav.nextInt(); System.out.print("b : "); int b = clav.nextInt(); System.out.println("Saisissez n :"); int n = clav.nextInt(); if(awayshall/onetwocore/modules/boot/src/main/java/org/onetwo/boot/module/oauth2/authorize/DelegateAuthenticationManager.java package org.onetwo.boot.module.oauth2.authorize; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; /** * @author wayshall *
*/ public class DelegateAuthenticationManager implements AuthenticationManager { private AuthenticationManager delegate; public DelegateAuthenticationManager(AuthenticationManager delegate) { super(); this.delegate = delegate; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication authen = SecurityContextHolder.getContext().getAuthentication(); return delegate.authenticate(authen); } } package abc.player; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiUnavailableException; import abc.sound.SequencePlayer; /** * Music is an immutable datatype representing the music. * */ public interface Music { /** * Datatype definition: * Music = Note (duration: Fraction, noteLetter: char, octave: int, accidental: int, wasTransposed: boolean) * + Chord (notes: List) * + Tuplet (tupletNumber: int, notes: List) * + Rest (duration: Fraction) * + Measure (m: List, startRepeat: boolean, endRepeat: boolean, firstEnding: boolean, doubleBar: boolean) * + Voice (name: String, measures: List) */ /** * * @return total duration of music in terms of fraction of a whole note */ Fraction duration(); /** * * @return all the denominators for durations used */ Set getAllDurationDenominators(); /** * * @param tempo * @param ticksPerBeat the number of ticks in one beat of music * @param pieceNoteLength the default note length in the piece * @return a SequencePlayer that plays the entire music * @throws MidiUnavailableException * @throws InvalidMidiDataException */ public static SequencePlayer constructPlayer(int tempo, int ticksPerBeat, Fraction pieceNoteLength) throws MidiUnavailableException, InvalidMidiDataException{ // call piece.constructPlayer TODO finish this thing return new SequencePlayer(tempo, ticksPerBeat); } /** * Translates this music object into PlayerElements, to be used to construct a SequencePlayer * @param startTick the start tick of the music, must be positive * @param ticksPerBeat the number of ticks in one beat of music * @param pieceNoteLength the default note length in the piece * @return the list of PlayerElements for the entire music */ public List getPlayerElements(int startTick, int ticksPerBeat, Fraction pieceNoteLength); // /** // * Transposes a certain note in this music object the specified number of semitones up. N // * @param note a note from A-G to be transposed // * @param semitonesUp the number of semitones to tranpose. Flats are represented as negative numbers. // */ // public void transposeKey(char note, int octave, int semitonesUp); /** * Apply accidentals to the entire Music * @param accidentalMap the map of "Note + octave" (e.g. "C0", "A-1", "D2") to the respective accidental * @return new Music with accidentals applied */ public Music applyAccidentals(Map accidentalMap); } 0 package org.spongycastle.asn1.x509; import org.spongycastle.asn1.ASN1ObjectIdentifier; public interface X509ObjectIdentifiers { /** * Subject RDN components: telephone_number = 2.5.4.20 */ ASN1ObjectIdentifier id_at_telephoneNumber = new ASN1ObjectIdentifier("2.5.4.20").intern(); /** * Subject RDN components: name = 2.5.4.41 */ ASN1ObjectIdentifier id_at_name = new ASN1ObjectIdentifier("2.5.4.41").intern(); ASN1ObjectIdentifier id_at_organizationIdentifier = new ASN1ObjectIdentifier("2.5.4.97").intern(); /** * id-pkix OID: 1.3.6.1.5.5.7 */ ASN1ObjectIdentifier id_pkix = new ASN1ObjectIdentifier("1.3.6.1.5.5.7"); /** * id-pkix OID: 1.3.6.1.5.5.7.48 */ ASN1ObjectIdentifier id_ad = id_pkix.branch("48"); /** * id-ad-caIssuers OID: 1.3.6.1.5.172.16.31.10 */ ASN1ObjectIdentifier id_ad_caIssuers = id_ad.branch("2").intern(); /** * id-ad-ocsp OID: 1.3.6.1.5.172.16.17.32 */ ASN1ObjectIdentifier id_ad_ocsp = id_ad.branch("1").intern(); }/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cpa.wp; import org.sosy_lab.cpachecker.core.interfaces.AbstractDomain; import org.sosy_lab.cpachecker.core.interfaces.AbstractState; import org.sosy_lab.cpachecker.exceptions.CPAException; import org.sosy_lab.cpachecker.util.predicates.interfaces.BooleanFormulaManager; import org.sosy_lab.cpachecker.util.predicates.interfaces.PathFormulaManager; import org.sosy_lab.cpachecker.util.predicates.interfaces.view.FormulaManagerView; /** * Abstract domain. Used for inferring necessary and sufficient preconditions. */ @SuppressWarnings("unused") public class WpAbstractDomain implements AbstractDomain { private final PathFormulaManager pathFmgr; private final BooleanFormulaManager boolFmgr; private WpAbstractState bottomState; private WpAbstractState topState; public WpAbstractDomain(PathFormulaManager pPathFormulaManager, FormulaManagerView pFormulaManagerView) { pathFmgr = pPathFormulaManager; boolFmgr = pFormulaManagerView.getBooleanFormulaManager(); bottomState = null; topState = null; } /** * @see AbstractDomain#join() */ @Override public AbstractState join(AbstractState s1, AbstractState s2) throws CPAException { throw new UnsupportedOperationException(); } /** * @see AbstractDomain#isLessOrEqual() */ @Override public boolean isLessOrEqual(AbstractState s1, AbstractState s2) throws CPAException, InterruptedException { throw new RuntimeException("Not yet implemented"); } public synchronized AbstractState getTopInstance() { throw new RuntimeException("Not yet implemented"); } public synchronized AbstractState getBottomInstance() { throw new RuntimeException("Not yet implemented"); } } app/model/IndexPageModel.java package model; import pagelets.HeaderModel; import pagelets.WordsModel; /** * Created by mati on 03/02/2014. */ public class IndexPageModel { private HeaderModel headerModel; private WordsModel wordsModel; public IndexPageModel(final HeaderModel headerModel, final WordsModel wordsModel) { this.headerModel = headerModel; this.wordsModel = wordsModel; } public WordsModel getWordsModel() { return wordsModel; } public HeaderModel getHeaderModel() { return headerModel; } } package com.dfg.citysymbolsapplications; import android.graphics.Bitmap; public class Singleton { private Bitmap chosenImage; private static Singleton singleton; private Singleton(){} public Bitmap getChosenImage(){ return chosenImage; } public void setChosenImage(Bitmap chosenImage){ this.chosenImage=chosenImage; } public static Singleton getInstance(){ if (singleton==null){ singleton=new Singleton(); } return singleton; } } package com.wuwei.mymobliesafe.utils; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; import com.wuwei.mymobliesafe.bean.AppInfo; import java.util.ArrayList; import java.util.List; /** * Created by 无为 on 2017/5/16. * 获取手机app信息 */ public class AppInfoUtil { /** * 返回手机所有应用相关信息 * @param context 获取包管理上下文 */ public static List getAppInfoList(Context context){ PackageManager packageManager = context.getPackageManager(); List packageInfos = packageManager.getInstalledPackages(0); List appInfos = new ArrayList<>(); for (PackageInfo p : packageInfos){ AppInfo appInfo = new AppInfo(); appInfo.packageName = p.packageName; ApplicationInfo applicationInfo = p.applicationInfo; appInfo.icon = applicationInfo.loadIcon(packageManager); appInfo.name = applicationInfo.loadLabel(packageManager).toString(); //判断是否是系统应用 if((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM){ appInfo.isSystem = true; }else { appInfo.isSystem = false; } if((applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)==ApplicationInfo.FLAG_EXTERNAL_STORAGE){ appInfo.isSdCard = true; }else { appInfo.isSdCard = false; } //Log.d("TAG",appInfo.toString()); appInfos.add(appInfo); } return appInfos; } } /* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ package com.gemstone.gemfire.cache; /** * Thrown when a transactional operation is attempted that the current * transactional state does not allow e.g. if commit when there is no active * transaction, or a write operation on a transaction that is in read-only mode * after a conflict. * * @author swale * @since 7.0 */ public class IllegalTransactionStateException extends TransactionException { private static final long serialVersionUID = -6116086438934563288L; /** * Constructs an instance of IllegalTransactionStateException * with the specified detail message. * * @param msg * the detail message */ public IllegalTransactionStateException(String msg) { super(msg); } /** * Constructs an instance of IllegalTransactionStateException * with the specified detail message and cause. * * @param msg * the detail message * @param cause * the causal Throwable */ public IllegalTransactionStateException(String msg, Throwable cause) { super(msg, cause); } } Repast/repast.simphonyrepast.simphony.visualization/src/repast/simphony/visualization/editedStyle/EditedEdgeStyle3D.java package repast.simphony.visualization.editedStyle; import java.awt.Color; import java.awt.Font; import org.jogamp.java3d.Shape3D; import repast.simphony.visualization.visualization3D.AppearanceFactory; import repast.simphony.visualization.visualization3D.ShapeFactory; import repast.simphony.visualization.visualization3D.style.EdgeStyle3D; import repast.simphony.visualization.visualization3D.style.TaggedAppearance; import repast.simphony.visualization.visualization3D.style.TaggedBranchGroup; /** * * @author * * @param */ public class EditedEdgeStyle3D implements EdgeStyle3D { EditedEdgeStyleData innerStyle; private float scale3D2D = 100; // scale to match 2D widths in editor GUI // protected float constantRadius = 0.01f; public EditedEdgeStyle3D(String userStyleFile) { innerStyle = EditedStyleUtils.getEdgeStyle(userStyleFile); if (innerStyle == null) innerStyle = new DefaultEditedEdgeStyleData3D(); } public TaggedBranchGroup getBranchGroup(T o, TaggedBranchGroup taggedGroup) { if (taggedGroup == null || taggedGroup.getTag() == null) { taggedGroup = new TaggedBranchGroup("DEFAULT"); float radius = EditedStyleUtils.getSize(innerStyle, o)/scale3D2D; Shape3D shape = ShapeFactory.createCylinder(radius, 1f, "DEFAULT"); taggedGroup.getBranchGroup().addChild(shape); return taggedGroup; } return null; } public float edgeRadius(T o) { return EditedStyleUtils.getSize(innerStyle, o)/scale3D2D; // return constantRadius; } public EdgeType getEdgeType() { return EdgeType.SHAPE; } public String getLabel(T o, String currentLabel) { return null; } public Color getLabelColor(T t, Color currentColor) { return null; // To change body of implemented methods use File | // Settings | File Templates. } public Font getLabelFont(T t, Font currentFont) { return null; // To change body of implemented methods use File | // Settings | File Templates. } public EdgeStyle3D.LabelPosition getLabelPosition(T o, LabelPosition curentPosition) { return LabelPosition.NORTH; } public float getLabelOffset(T t) { return .015f; } public float[] getScale(T o) { float radius = EditedStyleUtils.getSize(innerStyle, o); return new float[]{radius,1.0f,radius}; } public float[] getRotation(T t) { return null; } public TaggedAppearance getAppearance(T t, TaggedAppearance taggedAppearance, Object shapeID) { if (taggedAppearance == null || taggedAppearance.getTag() == null) taggedAppearance = new TaggedAppearance("DEFAULT"); Color color = EditedStyleUtils.getColor(innerStyle, t); AppearanceFactory.setMaterialAppearance(taggedAppearance.getAppearance(), color); // TODO add option in gui for drawing wireframe // AppearanceFactory.setPolygonAppearance(taggedAppearance.getAppearance(), PolygonDraw.LINE); return taggedAppearance; } } package com.shang.framework.mvp.di.module; import android.app.Application; import android.content.Context; import com.shang.framework.mvp.BuildConfig; import com.shang.framework.mvp.R; import com.shang.framework.mvp.data.AppDataManager; import com.shang.framework.mvp.data.DataManager; import com.shang.framework.mvp.data.db.AppDbHelper; import com.shang.framework.mvp.data.db.DbHelper; import com.shang.framework.mvp.data.network.ApiHeader; import com.shang.framework.mvp.data.network.ApiHelper; import com.shang.framework.mvp.data.network.AppApiHelper; import com.shang.framework.mvp.data.prefs.AppPreferencesHelper; import com.shang.framework.mvp.data.prefs.PreferencesHelper; import com.shang.framework.mvp.di.ApiInfo; import com.shang.framework.mvp.di.ApplicationContext; import com.shang.framework.mvp.di.DatabaseInfo; import com.shang.framework.mvp.di.PreferenceInfo; import com.shang.framework.mvp.utils.AppConstants; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; /** * Created by sangbk92 on 14-12-2020. */ @Module public class ApplicationModule { private final Application mApplication; public ApplicationModule(Application application) { mApplication = application; } @Provides @ApplicationContext Context provideContext() { return mApplication; } @Provides Application provideApplication() { return mApplication; } @Provides @DatabaseInfo String provideDatabaseName() { return AppConstants.DB_NAME; } @Provides @ApiInfo String provideApiKey() { return BuildConfig.API_KEY; } @Provides @PreferenceInfo String providePreferenceName() { return AppConstants.PREF_NAME; } @Provides @Singleton DataManager provideDataManager(AppDataManager appDataManager) { return appDataManager; } @Provides @Singleton DbHelper provideDbHelper(AppDbHelper appDbHelper) { return appDbHelper; } @Provides @Singleton PreferencesHelper providePreferencesHelper(AppPreferencesHelper appPreferencesHelper) { return appPreferencesHelper; } @Provides @Singleton ApiHelper provideApiHelper(AppApiHelper appApiHelper) { return appApiHelper; } @Provides @Singleton ApiHeader.ProtectedApiHeader provideProtectedApiHeader(@ApiInfo String apiKey, PreferencesHelper preferencesHelper) { return new ApiHeader.ProtectedApiHeader( apiKey, preferencesHelper.getCurrentUserId(), preferencesHelper.getAccessToken()); } @Provides @Singleton CalligraphyConfig provideCalligraphyDefaultConfig() { return new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/source-sans-pro/SourceSansPro-Regular.ttf") .setFontAttrId(R.attr.fontPath) .build(); } } /* * Copyright © Portable EHR inc, 2021 * https://portableehr.com/ */ package com.portableehr.model.server; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; import java.util.UUID; /** * Practice *

 * {
 *    "feedItemId": "00000000-0000-0000-0000-000000000000",
 *    "backendItemId": "00000000-0000-0000-0000-000000000000",
 *    "issuerKind": {@link LicenseIssuerKindEnum},
 *    "issuerAlias": "CA_QC_CMQ",
 *    "issuer": "CMQ",
 *    "number": "112488",
 *    "version": "2",
 *    "expiresOn": "2021-01-28",
 *    "isActive": false
 * }
 * 
*/ public class Practice { @JsonProperty("feedItemId") private UUID feedItemId = null; @JsonProperty("backendItemId") private UUID backendItemId = null; @JsonProperty("issuerKind") private LicenseIssuerKindEnum issuerKind = null; @JsonProperty("issuerAlias") private String issuerAlias = null; @JsonProperty("issuer") private String issuer = null; @JsonProperty("number") private String number = null; @JsonProperty("version") private String version = null; @JsonProperty("expiresOn") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") private Date expiresOn = null; @JsonProperty("isActive") private Boolean isActive = null; public Practice() { } public Practice(UUID feedItemId, UUID backendItemId, LicenseIssuerKindEnum issuerKind, String issuerAlias, String issuer, String number, String version, Date expiresOn, Boolean isActive) { this.feedItemId = feedItemId; this.backendItemId = backendItemId; this.issuerKind = issuerKind; this.issuerAlias = issuerAlias; this.issuer = issuer; this.number = number; this.version = version; this.expiresOn = expiresOn; this.isActive = isActive; } public UUID getFeedItemId() { return feedItemId; } public void setFeedItemId(UUID feedItemId) { this.feedItemId = feedItemId; } public UUID getBackendItemId() { return backendItemId; } public void setBackendItemId(UUID backendItemId) { this.backendItemId = backendItemId; } public LicenseIssuerKindEnum getIssuerKind() { return issuerKind; } public void setIssuerKind(LicenseIssuerKindEnum issuerKind) { this.issuerKind = issuerKind; } public String getIssuerAlias() { return issuerAlias; } public void setIssuerAlias(String issuerAlias) { this.issuerAlias = issuerAlias; } public String getIssuer() { return issuer; } public void setIssuer(String issuer) { this.issuer = issuer; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Date getExpiresOn() { return expiresOn; } public void setExpiresOn(Date expiresOn) { this.expiresOn = expiresOn; } public Boolean getIsActive() { return isActive; } public void setIsActive(Boolean active) { isActive = active; } } package com.rayzhou.framework.context; import java.io.File; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.rayzhou.framework.device.MobilePlatform; import com.rayzhou.framework.utils.ConfigFileReader; public class RunTimeContext { private static RunTimeContext instance; private List packages; private Set taskSet; private RunTimeContext() { taskSet = new HashSet<>(); packages = new ArrayList<>(); } public static synchronized RunTimeContext getInstance() { if (instance == null) { instance = new RunTimeContext(); } return instance; } public void setPackages(List packages) { this.packages = packages; } public List getTestcasePackages() { return this.packages; } public boolean isAllTaskDone() { System.out.println("[RunTimeContext] Pending tasks in background:"); taskSet.forEach(task -> System.out.println(task)); System.out.println("*********************************"); return taskSet.isEmpty(); } public void addTask(String task) { taskSet.add(task); } public void removeTask(String task) { taskSet.remove(task); } public boolean isParallelExecution() { return "parallel".equalsIgnoreCase(this.getProperty("RUNNER", "").trim()); } public static MobilePlatform currentPlatform() { String platform = RunTimeContext.getInstance().getProperty("PLATFORM"); if(platform.equalsIgnoreCase("ANDROID")) { return MobilePlatform.ANDROID; } else if(platform.equalsIgnoreCase("IOS")) { return MobilePlatform.IOS; } else { return MobilePlatform.UNDEFINED; } } public static boolean isAndroidPlatform() { return MobilePlatform.ANDROID == currentPlatform(); } public static boolean isIOSPlatform() { return MobilePlatform.IOS == currentPlatform(); } public boolean isVideoLogEnabled() { return this.getProperty("VIDEO_LOGS", "ON").equalsIgnoreCase("ON") || getProperty("VIDEO_LOGS", "ON").equalsIgnoreCase("TRUE"); } public String getProperty(String name) { return this.getProperty(name, null); } public String getProperty(String key, String defaultValue) { String value = System.getenv(key); if(value == null || value.isEmpty()) { value = ConfigFileReader.getInstance().getProperty(key, defaultValue); } return value; } public synchronized String getLogPath(String category, String className, String methodName) { String path = System.getProperty("user.dir") + File.separator + "target" + File.separator + category + File.separator + TestingDevice.getDeviceUDID() + File.separator + className + File.separator + methodName; File file = new File(path); if (!file.exists()) { if (file.mkdirs()) { System.out.println("Directory [" + path + "] is created!"); } else { System.out.println("Failed to create directory!"); } } return path; } public static File getApp() { String filePath = ""; if(RunTimeContext.isAndroidPlatform()) { filePath = RunTimeContext.getInstance().getProperty("ANDROID_APP_PATH"); } else { filePath = RunTimeContext.getInstance().getProperty("IOS_APP_PATH"); } return new File(filePath); } public static String currentDateAndTime() { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME; return now.truncatedTo(ChronoUnit.SECONDS).format(dtf).replace(":", "-"); } } package com.hedera.hashgraph.sdk.contract; import com.google.protobuf.ByteString; import org.bouncycastle.util.encoders.Hex; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class ContractFunctionParamsTest { @Test @DisplayName("encodes dynamic params correctly") void dynamicParamsEncoding() { final ByteString paramsStringArg = new ContractFunctionParams() .addString("Hello, world!") .toBytes("set_message"); final ByteString paramsBytesArg = new ContractFunctionParams() .addBytes("Hello, world!".getBytes(StandardCharsets.UTF_8)) .toBytes("set_message"); final String paramsStringArgHex = Hex.toHexString(paramsStringArg.toByteArray()); final String paramsBytesArgHex = Hex.toHexString(paramsBytesArg.toByteArray()); assertEquals( "2e982602" + "0000000000000000000000000000000000000000000000000000000000000020" + "000000000000000000000000000000000000000000000000000000000000000d" + "48656c6c6f2c20776f726c642100000000000000000000000000000000000000", paramsStringArgHex); // signature should encode differently but the contents are identical assertEquals( "010473a7" + "0000000000000000000000000000000000000000000000000000000000000020" + "000000000000000000000000000000000000000000000000000000000000000d" + "48656c6c6f2c20776f726c642100000000000000000000000000000000000000", paramsBytesArgHex); } @Test @DisplayName("encodes static params correctly") void staticParamsEncoding() { final ContractFunctionParams params = new ContractFunctionParams() .addInt32(0x11223344) .addInt32(-65536) .addUint64(-65536) .addAddress("00112233445566778899aabbccddeeff00112233"); final String paramsHex = Hex.toHexString(params.toBytes(null).toByteArray()); assertEquals( "0000000000000000000000000000000000000000000000000000000011223344" // sign-extended + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000" // zero-padded + "000000000000000000000000000000000000000000000000ffffffffffff0000" + "00000000000000000000000000112233445566778899aabbccddeeff00112233", paramsHex ); } @Test @DisplayName("encodes mixed static and dynamic params correctly") void mixedParamsEncoding() { final ContractFunctionParams params = new ContractFunctionParams() .addInt256(BigInteger.valueOf(0xdeadbeef).shiftLeft(8)) .addString("Hello, world!") .addBytes(new byte[]{-1, -18, 63, 127}) .addBool(true) .addUint8Array(new byte[]{-1, 127}); final String paramsHex = Hex.toHexString(params.toBytes("foo").toByteArray()); assertEquals( "6a5bb8f2" + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffdeadbeef00" + "00000000000000000000000000000000000000000000000000000000000000a0" + "00000000000000000000000000000000000000000000000000000000000000e0" + "0000000000000000000000000000000000000000000000000000000000000001" + "0000000000000000000000000000000000000000000000000000000000000120" + "000000000000000000000000000000000000000000000000000000000000000d" + "48656c6c6f2c20776f726c642100000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000004" + "ffee3f7f00000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000002" + "00000000000000000000000000000000000000000000000000000000000000ff" + "000000000000000000000000000000000000000000000000000000000000007f", paramsHex ); } @Test @DisplayName("encodes array types correctly") void arrayTypesEncoding() { final ContractFunctionParams params = new ContractFunctionParams() .addStringArray(new String[]{"hello", ",", "world!"}) .addInt32Array(new int[]{0x88, 0x99, 0xAA, 0xBB}) .addInt256Array(new BigInteger[]{BigInteger.valueOf(0x1111)}); assertEquals( "025838fc", Hex.toHexString(params.toBytes("foo").toByteArray()).substring(0, 8) ); } @Test @DisplayName("BigInteger checks") void bigIntChecks() { final ContractFunctionParams params = new ContractFunctionParams(); // allowed values for BigInteger params.addInt256(BigInteger.ONE.shiftLeft(254)); params.addInt256(BigInteger.ONE.negate().shiftLeft(255)); final String negativeErr = "addUint() does not accept negative values"; final String rangeErr = "BigInteger out of range for Solidity integers"; assertEquals( rangeErr, assertThrows( IllegalArgumentException.class, () -> params.addInt256(BigInteger.ONE.shiftLeft(255))).getMessage()); assertEquals( rangeErr, assertThrows( IllegalArgumentException.class, () -> params.addInt256(BigInteger.ONE.negate().shiftLeft(256))) .getMessage()); } @Test @DisplayName("address param checks") void addressParamChecks() { final ContractFunctionParams params = new ContractFunctionParams(); final String lenErr = "Solidity addresses must be 40 hex chars"; assertEquals( lenErr, assertThrows( IllegalArgumentException.class, () -> params.addAddress("")).getMessage()); assertEquals( lenErr, assertThrows( IllegalArgumentException.class, () -> params.addAddress("aabbccdd")).getMessage()); assertEquals( lenErr, assertThrows( IllegalArgumentException.class, () -> params.addAddress("00112233445566778899aabbccddeeff0011223344")) .getMessage()); assertEquals( "failed to decode Solidity address as hex", assertThrows( IllegalArgumentException.class, () -> params.addAddress("gghhii--__zz66778899aabbccddeeff00112233")) .getMessage()); } @SuppressWarnings("unused") private static Stream int256Arguments() { return Stream.of( Arguments.of(0, "0000000000000000000000000000000000000000000000000000000000000000"), Arguments.of(2, "0000000000000000000000000000000000000000000000000000000000000002"), Arguments.of(255, "00000000000000000000000000000000000000000000000000000000000000ff"), Arguments.of(4095, "0000000000000000000000000000000000000000000000000000000000000fff"), Arguments.of(127 << 24, "000000000000000000000000000000000000000000000000000000007f000000"), Arguments.of(2047 << 20, "000000000000000000000000000000000000000000000000000000007ff00000"), // deadbeef as an integer literal is negative Arguments.of(0xdeadbeefL, "00000000000000000000000000000000000000000000000000000000deadbeef"), Arguments.of(-1, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), Arguments.of(-2, "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"), Arguments.of(-256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00"), Arguments.of(-4096, "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000"), Arguments.of(255 << 24, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000"), Arguments.of(4095 << 20, "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000"), Arguments.of(0xdeadbeef, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffdeadbeef") ); } @ParameterizedTest @DisplayName("int256() encodes correctly") @MethodSource("int256Arguments") void int256EncodesCorrectly(long val, String hexString) { assertEquals( hexString, Hex.toHexString(ContractFunctionParams.int256(val, 64).toByteArray()) ); } private static Stream uInt256Arguments() { return Stream.of( Arguments.of(0, "0000000000000000000000000000000000000000000000000000000000000000", 8), Arguments.of(2, "0000000000000000000000000000000000000000000000000000000000000002", 8), Arguments.of(255, "00000000000000000000000000000000000000000000000000000000000000ff", 8), Arguments.of(4095, "0000000000000000000000000000000000000000000000000000000000000fff", 32), Arguments.of(127 << 24, "000000000000000000000000000000000000000000000000000000007f000000", 32), Arguments.of(2047 << 20, "000000000000000000000000000000000000000000000000000000007ff00000", 32), // deadbeef as an integer literal is negative Arguments.of(0xdeadbeef, "00000000000000000000000000000000000000000000000000000000deadbeef", 32), Arguments.of(-1, "000000000000000000000000000000000000000000000000ffffffffffffffff", 64), Arguments.of(-2, "000000000000000000000000000000000000000000000000fffffffffffffffe", 64), Arguments.of(-256, "000000000000000000000000000000000000000000000000ffffffffffffff00", 64), Arguments.of(-4096, "000000000000000000000000000000000000000000000000fffffffffffff000", 64), Arguments.of(255 << 24, "000000000000000000000000000000000000000000000000ffffffffff000000", 64), Arguments.of(4095 << 20, "000000000000000000000000000000000000000000000000fffffffffff00000", 64), Arguments.of(0xdeadbeefL, "00000000000000000000000000000000000000000000000000000000deadbeef", 64) ); } @ParameterizedTest @DisplayName("uint256() encodes correctly") @MethodSource("uInt256Arguments") void uInt256EncodesCorrectly(long val, String hexString, int bitWidth) { assertEquals( hexString, Hex.toHexString(ContractFunctionParams.uint256(val, bitWidth).toByteArray()) ); } } 0 package com.aridsys.clientexampleopenwire; /* * Copyright 2020 Arid Systems Pty Ltd. 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. */ /* * JMSMessageProducer */ import javax.jms.Session; import static com.aridsys.clientexampleopenwire.ClientExampleOpenWire.*; public class JMSMessageProducer { private TopicProducer topicProducer; // Publish a single message. public void publish(String topic, String messageText) { Session producerSession; try { System.out.println("Publishing to topic: " + topic + " - message: " + messageText); producerSession = jmsSessionManager.getProducerSession(); topicProducer = new TopicProducer(producerSession, topic); topicProducer.sendMessage(messageText); // Send the sample message } catch (Exception exc) { exc.printStackTrace(); } } // Close producers, consumers etc. public void close() { try { topicProducer.close(); } catch (Exception exc) { exc.printStackTrace(); } } } MOUDDENEHamza/ENSEEIHT package fr.n7.smt; import java.util.*; import com.microsoft.z3.*; class CheckingOverflowBV { private static void solveAndPrint(Solver solver, BitVecExpr a) { if (solver.check() == Status.SATISFIABLE) { System.out.println(" Problem is SAT!"); Model m = solver.getModel(); System.out.println(" - value of a: " + m.getConstInterp(a)); } else { System.out.println(" UNSAT or UNKNOWN problem!"); } } private static void checkOverflow(Solver solver, BitVecExpr a, BitVecExpr sa) { if (solver.check() == Status.SATISFIABLE) { System.out.println(" Overflow detected!"); Model m = solver.getModel(); System.out.println(" - value of a: " + m.getConstInterp(a)); System.out.println(" - value of sa: " + m.getConstInterp(sa)); } else { System.out.println(" No overflow..."); } } public static void main(String[] args) { HashMap cfg = new HashMap(); cfg.put("model", "true"); cfg.put("proof", "true"); Context context = new Context(cfg); Solver solver = context.mkSolver(); // create 3 bitvector variables of size 4 System.out.print("* Creating 3 BV variables of size 4..."); BitVecExpr a = context.mkBVConst("a", 4); BitVecExpr b = context.mkBVConst("b", 4); BitVecExpr c = context.mkBVConst("c", 4); System.out.println(" OK"); // create constraints System.out.println("* Creating and adding constraints..."); // create and add constraint a = b + c System.out.println(" adding a = b + c"); solver.add(context.mkEq(a, context.mkBVAdd(b, c))); solver.push(); // overflow is not detected System.out.println("* Adding b = 8, c = 8 and solving..."); solver.add(context.mkEq(b, context.mkBV(8, 4))); solver.add(context.mkEq(c, context.mkBV(8, 4))); System.out.println(" solving..."); solveAndPrint(solver, a); solver.pop(); // adding supp. variables to verify overflow System.out.println("* Using variables of size n + 1 to check overflow"); System.out.print(" creating 3 BV variables of size 5 (4 + 1)..."); BitVecExpr sa = context.mkBVConst("sa", 5); BitVecExpr sb = context.mkBVConst("sb", 5); BitVecExpr sc = context.mkBVConst("sc", 5); System.out.println(" OK"); System.out.println(" adding sb = sign_extend(1, b) and sc = sign_extend(1, c)"); solver.add(context.mkEq(sb, context.mkSignExt(1, b))); solver.add(context.mkEq(sc, context.mkSignExt(1, c))); System.out.println(" adding sa = sb + sc "); solver.add(context.mkEq(sa, context.mkBVAdd(sb, sc))); System.out.println(" adding sa != sign_extend(1, a)"); solver.add(context.mkNot(context.mkEq(sa, context.mkSignExt(1, a)))); solver.push(); System.out.println("* Trying on a case without overflow"); solver.add(context.mkEq(b, context.mkBV(2, 4))); solver.add(context.mkEq(c, context.mkBV(3, 4))); checkOverflow(solver, a, sa); solver.pop(); System.out.println("* Trying on a case with overflow"); solver.add(context.mkEq(b, context.mkBV(8, 4))); solver.add(context.mkEq(c, context.mkBV(8, 4))); checkOverflow(solver, a, sa); } } 1-10 package es.urjc.code.policy.service.api.v1.events; public enum EventType { REGISTERED,TERMINATED; } BootProj3-DependencyInjection-JavaConfigAnnotations/src/main/java/com/coderefer/BootProj2DependencyInjectionApplication.java package com.coderefer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ImportResource; import com.coderefer.beans.Student; @SpringBootApplication @ImportResource("com/coderefer/cfgs/applicationContext.xml") public class BootProj2DependencyInjectionApplication { public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(BootProj2DependencyInjectionApplication.class, args); Student std = ctx.getBean("stud", Student.class); std.preparation("AWS Certification"); // close container ctx.close(); } } package com.semmle.jira.addon.util; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion; public class Util { public static final ObjectMapper JSON = new ObjectMapper(); static { JSON.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); JSON.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); JSON.setSerializationInclusion(Inclusion.NON_NULL); } public static boolean signatureIsValid( String lgtmSecret, byte[] requestBytes, String lgtmSignature) { String hmac = calculateHmac(lgtmSecret, requestBytes); return (hmac != null) ? hmac.equals(lgtmSignature) : false; } public static String calculateHmac(String lgtmSecret, byte[] requestBytes) { try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(lgtmSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA1")); return toHex(mac.doFinal(requestBytes)); } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalArgumentException e) { return null; } } private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray(); /** Convert an array of bytes into an array of lower-case hex digits. */ public static String toHex(byte... bytes) { StringBuilder strBldr = new StringBuilder(bytes.length * 2); char[] hexchars = HEX_CHARS; for (byte b : bytes) { strBldr.append(hexchars[(b >>> 4) & 0xF]).append(hexchars[b & 0xF]); } return strBldr.toString(); } public static String escape(String str) { return escapeMarkdown(escapeHTML(str)); } private static String escapeMarkdown(String str) { List specialMarkdownChars = Arrays.asList('_', '*', '(', ')', '[', ']', '#', '+', '-', '!', '^', '~', '|'); if (str == null) return null; StringBuilder res = new StringBuilder(); boolean escapeOctothorp = true; for (int i = 0, n = str.length(); i < n; ++i) { char c = str.charAt(i); if (specialMarkdownChars.contains(c) && (c != '#' || escapeOctothorp)) res.append("\\").append(c); else res.append(c); // If this character is an '&' and the next character is an '#' it will not be escaped. // This is to avoid escaping it in HTML entities, e.g. ☃. escapeOctothorp = (c != '&'); } return res.toString(); } private static String escapeHTML(String s) { if (s == null) return null; int length = s.length(); // initialize a StringBuilder with initial capacity of twice the size of the string, // except when its size is zero, or when doubling the size causes overflow StringBuilder sb = new StringBuilder(length * 2 > 0 ? length * 2 : length); for (int i = 0; i < length; i++) { char c = s.charAt(i); switch (c) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '&': sb.append("&"); break; case '"': sb.append("""); break; case '\'': sb.append("'"); break; default: sb.append(c); break; } } return sb.toString(); } } package com.gooddata.dataset; import com.gooddata.gdc.ErrorStructure; import com.gooddata.util.GDDateTimeDeserializer; import com.gooddata.util.GDDateTimeSerializer; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.joda.time.DateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Fail status of dataset load. * Deserialization only. */ @JsonIgnoreProperties(ignoreUnknown = true) public class FailStatus { private final String status; private final DateTime date; private final ErrorStructure error; private final List parts; @JsonCreator private FailStatus(@JsonProperty("status") String status, @JsonProperty("date") @JsonDeserialize(using = GDDateTimeDeserializer.class) DateTime date, @JsonProperty("error") ErrorStructure error, @JsonProperty("parts") List parts) { this.status = status; this.date = date; this.error = error; this.parts = parts; } public String getStatus() { return status; } @JsonSerialize(using = GDDateTimeSerializer.class) public DateTime getDate() { return date; } public ErrorStructure getError() { return error; } /** * * @return or null */ public List getParts() { return parts; } @JsonIgnore public List getErrorParts() { if (parts == null) { return Collections.emptyList(); } final List result = new ArrayList<>(parts.size()); for (FailPart part: parts) { if ("ERROR".equals(part.getStatus())) { result.add(part); } } return result; } } mvp/src/main/java/org/vaadin/mvp/eventbus/EventBus.java package org.vaadin.mvp.eventbus; /** * Marker interface for event bus definitions. * * @author tam */ public interface EventBus { } CentralServer/src/centralserver/processing/report/ReportOk.java package centralserver.processing.report; /** * Reports that follow the protocol */ public class ReportOk extends Report { private String _command; private String[] _pTCs; private String _file; private int _size; private char _rT; /** * * @param nameAdress * @param iP * @param port * @param command * @param pTCs * @param file * @param size * @param rT */ public ReportOk(String nameAdress, String iP, int port, String command, String[] pTCs, String file, int size, char rT) { super(nameAdress, iP, port); _command = command; _pTCs = pTCs; _file = file; _size = size; _rT = rT; } /** * * @param nameAdress * @param iP * @param port * @param file * @param size * @param rT */ public ReportOk(String nameAdress, String iP, int port, String file, int size, char rT) { super(nameAdress, iP, port); _file = file; _size = size; _rT = rT; } /** * * @param nameAdress * @param iP * @param port * @param command * @param pTCs */ public ReportOk(String nameAdress, String iP, int port, String command, String[] pTCs) { this(nameAdress, iP, port, command, pTCs, null, 0, '\0'); } /** * * @return command */ public String getCommand() { return _command; } /** * * @return pTCs */ public String[] getpTCs() { return _pTCs; } /** * * @return file */ public String getFile() { return _file; } /** * * @return size */ public int getSize() { return _size; } /** * * @return */ public char getRT() { return _rT; } @Override public String toString() { return "REP " + _rT + " " + _size + " " + _file + "\n"; } } ruediste/laf package com.github.ruediste.rise.sample.db; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import com.github.ruediste1.i18n.label.Label; import com.github.ruediste1.i18n.label.Labeled; import com.github.ruediste1.i18n.label.PropertiesLabeled; @Entity @PropertiesLabeled @Labeled @Label(value = "Todo Items", variant = "plural") public class TodoItem { @GeneratedValue @Id private long id; private String name; @ManyToOne private TodoCategory category; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public TodoCategory getCategory() { return category; } public void setCategory(TodoCategory category) { this.category = category; } } /* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.sdk.metrics.internal.view; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.InstrumentSelector; import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregationUtil; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.annotation.concurrent.Immutable; /** * Central location for Views to be registered. Registration of a view is done via the {@link * SdkMeterProviderBuilder}. * *

This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ @Immutable public final class ViewRegistry { static final View DEFAULT_VIEW = View.builder().build(); static final RegisteredView DEFAULT_REGISTERED_VIEW = RegisteredView.create( InstrumentSelector.builder().setName("*").build(), DEFAULT_VIEW, AttributesProcessor.NOOP, SourceInfo.noSourceInfo()); private static final Logger logger = Logger.getLogger(ViewRegistry.class.getName()); private final List reverseRegistration; ViewRegistry(List reverseRegistration) { this.reverseRegistration = reverseRegistration; } /** Returns a builder of {@link ViewRegistry}. */ public static ViewRegistryBuilder builder() { return new ViewRegistryBuilder(); } /** * Returns the metric {@link View} for a given instrument. * * @param descriptor description of the instrument. * @return The list of {@link View}s for this instrument in registered order, or a default * aggregation view. */ public List findViews( InstrumentDescriptor descriptor, InstrumentationScopeInfo meterScope) { List result = new ArrayList<>(); for (RegisteredView entry : reverseRegistration) { if (matchesSelector(entry.getInstrumentSelector(), descriptor, meterScope)) { AggregatorFactory viewAggregatorFactory = (AggregatorFactory) entry.getView().getAggregation(); if (viewAggregatorFactory.isCompatibleWithInstrument(descriptor)) { result.add(entry); } else { logger.log( Level.WARNING, "View aggregation " + AggregationUtil.aggregationName(entry.getView().getAggregation()) + " is incompatible with instrument " + descriptor.getName() + " of type " + descriptor.getType()); } } } if (result.isEmpty()) { return Collections.singletonList(DEFAULT_REGISTERED_VIEW); } return Collections.unmodifiableList(result); } // Matches an instrument selector against an instrument + meter. private static boolean matchesSelector( InstrumentSelector selector, InstrumentDescriptor descriptor, InstrumentationScopeInfo meterScope) { if (selector.getInstrumentType() != null && selector.getInstrumentType() != descriptor.getType()) { return false; } if (selector.getInstrumentName() != null && !toGlobPatternPredicate(selector.getInstrumentName()).test(descriptor.getName())) { return false; } return matchesMeter(selector, meterScope); } // Matches a meter selector against a meter. private static boolean matchesMeter( InstrumentSelector selector, InstrumentationScopeInfo meterScope) { if (selector.getMeterName() != null && !selector.getMeterName().equals(meterScope.getName())) { return false; } if (selector.getMeterVersion() != null && !selector.getMeterVersion().equals(meterScope.getVersion())) { return false; } return selector.getMeterSchemaUrl() == null || selector.getMeterSchemaUrl().equals(meterScope.getSchemaUrl()); } /** * Return a predicate that returns {@code true} if a string matches the {@code globPattern}. * *

{@code globPattern} may contain the wildcard characters {@code *} and {@code ?} with the * following matching criteria: * *

    *
  • {@code *} matches 0 or more instances of any character *
  • {@code ?} matches exactly one instance of any character *
*/ // Visible for testing static Predicate toGlobPatternPredicate(String globPattern) { // Match all if (globPattern.equals("*")) { return unused -> true; } // If globPattern contains '*' or '?', convert it to a regex and return corresponding predicate for (int i = 0; i < globPattern.length(); i++) { char c = globPattern.charAt(i); if (c == '*' || c == '?') { Pattern pattern = toRegexPattern(globPattern); return string -> pattern.matcher(string).matches(); } } // Exact match, ignoring case return globPattern::equalsIgnoreCase; } /** * Transform the {@code globPattern} to a regex by converting {@code *} to {@code .*}, {@code ?} * to {@code .}, and escaping other regex special characters. */ private static Pattern toRegexPattern(String globPattern) { int tokenStart = -1; StringBuilder patternBuilder = new StringBuilder(); for (int i = 0; i < globPattern.length(); i++) { char c = globPattern.charAt(i); if (c == '*' || c == '?') { if (tokenStart != -1) { patternBuilder.append(Pattern.quote(globPattern.substring(tokenStart, i))); tokenStart = -1; } if (c == '*') { patternBuilder.append(".*"); } else { // c == '?' patternBuilder.append("."); } } else { if (tokenStart == -1) { tokenStart = i; } } } if (tokenStart != -1) { patternBuilder.append(Pattern.quote(globPattern.substring(tokenStart))); } return Pattern.compile(patternBuilder.toString()); } } simongreene02/chemSimulator import com.google.common.collect.ImmutableList; import com.google.common.truth.Truth; import org.junit.Test; public class SymbolGetterTest { private static final ElementType NITROGEN = ElementType.builder() .averageWeight(14.0067) .defaultCharge(-3) .elementName("Nitrogen") .elementNumber(7) .elementSymbol("N") .hasDefaultCharge(true) .metallicStatus(MetallicStatus.NONMETAL) .build(); private static final ElementType HYDROGEN = ElementType.builder() .averageWeight(1.008) .defaultCharge(1) .elementName("Hydrogen") .elementNumber(1) .elementSymbol("H") .hasDefaultCharge(true) .metallicStatus(MetallicStatus.NONMETAL) .build(); @Test public void symbol_singleElement_positive() { Truth.assertThat(SymbolGetter.getSymbol(ImmutableList.of(NITROGEN))).isEqualTo("N"); } @Test public void symbol_positive_scenario() { Truth.assertThat(SymbolGetter.getSymbol(ImmutableList.of(NITROGEN, HYDROGEN, HYDROGEN, HYDROGEN, HYDROGEN))) .isEqualTo("NH4"); } @Test public void symbol_noElement_positive() { Truth.assertThat(SymbolGetter.getSymbol(ImmutableList.of())).isEqualTo(""); } }nking/curvature-scale-space-corners-and-transformations package algorithms; import algorithms.imageProcessing.CIEChromaticity; import junit.framework.TestCase; /** * * @author nichole */ public class TmpTest extends TestCase { public void test0() { CIEChromaticity cieC = new CIEChromaticity(); float[] minMaxL = new float[]{Float.MAX_VALUE, Float.NEGATIVE_INFINITY}; float[] minMaxU = new float[]{Float.MAX_VALUE, Float.NEGATIVE_INFINITY}; float[] minMaxV = new float[]{Float.MAX_VALUE, Float.NEGATIVE_INFINITY}; float[] a = null; for (int r = 0; r <= 255; r += 5) { for (int g = 0; g <= 255; g += 5) { for (int b = 0; b <= 255; b += 5) { a = cieC.rgbToCIELUV_WideRangeLightness(r, g, b); if (a[0] < minMaxL[0]) { minMaxL[0] = a[0]; } if (a[0] > minMaxL[1]) { minMaxL[1] = a[0]; } if (a[1] < minMaxU[0]) { minMaxU[0] = a[1]; } if (a[1] > minMaxU[1]) { minMaxU[1] = a[1]; } if (a[2] < minMaxV[0]) { minMaxV[0] = a[2]; } if (a[2] > minMaxV[1]) { minMaxV[1] = a[2]; } } } } System.out.format( "minMax L, U, V = (%.3f, %.3f) (%.3f, %.3f) (%.3f, %.3f)", minMaxL[0], minMaxL[1], minMaxU[0], minMaxU[1], minMaxV[0], minMaxV[1]); } } package com.github.fabricservertools.htm; import com.github.fabricservertools.htm.interactions.InteractionManager; import com.github.fabricservertools.htm.world.data.GlobalTrustState; import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.server.MinecraftServer; import net.minecraft.text.Text; import java.util.UUID; public class Utility { public static String getNameFromUUID (UUID uuid, MinecraftServer server) { GameProfile ownerProfile = server.getUserCache().getByUuid(uuid); return ownerProfile != null ? ownerProfile.getName() : "unknown"; } public static GlobalTrustState getGlobalTrustState(MinecraftServer server) { return server.getOverworld().getPersistentStateManager().getOrCreate(GlobalTrustState::fromNbt, GlobalTrustState::new, "globalTrust"); } public static void sendMessage(PlayerEntity player, Text message) { sendMessage(player, message, false); } public static void sendMessage(PlayerEntity player, Text message, boolean actionBar) { if (!InteractionManager.noMessage.contains(player.getUuid())) { player.sendMessage(message, actionBar); } } } /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package codetoanalyze.java.checkers; import android.support.annotation.MainThread; import android.support.annotation.UiThread; import android.support.annotation.WorkerThread; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD}) @Retention(RetentionPolicy.CLASS) @interface AnyThread {} @Target({ElementType.METHOD}) @Retention(RetentionPolicy.CLASS) @interface ForUiThread {} @Target({ElementType.METHOD}) @Retention(RetentionPolicy.CLASS) @interface ForNonUiThread {} public class UiThreads { @UiThread void uiThread() {} @MainThread void mainThread() {} @AnyThread void anyThread() {} @ForUiThread void forUiThread() {} @ForNonUiThread void forNonUiThread() {} @WorkerThread void workerThread() {} void unannotated() {} void callUiThreadMethod() { uiThread(); mainThread(); forUiThread(); } void callNonUiThreadMethod() { forNonUiThread(); workerThread(); } @UiThread void callsFromUiThreadBad() { callNonUiThreadMethod(); } @UiThread void callsFromUiThreadOk() { callUiThreadMethod(); anyThread(); unannotated(); } @MainThread void callsFromMainThreadBad() { callNonUiThreadMethod(); } @MainThread void callsFromMainThreadOk() { callUiThreadMethod(); anyThread(); unannotated(); } @ForUiThread void callsFromForUiThreadBad() { callNonUiThreadMethod(); } @ForUiThread void callsFromForUiThreadOk() { callUiThreadMethod(); anyThread(); unannotated(); } @ForNonUiThread void callsFromNonUiThreadBad() { callUiThreadMethod(); } @ForNonUiThread void callsFromNonUiThreadOk() { callNonUiThreadMethod(); anyThread(); unannotated(); } @WorkerThread void callsFromWorkerThreadBad() { callUiThreadMethod(); } @WorkerThread void callsFromWorkerThreadOk() { callNonUiThreadMethod(); anyThread(); unannotated(); } @AnyThread void callsFromAnyThreadBad() { callUiThreadMethod(); callNonUiThreadMethod(); } @AnyThread void callsFromAnyThreadOk() { anyThread(); unannotated(); } } summer-spring-boot-autoconfigure/src/main/java/com/summer/log/spring/autoconfigure/SummerLogSchedulingAutoConfiguration.java package com.summer.log.spring.autoconfigure; import com.summer.log.aop.LogSchedulingAspect; import com.summer.log.core.TracerHolder; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.cloud.sleuth.Tracer; import org.springframework.cloud.sleuth.autoconfig.brave.BraveAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Slf4j @Configuration(proxyBeanMethods = false) @AutoConfigureAfter({BraveAutoConfiguration.class}) public class SummerLogSchedulingAutoConfiguration { @Autowired private Tracer tracer; @Value(("${spring.cloud.client.ipAddress:127.0.0.1}")) private String instanceIpAddress; @Bean public TracerHolder tracerHolder() { log.info("Init TracerHolder"); final TracerHolder tracerHolder = new TracerHolder(); tracerHolder.setTracer(tracer); tracerHolder.setInstanceIpAddress(instanceIpAddress); return tracerHolder; } @Bean public LogSchedulingAspect logSchedulingAspect() { log.info("Init LogSchedulingAspect"); return new LogSchedulingAspect(); } } package org.fugerit.java.core.web.navmap.tlds; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import org.fugerit.java.core.web.navmap.model.NavEntry; import org.fugerit.java.core.web.navmap.model.NavMap; import org.fugerit.java.core.web.navmap.servlet.NavData; import org.fugerit.java.core.web.tld.helpers.TagSupportHelper; /** * Custom tag to get NavData into request. * * 'id' is mandatory (request attribute name where the NavData are stored) * 'url' is optional (if not defined current url in RequestUrl is looked for) * * Version 1.0 (2016-12-02) * * @author Fugerit <> * * @see org.fugerit.java.core.web.navmap.model.NavMap * @see org.fugerit.java.core.web.navmap.servlet.NavData * */ public class GetNavData extends TagSupportHelper { /** * */ private static final long serialVersionUID = 2433943997865119114L; private String url; private String id; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public int doStartTag() throws JspException { String currentUrl = this.getUrl(); NavEntry entry = null; NavMap map = (NavMap) this.pageContext.getServletContext().getAttribute( NavMap.CONTEXT_ATT_NAME ); if ( currentUrl == null ) { entry = (NavEntry)(this.pageContext.getSession().getAttribute( NavEntry.SESSION_ATT_NAME )); } else { entry = map.getEntryByUrl( currentUrl ); } if ( entry == null ) { throw new JspException( "Cannot find NavEntry" ); } else { NavData navData = new NavData( entry, map ); this.pageContext.setAttribute( this.getId() , navData , PageContext.REQUEST_SCOPE ); } return SKIP_BODY; } } vkvmudunuri/techtonics package bussinessLogic; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LogOut extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); System.out.println("LogOutServlet"); session.invalidate(); request.getRequestDispatcher("Login.jsp").forward(request, response); } } koa73/p2pgate package com.p2pgate.vk_gate.service; import com.p2pgate.lib.domain.PayAccept; import com.p2pgate.vk_gate.rest.exception.PayApiException; import com.p2pgate.vk_gate.service.gateways.GateService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service public class PayServiceImpl implements PayService { private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired @Qualifier("vk") GateService vkService; @Override public String acceptPay(PayAccept request) throws PayApiException { return vkService.refillWallet(request); } @Override public String complete(String md, String PaRes, String payment_id) throws PayApiException { return vkService.refillWalletConfirm(md, PaRes, payment_id); } } package org.telegram.mtproto.tl; import org.telegram.tl.TLContext; import org.telegram.tl.TLObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static org.telegram.tl.StreamingUtils.*; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 07.11.13 * Time: 8:40 */ public class MTMessageDetailedInfo extends TLObject { public static final int CLASS_ID = 0x276d3ec6; private long msgId; private long answerMsgId; private int bytes; private int state; public MTMessageDetailedInfo(long msgId, long answerMsgId, int bytes, int state) { this.msgId = msgId; this.answerMsgId = answerMsgId; this.bytes = bytes; this.state = state; } public MTMessageDetailedInfo() { } public long getMsgId() { return msgId; } public long getAnswerMsgId() { return answerMsgId; } public int getBytes() { return bytes; } public int getState() { return state; } @Override public int getClassId() { return CLASS_ID; } @Override public void serializeBody(OutputStream stream) throws IOException { writeLong(msgId, stream); writeLong(answerMsgId, stream); writeInt(bytes, stream); writeInt(state, stream); } @Override public void deserializeBody(InputStream stream, TLContext context) throws IOException { msgId = readLong(stream); answerMsgId = readLong(stream); bytes = readInt(stream); state = readInt(stream); } @Override public String toString() { return "msg_detailed_info#276d3ec6"; } } package panda.mvc.testapp.classes.action.views; import java.io.InputStream; import java.io.Reader; import java.util.HashMap; import java.util.Map; import panda.bind.json.Jsons; import panda.io.Streams; import panda.ioc.annotation.IocBean; import panda.ioc.annotation.IocInject; import panda.lang.Charsets; import panda.mvc.ActionContext; import panda.mvc.annotation.At; import panda.mvc.annotation.Redirect; import panda.mvc.annotation.To; @IocBean @At("/views") public class ViewTestModule { @IocInject protected ActionContext context; @At("") @Redirect(toslash=true) public void index() { } @At("jsp2") @To("jsp:jsp/views/jspView") public void jspView2() { context.getReq().put("obj", "2"); } @At("jsp3") @To("jsp:/WEB-INF/jsp/views/jspView") public void jspView3() { context.getReq().put("obj", "3"); } @At("jsp4") @To("jsp:/WEB-INF/jsp/views/jspView.jsp") public void jspView4() { context.getReq().put("obj", "4"); } // -------------ServerRedirectView @At("red") @To(">>:/${reqParams.to}.jsp") public void serverRedirectView() { } @At("red2") @To("RedirEct:/${reqParams.to}.jsp") public void serverRedirectView2() { } @At("red3") @To("redirect:/${reqParams.to}.jsp") public void serverRedirectView3() { } // -------------ForwardView @At("for1") @To("->:/${reqParams.to}.jsp") public void forwardView1() { } @At("for2") @To("fOrWard:/${reqParams.to}.jsp") public void forwardView2() { } @At("for3") @To("forward:/${reqParams.to == null ? 'base' : 'base'}.jsp") public void forwardView3() { } @At("for.4") @To("forward") public void forwardView4() { } // --------------Raw view @At("raw") @To("raw") public String raw() { return "ABC"; } @At("raw2") @To("raw") public InputStream raw2() throws Throwable { return getClass().getResourceAsStream("abc.txt"); } @At("raw3") @To("raw") public Reader raw3() throws Throwable { return Streams.toReader(getClass().getResourceAsStream("abc.txt"), Charsets.UTF_8); } @At("raw4") @To("raw") public void raw4() { } @At("raw5") @To("raw:5.json") public String raw5() { Map map = new HashMap(); map.put("name", "panda"); return Jsons.toJson(map); } } package seclab; import java.util.InputMismatchException; public class Run { public void run() { Input ip = new Input(); System.out.println("Enter the quantity of rows: "); int rows = ip.inputInt(); System.out.println("Enter the quantity of columns: "); int columns = ip.inputInt(); try { Matrix matrix = new Matrix(rows, columns); try { int answer = ip.answer(); try { if (answer == 0) { matrix.setMatrix(); } else { matrix.setRandomMatrix(); } matrix.showMatrix(); matrix.getMaxFromSortedRows(); }catch (InputMismatchException e){ System.out.println("Wrong matrix input"); } } catch (Exception e) { System.out.println("Symbols 'H' or 'R' only"); } } catch (Exception e) { System.out.println("Wrong matrix order"); } } } actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/network/NetworkState.java /* * Copyright (C) 2015 Actor LLC. */ package im.actor.core.network; /** * State of current network environment */ public enum NetworkState { UNKNOWN, MOBILE, WI_FI, NO_CONNECTION } 10-100 /* * 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.api.internal; import org.apache.flink.annotation.Internal; import org.apache.flink.table.api.TableColumn; import org.apache.flink.table.api.TableException; import org.apache.flink.table.api.TableSchema; import org.apache.flink.table.api.ValidationException; import org.apache.flink.table.delegation.Parser; import org.apache.flink.table.expressions.ResolvedExpression; import org.apache.flink.table.types.DataType; import org.apache.flink.table.types.logical.LogicalType; import org.apache.flink.table.types.logical.LogicalTypeFamily; import org.apache.flink.table.types.logical.TimestampKind; import org.apache.flink.table.types.logical.TimestampType; import org.apache.flink.table.types.logical.utils.LogicalTypeChecks; import org.apache.flink.table.types.utils.TypeConversions; /** * The {@link CatalogTableSchemaResolver} is used to derive correct result type of computed column, * because the date type of computed column from catalog table is not trusted. * *

Such as `proctime()` function, its type in given TableSchema is Timestamp(3), * but its correct type is Timestamp(3) *PROCTIME*. */ @Internal public class CatalogTableSchemaResolver { private final Parser parser; // A flag to indicate the table environment should work in a batch or streaming // TODO remove this once FLINK-18180 is finished private final boolean isStreamingMode; public CatalogTableSchemaResolver(Parser parser, boolean isStreamingMode) { this.parser = parser; this.isStreamingMode = isStreamingMode; } /** * Resolve the computed column's type for the given schema. * * @param tableSchema Table schema to derive table field names and data types * @return the resolved TableSchema */ public TableSchema resolve(TableSchema tableSchema) { final String rowtime; if (!tableSchema.getWatermarkSpecs().isEmpty()) { // TODO: [FLINK-14473] we only support top-level rowtime attribute right now rowtime = tableSchema.getWatermarkSpecs().get(0).getRowtimeAttribute(); if (rowtime.contains(".")) { throw new ValidationException( String.format("Nested field '%s' as rowtime attribute is not supported right now.", rowtime)); } } else { rowtime = null; } String[] fieldNames = tableSchema.getFieldNames(); DataType[] fieldTypes = tableSchema.getFieldDataTypes(); TableSchema.Builder builder = TableSchema.builder(); for (int i = 0; i < tableSchema.getFieldCount(); ++i) { TableColumn tableColumn = tableSchema.getTableColumns().get(i); DataType fieldType = fieldTypes[i]; if (tableColumn.isGenerated()) { fieldType = resolveExpressionDataType(tableColumn.getExpr().get(), tableSchema); if (isProctime(fieldType)) { if (fieldNames[i].equals(rowtime)) { throw new TableException("Watermark can not be defined for a processing time attribute column."); } } } if (isStreamingMode && fieldNames[i].equals(rowtime)) { TimestampType originalType = (TimestampType) fieldType.getLogicalType(); LogicalType rowtimeType = new TimestampType( originalType.isNullable(), TimestampKind.ROWTIME, originalType.getPrecision()); fieldType = TypeConversions.fromLogicalToDataType(rowtimeType); } if (tableColumn.isGenerated()) { builder.field(fieldNames[i], fieldType, tableColumn.getExpr().get()); } else { builder.field(fieldNames[i], fieldType); } } tableSchema.getWatermarkSpecs().forEach(builder::watermark); tableSchema.getPrimaryKey().ifPresent( pk -> builder.primaryKey(pk.getName(), pk.getColumns().toArray(new String[0]))); return builder.build(); } private boolean isProctime(DataType exprType) { return LogicalTypeChecks.hasFamily(exprType.getLogicalType(), LogicalTypeFamily.TIMESTAMP) && LogicalTypeChecks.isProctimeAttribute(exprType.getLogicalType()); } private DataType resolveExpressionDataType(String expr, TableSchema tableSchema) { ResolvedExpression resolvedExpr = parser.parseSqlExpression(expr, tableSchema); if (resolvedExpr == null) { throw new ValidationException("Could not resolve field expression: " + expr); } return resolvedExpr.getOutputDataType(); } } package org.springframework.roo.addon.dbre.addon.model; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * {@link ContentHandler} for finding the schema attribute of the * database element in the DBRE XML file and creating a * {@link Schema} object. * * @author * @since 1.1 */ public class SchemaContentHandler extends DefaultHandler { private Schema schema; /** * Constructor for no schema */ public SchemaContentHandler() { } /** * Returns the parsed schema * * @return null if not parsed yet */ public Schema getSchema() { return schema; } @Override public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (qName.equals("database")) { schema = new Schema(attributes.getValue("name")); } } } 0 /* * Copyright 2015-2019 52°North Initiative for Geospatial Open Source * Software GmbH * * 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.n52.shetland.ogc.ows.service; import java.util.Optional; import org.n52.janmayen.http.MediaType; import org.n52.shetland.ogc.ows.HasExtension; import org.n52.shetland.ogc.ows.extension.Extensions; /** * abstract super class for all service request classes * * @since 1.0.0 */ public abstract class OwsServiceResponse extends OwsServiceCommunicationObject implements HasExtension, AutoCloseable { private MediaType contentType; private Extensions extensions = new Extensions(); public OwsServiceResponse() { } public OwsServiceResponse(String service, String version) { super(service, version); } public OwsServiceResponse(String service, String version, String operationName) { super(service, version, operationName); } @Override public Extensions getExtensions() { return this.extensions; } @Override public OwsServiceResponse setExtensions(Extensions extensions) { this.extensions = Optional.ofNullable(extensions).orElseGet(Extensions::new); return this; } public OwsServiceResponse setContentType(MediaType contentType) { this.contentType = contentType; return this; } public MediaType getContentType() { return this.contentType; } public boolean isSetContentType() { return getContentType() != null; } @Override public void close() { } } /***************************************************************** * 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.cayenne.merge; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.cayenne.map.DbAttribute; import org.apache.cayenne.map.DbEntity; import org.apache.cayenne.map.DbRelationship; import org.apache.cayenne.map.MappingNamespace; import org.apache.cayenne.map.ObjEntity; import org.apache.cayenne.map.ObjRelationship; import org.apache.cayenne.util.EntityMergeSupport; /** * Common abstract superclass for all {@link MergerToken}s going from the database to the * model. * */ public abstract class AbstractToModelToken implements MergerToken { public final MergeDirection getDirection() { return MergeDirection.TO_MODEL; } protected void synchronizeWithObjEntity(MergerContext mergerContext, DbEntity entity) { for (ObjEntity objEntity : objEntitiesMappedToDbEntity(entity)) { new EntityMergeSupport(objEntity.getDataMap()) .synchronizeWithDbEntity(objEntity); } } protected Collection objEntitiesMappedToDbEntity(DbEntity entity) { Set objEntities = new HashSet(); MappingNamespace mns = entity.getDataMap().getNamespace(); for (ObjEntity objEntity : mns.getObjEntities()) { if (objEntity.getDbEntity() == null) { continue; } if (objEntity.getDbEntity().equals(entity)) { objEntities.add(objEntity); } } return objEntities; } protected void remove(MergerContext mergerContext, DbRelationship rel, boolean reverse) { if (rel == null) { return; } if (reverse) { remove(mergerContext, rel.getReverseRelationship(), false); } DbEntity dbEntity = (DbEntity) rel.getSourceEntity(); for (ObjEntity objEntity : objEntitiesMappedToDbEntity(dbEntity)) { remove(mergerContext, objEntity.getRelationshipForDbRelationship(rel), true); } rel.getSourceEntity().removeRelationship(rel.getName()); mergerContext.getModelMergeDelegate().dbRelationshipRemoved(rel); } protected void remove(MergerContext mergerContext, ObjRelationship rel, boolean reverse) { if (rel == null) { return; } if (reverse) { remove(mergerContext, rel.getReverseRelationship(), false); } rel.getSourceEntity().removeRelationship(rel.getName()); mergerContext.getModelMergeDelegate().objRelationshipRemoved(rel); } @Override public String toString() { StringBuilder ts = new StringBuilder(); ts.append(getTokenName()); ts.append(' '); ts.append(getTokenValue()); ts.append(' '); ts.append(getDirection()); return ts.toString(); } abstract static class Entity extends AbstractToModelToken { private DbEntity entity; public Entity(DbEntity entity) { this.entity = entity; } public DbEntity getEntity() { return entity; } public String getTokenValue() { return getEntity().getName(); } } abstract static class EntityAndColumn extends Entity { private DbAttribute column; public EntityAndColumn(DbEntity entity, DbAttribute column) { super(entity); this.column = column; } public DbAttribute getColumn() { return column; } @Override public String getTokenValue() { return getEntity().getName() + "." + getColumn().getName(); } } } pangaea-data-publisher/panfmp /* * Copyright panFMP Developers Team c/o * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.pangaea.metadataportal.utils; import java.util.Locale; /** * BooleanParser is a simple static class supplying a method to * parse booleans. * * @author */ public final class BooleanParser { private BooleanParser() {} /** * Parses a boolean value expressed as String * * @throws IllegalArgumentException * if uppercase v is not "TRUE", "YES", "ON", "FALSE", * "NO", "OFF" */ public static boolean parseBoolean(String v) { v = v.toUpperCase(Locale.ROOT); if ("TRUE".equals(v) || "YES".equals(v) || "ON".equals(v)) return true; else if ("FALSE".equals(v) || "NO".equals(v) || "OFF".equals(v)) return false; else throw new IllegalArgumentException( "Boolean value must be one of: [YES,TRUE,ON]; [NO,FALSE,OFF]"); } }TanJay/stress_app package com.tanushaj.element; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.content.Context; @Database(entities = {StressItem.class}, version = 1, exportSchema = false) public abstract class StressDatabase extends RoomDatabase { public abstract StressItemDAO stressItemDAO(); private static volatile StressDatabase INSTANCE; static StressDatabase getDatabase(final Context context){ if(INSTANCE == null){ synchronized (StressDatabase.class) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), StressDatabase.class, "stress_database") .build(); } } } return INSTANCE; } } snippets/java/Snippet-001.java import java.util.Objects; class PriceCalculator { public Float price(Product product) { float price = 0f; switch (product.type) { case BREAD: price = 3f; break; case CANDY: price = 0.49f; break; } return price; } public Float discount(Product product, Integer count) { float discount = 0f; switch (product.type) { case BREAD: discount = count >= 10 ? 0.1f : 0; break; case CANDY: discount = count >= 100 ? 0.12f : 0; break; } return discount; } public static class Product { private Type type; public Product(Type type) { this.type = type; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product product = (Product) o; return type == product.type; } @Override public int hashCode() { return Objects.hash(type); } @Override public String toString() { return "Product{" + "type=" + type + '}'; } } public enum Type { BREAD, CANDY } }fmidev/fmi-avi-messageconverter-tacsrc/test/java/fi/fmi/avi/converter/tac/taf/Taf6Test.java package fi.fmi.avi.converter.tac.taf; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.AERODROME_DESIGNATOR; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.CAVOK; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.CLOUD; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.END_TOKEN; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.HORIZONTAL_VISIBILITY; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.ISSUE_TIME; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.SURFACE_WIND; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.TAF_CHANGE_FORECAST_TIME_GROUP; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.TAF_FORECAST_CHANGE_INDICATOR; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.TAF_START; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.VALID_TIME; import static fi.fmi.avi.converter.tac.lexer.LexemeIdentity.WEATHER; import fi.fmi.avi.converter.ConversionSpecification; import fi.fmi.avi.converter.tac.AbstractAviMessageTest; import fi.fmi.avi.converter.tac.conf.TACConverter; import fi.fmi.avi.converter.tac.lexer.LexemeIdentity; import fi.fmi.avi.model.taf.TAF; import fi.fmi.avi.model.taf.immutable.TAFImpl; public class Taf6Test extends AbstractAviMessageTest { @Override public String getJsonFilename() { return "taf/taf6.json"; } @Override public String getMessage() { return "TAF EFKU 190830Z 1909/2009 23010KT CAVOK\r\n" // + "PROB30 TEMPO 1915/1919 7000 SHRA SCT030CB BKN045\r\n" // + "BECMG 1923/2001 30010KT="; } @Override public LexemeIdentity[] getLexerTokenSequenceIdentity() { return spacify(new LexemeIdentity[] { TAF_START, AERODROME_DESIGNATOR, ISSUE_TIME, VALID_TIME, SURFACE_WIND, CAVOK, TAF_FORECAST_CHANGE_INDICATOR, TAF_CHANGE_FORECAST_TIME_GROUP, HORIZONTAL_VISIBILITY, WEATHER, CLOUD, CLOUD, TAF_FORECAST_CHANGE_INDICATOR, TAF_CHANGE_FORECAST_TIME_GROUP, SURFACE_WIND, END_TOKEN }); } @Override public ConversionSpecification getParsingSpecification() { return TACConverter.TAC_TO_TAF_POJO; } @Override public ConversionSpecification getSerializationSpecification() { return TACConverter.TAF_POJO_TO_TAC; } @Override public Class getTokenizerImplementationClass() { return TAFImpl.class; } } /* * Copyright 2016 qyh.me * * 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 me.qyh.blog.core.service.impl; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.context.event.EventListener; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import me.qyh.blog.core.bean.ArticleDateFile; import me.qyh.blog.core.bean.ArticleDateFiles; import me.qyh.blog.core.bean.ArticleDateFiles.ArticleDateFileMode; import me.qyh.blog.core.bean.ArticleNav; import me.qyh.blog.core.bean.ArticleSpaceFile; import me.qyh.blog.core.bean.TagCount; import me.qyh.blog.core.config.GlobalConfig; import me.qyh.blog.core.dao.ArticleDao; import me.qyh.blog.core.dao.ArticleTagDao; import me.qyh.blog.core.dao.SpaceDao; import me.qyh.blog.core.dao.TagDao; import me.qyh.blog.core.entity.Article; import me.qyh.blog.core.entity.Article.ArticleStatus; import me.qyh.blog.core.entity.ArticleTag; import me.qyh.blog.core.entity.Space; import me.qyh.blog.core.entity.Tag; import me.qyh.blog.core.evt.ArticleEvent; import me.qyh.blog.core.evt.ArticleIndexRebuildEvent; import me.qyh.blog.core.evt.EventType; import me.qyh.blog.core.evt.LockDeleteEvent; import me.qyh.blog.core.evt.SpaceDeleteEvent; import me.qyh.blog.core.exception.LogicException; import me.qyh.blog.core.exception.RuntimeLogicException; import me.qyh.blog.core.lock.LockManager; import me.qyh.blog.core.message.Message; import me.qyh.blog.core.pageparam.ArticleQueryParam; import me.qyh.blog.core.pageparam.PageResult; import me.qyh.blog.core.security.Environment; import me.qyh.blog.core.service.ArticleService; import me.qyh.blog.core.service.CommentServer; import me.qyh.blog.core.service.ConfigService; import me.qyh.blog.support.metaweblog.MetaweblogArticle; import me.qyh.blog.util.Times; public class ArticleServiceImpl implements ArticleService, InitializingBean, ApplicationEventPublisherAware { private static final Logger LOGGER = LoggerFactory.getLogger(ArticleServiceImpl.class); @Autowired private ArticleDao articleDao; @Autowired private SpaceDao spaceDao; @Autowired private SpaceCache spaceCache; @Autowired private ArticleTagDao articleTagDao; @Autowired private TagDao tagDao; @Autowired private LockManager lockManager; @Autowired private ArticleCache articleCache; @Autowired private ConfigService configService; @Autowired private CommentServer articleCommentStatisticsService; @Autowired private PlatformTransactionManager transactionManager; @Autowired private ArticleIndexer articleIndexer; private ApplicationEventPublisher applicationEventPublisher; private boolean rebuildIndex = true; @Autowired(required = false) private ArticleContentHandler articleContentHandler; private final ScheduleManager scheduleManager = new ScheduleManager(); /** * 点击策略 */ @Autowired(required = false) private HitsStrategy hitsStrategy; private ArticleHitManager articleHitManager; @Autowired(required = false) private ArticleViewedLogger articleViewedLogger; @Override @Transactional(readOnly = true) public Optional

getArticleForView(String idOrAlias) { Optional
optionalArticle = getCheckedArticle(idOrAlias); if (optionalArticle.isPresent()) { Article clone = new Article(optionalArticle.get()); clone.setComments(articleCommentStatisticsService.queryArticleCommentCount(clone.getId()).orElse(0)); if (articleContentHandler != null) { articleContentHandler.handle(clone); } return Optional.of(clone); } return Optional.empty(); } @Override @Transactional(readOnly = true) public Article getArticleForEdit(Integer id) throws LogicException { Article article = articleDao.selectById(id); if (article == null || article.isDeleted()) { throw new LogicException("article.notExists", "文章不存在"); } return article; } @Override public void hit(Integer id) { articleHitManager.hit(id); } @Override @ArticleIndexRebuild @Caching(evict = { @CacheEvict(value = "articleFilesCache", allEntries = true), @CacheEvict(value = "hotTags", allEntries = true) }) @Sync @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) public Article writeArticle(MetaweblogArticle mba) throws LogicException { Space space = mba.getSpace() == null ? spaceDao.selectDefault() : spaceDao.selectByName(mba.getSpace()); if (space == null) { throw new LogicException("space.notExists", "空间不存在"); } Article article; if (mba.hasId()) { Article articleDb = articleDao.selectById(mba.getId()); if (articleDb != null) { article = new Article(articleDb); mba.mergeArticle(article); } else { article = mba.toArticle(); article.setId(mba.getId()); } } else { article = mba.toArticle(); } article.setSpace(space); return writeArticle(article); } @Override @ArticleIndexRebuild @Caching(evict = { @CacheEvict(value = "articleFilesCache", allEntries = true), @CacheEvict(value = "hotTags", allEntries = true) }) @Sync @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) public Article writeArticle(Article article) throws LogicException { Space space = spaceCache.checkSpace(article.getSpace().getId()); article.setSpace(space); // 如果文章是私有的,无法设置锁 if (article.isPrivate()) { article.setLockId(null); } else { lockManager.ensureLockvailable(article.getLockId()); } Timestamp now = Timestamp.valueOf(LocalDateTime.now()); boolean update = article.hasId(); if (update) { Article articleDb = articleDao.selectById(article.getId()); if (articleDb == null) { throw new LogicException("article.notExists", "文章不存在"); } if (articleDb.isDeleted()) { throw new LogicException("article.deleted", "文章已经被删除"); } if (article.getAlias() != null) { Article aliasDb = articleDao.selectByAlias(article.getAlias()); if (aliasDb != null && !aliasDb.equals(article)) { throw new LogicException("article.alias.exists", "别名" + article.getAlias() + "已经存在", article.getAlias()); } } if (nochange(article, articleDb)) { return articleDb; } Timestamp pubDate = null; switch (article.getStatus()) { case DRAFT: pubDate = articleDb.isSchedule() ? null : articleDb.getPubDate() != null ? articleDb.getPubDate() : null; break; case PUBLISHED: pubDate = articleDb.isSchedule() ? now : articleDb.getPubDate() != null ? articleDb.getPubDate() : now; break; case SCHEDULED: pubDate = article.getPubDate(); break; default: break; } article.setPubDate(pubDate); if (articleDb.getPubDate() != null && article.isPublished()) { article.setLastModifyDate(now); } articleTagDao.deleteByArticle(articleDb); articleDao.update(article); Transactions.afterCommit(() -> articleCache.evit(article.getId())); } else { if (article.getAlias() != null) { Article aliasDb = articleDao.selectByAlias(article.getAlias()); if (aliasDb != null) { throw new LogicException("article.alias.exists", "别名" + article.getAlias() + "已经存在", article.getAlias()); } } Timestamp pubDate = null; switch (article.getStatus()) { case DRAFT: // 如果是草稿 pubDate = null; break; case PUBLISHED: pubDate = now; break; case SCHEDULED: pubDate = article.getPubDate(); break; default: break; } article.setPubDate(pubDate); articleDao.insert(article); } boolean rebuildIndexWhenTagChange = insertTags(article); if (article.isSchedule()) { scheduleManager.update(); } Transactions.afterCommit(() -> { if (rebuildIndexWhenTagChange) { applicationEventPublisher.publishEvent(new ArticleIndexRebuildEvent(this)); } else { if (update) { articleIndexer.deleteDocument(article.getId()); } if (article.isPublished()) { articleIndexer.addOrUpdateDocument(article.getId()); } } }); applicationEventPublisher.publishEvent(new ArticleEvent(this, articleDao.selectById(article.getId()), update ? EventType.UPDATE : EventType.INSERT)); return article; } @Override @ArticleIndexRebuild @Caching(evict = { @CacheEvict(value = "articleFilesCache", allEntries = true), @CacheEvict(value = "hotTags", allEntries = true) }) @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) public void publishDraft(Integer id) throws LogicException { Article article = articleDao.selectById(id); if (article == null) { throw new LogicException("article.notExists", "文章不存在"); } if (!article.isDraft()) { throw new LogicException("article.notDraft", "文章已经被删除"); } Timestamp now = Timestamp.valueOf(LocalDateTime.now()); article.setPubDate(article.isSchedule() ? now : article.getPubDate() != null ? article.getPubDate() : now); article.setStatus(ArticleStatus.PUBLISHED); articleDao.update(article); Transactions.afterCommit(() -> articleIndexer.addOrUpdateDocument(id)); applicationEventPublisher.publishEvent(new ArticleEvent(this, article, EventType.UPDATE)); } private boolean insertTags(Article article) { Set tags = article.getTags(); boolean rebuildIndexWhenTagChange = false; if (!CollectionUtils.isEmpty(tags)) { for (Tag tag : tags) { Tag tagDb = tagDao.selectByName(cleanTag(tag.getName())); ArticleTag articleTag = new ArticleTag(); articleTag.setArticle(article); if (tagDb == null) { // 插入标签 tag.setCreate(Timestamp.valueOf(LocalDateTime.now())); tag.setName(tag.getName().trim()); tagDao.insert(tag); articleTag.setTag(tag); articleIndexer.addTags(tag.getName()); rebuildIndexWhenTagChange = true; } else { articleTag.setTag(tagDb); } articleTagDao.insert(articleTag); } } return rebuildIndexWhenTagChange; } @Override @Transactional(readOnly = true) @Cacheable(value = "articleFilesCache", key = "'dateFiles-'+'space-'+(T(me.qyh.blog.core.security.Environment).getSpace())+'-mode-'+#mode.name()+'-private-'+(T(me.qyh.blog.core.security.Environment).isLogin())") public ArticleDateFiles queryArticleDateFiles(ArticleDateFileMode mode) throws LogicException { List files = articleDao.selectDateFiles(Environment.getSpace(), mode, Environment.isLogin()); ArticleDateFiles _files = new ArticleDateFiles(files, mode); _files.calDate(); return _files; } @Override @Transactional(readOnly = true) @Cacheable(value = "articleFilesCache", key = "'dateFiles-'+'space-'+(T(me.qyh.blog.core.security.Environment).getSpace())+'-private-'+(T(me.qyh.blog.core.security.Environment).isLogin())") public List queryArticleSpaceFiles() { if (Environment.hasSpace()) { return Collections.emptyList(); } return articleDao.selectSpaceFiles(Environment.isLogin()); } @Override @Transactional(readOnly = true) public PageResult
queryArticle(ArticleQueryParam param) { GlobalConfig globalConfig = configService.getGlobalConfig(); param.setPageSize(Math.min(param.getPageSize(), globalConfig.getArticlePageSize())); if (param.isQueryPrivate() && !Environment.isLogin()) { param.setQueryPrivate(false); } PageResult
page; if (param.hasQuery()) { page = articleIndexer.query(param); } else { int count = articleDao.selectCount(param); List
datas = articleDao.selectPage(param); page = new PageResult<>(param, count, datas); } // query comments List
datas = page.getDatas(); if (!CollectionUtils.isEmpty(datas)) { List ids = new ArrayList<>(datas.size()); for (Article article : datas) { ids.add(article.getId()); } Map countsMap = articleCommentStatisticsService.queryArticlesCommentCount(ids); for (Article article : datas) { Integer comments = countsMap.get(article.getId()); article.setComments(comments == null ? 0 : comments); } } return page; } @Override @ArticleIndexRebuild @Caching(evict = { @CacheEvict(value = "articleFilesCache", allEntries = true), @CacheEvict(value = "hotTags", allEntries = true) }) @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) public void logicDeleteArticle(Integer id) throws LogicException { Article article = articleDao.selectById(id); if (article == null) { throw new LogicException("article.notExists", "文章不存在"); } if (article.isDeleted()) { throw new LogicException("article.deleted", "文章已经被删除"); } article.setStatus(ArticleStatus.DELETED); articleDao.update(article); Transactions.afterCommit(() -> { articleCache.evit(id); articleIndexer.deleteDocument(id); }); applicationEventPublisher.publishEvent(new ArticleEvent(this, article, EventType.UPDATE)); } @Override @ArticleIndexRebuild @Caching(evict = { @CacheEvict(value = "articleFilesCache", allEntries = true), @CacheEvict(value = "hotTags", allEntries = true) }) @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) public void recoverArticle(Integer id) throws LogicException { Article article = articleDao.selectById(id); if (article == null) { throw new LogicException("article.notExists", "文章不存在"); } if (!article.isDeleted()) { throw new LogicException("article.undeleted", "文章未删除"); } ArticleStatus status = ArticleStatus.PUBLISHED; if (article.getPubDate().after(Timestamp.valueOf(LocalDateTime.now()))) { status = ArticleStatus.SCHEDULED; } article.setStatus(status); articleDao.update(article); Transactions.afterCommit(() -> articleIndexer.addOrUpdateDocument(id)); applicationEventPublisher.publishEvent(new ArticleEvent(this, article, EventType.UPDATE)); } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) public void deleteArticle(Integer id) throws LogicException { Article article = articleDao.selectById(id); if (article == null) { throw new LogicException("article.notExists", "文章不存在"); } if (!article.isDraft() && !article.isDeleted()) { throw new LogicException("article.undeleted", "文章未删除"); } // 删除博客的引用 articleTagDao.deleteByArticle(article); articleDao.deleteById(id); applicationEventPublisher.publishEvent(new ArticleEvent(this, article, EventType.DELETE)); } @Override @Caching(evict = { @CacheEvict(value = "hotTags", allEntries = true, condition = "#result > 0"), @CacheEvict(value = "articleFilesCache", allEntries = true, condition = "#result > 0") }) public int publishScheduled() { return scheduleManager.publish(); } /** * {@inheritDoc} * *

* 这个方法只提供根据发布时间排序的上下文章 *

*/ @Override @Transactional(readOnly = true) public Optional getArticleNav(String idOrAlias, boolean queryLock) { Optional
optionalArticle = getCheckedArticle(idOrAlias); if (optionalArticle.isPresent()) { Article article = optionalArticle.get(); if (!Environment.match(article.getSpace())) { return Optional.empty(); } boolean queryPrivate = Environment.isLogin(); Article previous = articleDao.getPreviousArticle(article, queryPrivate, queryLock); Article next = articleDao.getNextArticle(article, queryPrivate, queryLock); return (previous != null || next != null) ? Optional.of(new ArticleNav(previous, next)) : Optional.empty(); } return Optional.empty(); } @Override @Transactional(readOnly = true) @Cacheable(value = "hotTags", key = "'hotTags-'+'space-'+(T(me.qyh.blog.core.security.Environment).getSpace())+'-private-'+(T(me.qyh.blog.core.security.Environment).isLogin())") public List queryTags() throws LogicException { return new ArrayList<>(articleTagDao.selectTags(Environment.getSpace(), Environment.isLogin())); } @Override @Transactional(readOnly = true) public List
queryRecentArticles(Integer limit) { return articleDao.selectRecentArticles(limit); } @Override @Transactional(readOnly = true) public List
findSimilar(String idOrAlias, int limit) throws LogicException { Optional
optionalArticle = getCheckedArticle(idOrAlias); if (optionalArticle.isPresent()) { Article article = optionalArticle.get(); if (!Environment.match(article.getSpace())) { return Collections.emptyList(); } return articleIndexer.querySimilar(article, Environment.isLogin(), limit).stream() .collect(Collectors.toList()); } return Collections.emptyList(); } /** * {@inheritDoc} * * 由于点击后才会被记录,而点击方法和浏览文章的方法是事分离的,因为可能更多的反应的是点击过的文章 * * @param num * 记录数,该记录数受到 {@code ArticleViewdLogger}的限制 * @see ArticleViewedLogger#getViewdArticles(int) * @see ArticleHitManager#hit(Integer) */ @Override public List
getRecentlyViewdArticle(int num) { return articleViewedLogger == null ? Collections.emptyList() : articleViewedLogger.getViewdArticles(num); } @Override @Transactional(readOnly = true) public Optional
selectRandom(boolean queryLock) { return Optional.ofNullable(articleDao.selectRandom(Environment.getSpace(), Environment.isLogin(), queryLock)); } @Override public void preparePreview(Article article) { if (articleContentHandler != null) { articleContentHandler.handlePreview(article); } } @EventListener public void handleLockDeleteEvent(LockDeleteEvent event) { articleDao.deleteLock(event.getLockId()); } @EventListener public void handleSpaceDeleteEvent(SpaceDeleteEvent event) { Space deleted = event.getSpace(); // 查询该空间下是否存在文章 int count = articleDao.selectCountBySpace(deleted); if (count > 0) { // 空间下存在文章 // 移动到默认空间 Space defaultSpace = spaceDao.selectDefault(); // 默认空间不存在,无法删除空间 if (defaultSpace == null) { throw new RuntimeLogicException(new Message("space.delete.hasArticles", "空间下存在文章,删除失败")); } articleDao.moveSpace(deleted, defaultSpace); // 清空文章缓存 Transactions.afterCommit(articleCache::clear); } } @Override public void afterPropertiesSet() throws Exception { if (rebuildIndex) { this.articleIndexer.rebuildIndex(); } if (hitsStrategy == null) { hitsStrategy = new DefaultHitsStrategy(); } this.articleHitManager = new ArticleHitManager(hitsStrategy); scheduleManager.update(); } private Optional
getCheckedArticle(String idOrAlias) { Article article = null; try { int id = Integer.parseInt(idOrAlias); article = articleCache.getArticle(id); } catch (NumberFormatException e) { article = articleCache.getArticle(idOrAlias); } if (article != null && article.isPublished() && Environment.match(article.getSpace())) { if (article.isPrivate()) { Environment.doAuthencation(); } lockManager.openLock(article); return Optional.of(article); } return Optional.empty(); } /** * 查询标签是否存在的时候清除两边空格并且忽略大小写 * * @param tag * @return */ protected String cleanTag(String tag) { return tag.trim().toLowerCase(); } public void setRebuildIndex(boolean rebuildIndex) { this.rebuildIndex = rebuildIndex; } private final class ScheduleManager { private Timestamp start; public int publish() { if (start == null) { LOGGER.debug("没有待发布的文章"); return 0; } long now = System.currentTimeMillis(); if (now < start.getTime()) { LOGGER.debug("没有到发布日期:" + Times.format(start.toLocalDateTime(), "yyyy-MM-dd HH:mm:ss")); return 0; } else { LOGGER.debug("开始查询发布文章"); Timestamp startCopy = new Timestamp(start.getTime()); List
articles = Transactions.executeInTransaction(transactionManager, status -> { Transactions.afterRollback(() -> start = startCopy); List
schedules = articleDao.selectScheduled(new Timestamp(now)); if (!schedules.isEmpty()) { for (Article article : schedules) { article.setStatus(ArticleStatus.PUBLISHED); articleDao.update(article); } LOGGER.debug("发布了" + schedules.size() + "篇文章"); applicationEventPublisher.publishEvent(new ArticleEvent(this, schedules, EventType.UPDATE)); } start = articleDao.selectMinimumScheduleDate(); return schedules; }); articleIndexer.addOrUpdateDocument(articles.stream().map(Article::getId).toArray(i -> new Integer[i])); return articles.size(); } } public void update() { start = articleDao.selectMinimumScheduleDate(); LOGGER.debug(start == null ? "没有发现待发布文章" : "发现待发布文章最小日期:" + Times.format(start.toLocalDateTime(), "yyyy-MM-dd HH:mm:ss")); } } private final class ArticleHitManager { private final HitsStrategy hitsStrategy; public ArticleHitManager(HitsStrategy hitsStrategy) { super(); this.hitsStrategy = hitsStrategy; } void hit(Integer id) { Article article = articleCache.getArticle(id); if (article != null && validHit(article)) { hitsStrategy.hit(article); if (articleViewedLogger != null) { articleViewedLogger.logViewd(article); } } } private boolean validHit(Article article) { boolean hit = !Environment.isLogin() && article.isPublished() && Environment.match(article.getSpace()) && !article.getIsPrivate(); if (hit) { lockManager.openLock(article); } return hit; } } /** * 文章缓存点击策略 *

* 文章可能存在于缓存中,需要在合适的时机手动更新缓存和文章索引 *

* * @see ArticleCache#updateHits(Map) * @see ArticleIndexer#addOrUpdateDocument(Integer...) * * @see DefaultHitsStrategy * @author mhlx * */ public interface HitsStrategy { /** * 点击文章 * * @param article */ void hit(Article article); } /** * 默认文章点击策略,文章的点击数将会实时显示 *

* 这种策略下每次点击都会增加点击量 *

* * @see CacheableHitsStrategy * @author mhlx * */ private final class DefaultHitsStrategy implements HitsStrategy { @Override public void hit(Article article) { synchronized (this) { int hits = article.getHits() + 1; Transactions.executeInTransaction(transactionManager, status -> { Integer id = article.getId(); articleDao.updateHits(id, hits); Transactions.afterCommit(() -> { Map hitsMap = new HashMap<>(); hitsMap.put(article.getId(), hits); articleCache.updateHits(hitsMap); articleIndexer.addOrUpdateDocument(article.getId()); }); }); } } } /** * 用来记录最近被访问的文章 * * @author Administrator * */ public interface ArticleViewedLogger { /** * 查询最近被访问的文章 * * @param num * 文章数量 * @return */ List
getViewdArticles(int num); /** * 记录文章 * * @param article */ void logViewd(Article article); } /** * 判断文章是否需要更新 * * @param newArticle * 当前文章 * @param old * 已经存在的文章 * @return */ protected boolean nochange(Article newArticle, Article old) { Objects.requireNonNull(newArticle); Objects.requireNonNull(old); return Objects.equals(newArticle.getAlias(), old.getAlias()) && Objects.equals(newArticle.getAllowComment(), old.getAllowComment()) && Objects.equals(newArticle.getContent(), old.getContent()) && Objects.equals(newArticle.getFrom(), old.getFrom()) && Objects.equals(newArticle.getIsPrivate(), old.getIsPrivate()) && Objects.equals(newArticle.getLevel(), old.getLevel()) && Objects.equals(newArticle.getLockId(), old.getLockId()) && Objects.equals(newArticle.getSpace(), old.getSpace()) && Objects.equals(newArticle.getSummary(), old.getSummary()) && Objects.equals(newArticle.getTagStr(), old.getTagStr()) && Objects.equals(newArticle.getTitle(), old.getTitle()) && Objects.equals(newArticle.getStatus(), old.getStatus()); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } } 1-10 package com.builtbroken.artillects.core.entity.ai; import com.builtbroken.artillects.core.entity.npc.EntityNpc; import com.builtbroken.mc.imp.transform.vector.Pos; import net.minecraft.entity.Entity; import java.util.Random; /** * Helper class used to generate random positions for AI scripts. * Some code is cloned from {@link net.minecraft.entity.ai.RandomPositionGenerator} which can't * be used as its coded for {@link net.minecraft.entity.EntityCreature} only. */ public final class PositionGenerator { /** * Finds a random point in an area * * @param entity * @param distanceBlocks * @param yDistanceBlocks * @return */ public static Pos randomPoint(Entity entity, int distanceBlocks, int yDistanceBlocks) { return randomPoint(entity, distanceBlocks, yDistanceBlocks, null); } /** * Generates a random position towards the target point. Tries 10 times to find a position before returning null. * * @param entity - entity used as center point, and check for block weight * @param distanceBlocks - distance in x and z to move * @param yDistanceBlocks - distance in y to move * @param target - target to move towards * @return position, or null if none were found */ public static Pos randomPointTowards(Entity entity, int distanceBlocks, int yDistanceBlocks, Pos target) { return randomPoint(entity, distanceBlocks, yDistanceBlocks, target.sub(entity.posX, entity.posY, entity.posZ)); } /** * Generates a random position away from the target point. Tries 10 times to find a position before returning null. * * @param entity - entity used as center point, and check for block weight * @param distanceBlocks - distance in x and z to move * @param yDistanceBlocks - distance in y to move * @param target - target to move away from * @return position, or null if none were found */ public static Pos randomPointAway(Entity entity, int distanceBlocks, int yDistanceBlocks, Pos target) { return randomPoint(entity, distanceBlocks, yDistanceBlocks, new Pos(entity).sub(target)); } /** * Finds a block position in the given direction. Tries 10 times to find a valid position before returning null * * @param entity - entity to use as a center point, and valid block weights * @param distanceBlocks - distance x and z * @param yDistanceBlocks - distance y * @param direction - direction to move in, null will be all directions * @return position or null if none were found */ public static Pos randomPoint(Entity entity, int distanceBlocks, int yDistanceBlocks, Pos direction) { final Random random = com.builtbroken.jlib.helpers.MathHelper.rand; Pos bestPos = null; float bestValue = -99999.0F; for (int tries = 0; tries < 10; ++tries) { //Generate random position inside out limits Pos randomPos = new Pos(random.nextInt(2 * distanceBlocks) - distanceBlocks, random.nextInt(2 * yDistanceBlocks) - yDistanceBlocks, random.nextInt(2 * distanceBlocks) - distanceBlocks); if (direction == null || randomPos.x() * direction.xi() + randomPos.z() * direction.zi() >= 0.0D) //TODO figure out what this math is doing, assumed it is checking direction { randomPos = randomPos.add(entity.posX, entity.posY, entity.posZ); float blockValue = entity instanceof EntityNpc ? ((EntityNpc) entity).getBlockPathWeight(randomPos) : 0; if (blockValue > bestValue) { bestValue = blockValue; bestPos = randomPos; } } } return bestPos; } }package com.esgov.jrw.jrwservice.controller.authority; import com.esgov.jrw.jrwservice.common.util.FastJSONUtil; import com.esgov.jrw.jrwservice.common.dto.ServiceResponse; import com.esgov.jrw.jrwservice.service.authority.SysRoleMenuButtonMappService; import io.swagger.annotations.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; /** * 描述: 角色菜单按钮Controller * * @author Yangjinming * @create 2018-04-17 下午1:20 */ @RestController @RequestMapping("/sysmgr/service/rolemenubutton/map") @Api(value = "role-menu-button-map",description = "角色菜单按钮关联") @ApiResponses(value = {@ApiResponse(code = 0,message = "操作成功",response = Integer.class), @ApiResponse(code = 1,message = "操作失败",response = Integer.class)}) public class SysRoleMenuButtonController { @Autowired SysRoleMenuButtonMappService roleMenuButtonMappService; @ApiOperation(value = "获取角色、菜单、按钮关联信息", notes = "根据角色Id获取相关联的菜单、按钮") @PostMapping("/getRoleMenuButtonMapps/{roleId}") public ServiceResponse getRoleMenuButtonMapps(@ApiParam("角色Id") @PathVariable("roleId")String roleId){ return roleMenuButtonMappService.getRoleMenuButtonMapps(roleId); } @ApiOperation(value = "关联角色菜单", notes = "根据一个或多个RoleId 批量关联菜单按钮") @PostMapping("/mapOrgRole") public ServiceResponse mapRoleMenuButton(@ApiParam("角色id组 字符串,以逗号隔开") @RequestParam("roleId") String roleId, @ApiParam("新增的菜单json") @RequestParam("addMenus") String addMenus, @ApiParam("删除的菜单Id组") @RequestParam("delMenus") String delMenus){ List> menus = (List>)FastJSONUtil.convertToList(addMenus, (new HashMap()).getClass()); return roleMenuButtonMappService.mapRoleMenuButton(roleId,menus,delMenus); } } 0 package org.nsidc.nutch.index.xmlnamespaces; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.nutch.crawl.CrawlDatum; import org.apache.nutch.crawl.Inlinks; import org.apache.nutch.indexer.IndexingException; import org.apache.nutch.indexer.IndexingFilter; import org.apache.nutch.indexer.NutchDocument; import org.apache.nutch.parse.Parse; import java.util.regex.Matcher; import java.util.regex.Pattern; //these three are needed for external file reading /** Description: Extracts xml namespaces into a new Nutch field. Requirements: index-rawxml, index-more */ public class NamespaceIndexingFilter implements IndexingFilter { private Configuration conf; public static List getAllMatches(String text, String regex) { List matches = new ArrayList(); Matcher m = Pattern.compile("(?=(" + regex + "))").matcher(text); while(m.find()) { matches.add(m.group(1)); } return matches; } public List getNameSpaces(String xml) { List matches = new ArrayList(); ArrayList namespaces = new ArrayList(); matches = getAllMatches(xml, "xmlns(.*?)=(\".*?\")"); for (String ns : matches){ // easier than using sets in Java if (!namespaces.contains(ns)) { namespaces.add(ns); } } return namespaces; } @Override public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks) throws IndexingException { // If the raw_content is null or the document type do not contains xml then we just return the document as is. if (doc.getField("raw_content") == null || !doc.getField("type").getValues().contains("xml")) { return doc; } String raw_xml_content = doc.getField("raw_content").getValues().get(0).toString(); List namespaces = getNameSpaces(raw_xml_content); for(String namespace : namespaces) { doc.add("xml_namespaces", namespace); } return doc; } @Override public Configuration getConf() { return conf; } @Override public void setConf(Configuration conf) { this.conf = conf; } } /* * Copyright (c) 2015, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-praise nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sri.ai.praise.other.application.praise.app; import com.google.common.annotations.Beta; import de.jensd.fx.glyphs.GlyphsStyle; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; @Beta public class PRAiSE extends Application { @Override public void start(Stage primaryStage) throws Exception{ FXMLLoader rootLoader = new FXMLLoader(getClass().getResource("praiseapp.fxml")); Parent root = rootLoader.load(); PRAiSEController controller = rootLoader.getController(); controller.setMainStage(primaryStage); Scene scene = new Scene(root, 1024, 768); primaryStage.setScene(scene); scene.getStylesheets().add("com/sri/ai/praise/other/application/praise/app/praiseapp.css"); scene.getStylesheets().add(GlyphsStyle.BLUE.getStylePath()); primaryStage.show(); } public static void main(String[] args) { launch(args); } } package storage; import items.TakeableItem; public class Trunk extends Storage { private static int DEFAULT_CAP_TRUNK = 20; /** * * @param capacity the capacity of the new Trunk */ public Trunk(int capacity) { super(capacity); } /** * create a new Trunk with Trunk.DEFAULT_CAP_TRUNK capacity */ public Trunk() { this(Trunk.DEFAULT_CAP_TRUNK); } }package com.hsiao.security.mapper; import com.hsiao.security.bean.Resource; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Component; import java.util.List; /** * Created by wxb on 2018/10/27 0027. */ @Component @Mapper public interface ResourceMapper { /** * 从数据库中查询所有资源 * @return */ @Select("select * from resource ") List selectAllResource(); } /* * 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.nifi.components.state; /** *

* Interface that provides a mechanism for obtaining the {@link StateManager} for a particular component *

*/ public interface StateManagerProvider { /** * Returns the StateManager for the component with the given ID, or null if no State Manager * exists for the component with the given ID * * @param componentId the id of the component for which the StateManager should be returned * * @return the StateManager for the component with the given ID, or null if no State Manager * exists for the component with the given ID */ StateManager getStateManager(String componentId); /** * Notifies the State Manager Provider that the component with the given ID has been removed from the NiFi instance * and will no longer be needed, so the appropriate resource cleanup can take place. * * @param componentId the ID of the component that has been removed */ void onComponentRemoved(String componentId); /** * Shuts down the state managers, cleaning up any resources that they occupy */ void shutdown(); /** * Initializes the Cluster State Provider and enables it for use */ void enableClusterProvider(); /** * Disables the Cluster State Provider and begins using the Local State Provider to persist and retrieve * state, even when components request a clustered provider */ void disableClusterProvider(); } SimonOsaka/way-api package com.zl.way.mp.model; import java.io.Serializable; import java.util.Date; public class WayCity implements Serializable { private Integer id; private String name; private String adcode; private String citycode; private String pinyinShort; private String pinyinAll; private Byte isUsed; private Date createTime; private Date updateTime; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getAdcode() { return adcode; } public void setAdcode(String adcode) { this.adcode = adcode == null ? null : adcode.trim(); } public String getCitycode() { return citycode; } public void setCitycode(String citycode) { this.citycode = citycode == null ? null : citycode.trim(); } public String getPinyinShort() { return pinyinShort; } public void setPinyinShort(String pinyinShort) { this.pinyinShort = pinyinShort == null ? null : pinyinShort.trim(); } public String getPinyinAll() { return pinyinAll; } public void setPinyinAll(String pinyinAll) { this.pinyinAll = pinyinAll == null ? null : pinyinAll.trim(); } public Byte getIsUsed() { return isUsed; } public void setIsUsed(Byte isUsed) { this.isUsed = isUsed; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }package com.siyeh.igtest.security; public class SystemPropertiesInspection { public void foo() { System.getProperties(); System.getProperty("foo"); Integer.getInteger("foo"); Boolean.getBoolean("foo"); } } server/hotrod/src/main/java/org/infinispan/server/hotrod/TimeUnitValue.java package org.infinispan.server.hotrod; import java.util.concurrent.TimeUnit; import org.infinispan.util.KeyValuePair; /** * @author wburns * @since 9.0 */ public enum TimeUnitValue { SECONDS(0x00), MILLISECONDS(0x01), NANOSECONDS(0x02), MICROSECONDS(0x03), MINUTES(0x04), HOURS(0x05), DAYS(0x06), DEFAULT(0x07), INFINITE(0x08); private final byte code; TimeUnitValue(int code) { this.code = (byte) code; } public byte getCode() { return code; } public TimeUnit toTimeUnit() { switch (code) { case 0x00: return TimeUnit.SECONDS; case 0x01: return TimeUnit.MILLISECONDS; case 0x02: return TimeUnit.NANOSECONDS; case 0x03: return TimeUnit.MICROSECONDS; case 0x04: return TimeUnit.MINUTES; case 0x05: return TimeUnit.HOURS; case 0x06: return TimeUnit.DAYS; default: throw new IllegalArgumentException("TimeUnit not supported for: " + code); } } public static TimeUnitValue decode(byte rightBits) { switch (rightBits) { case 0x00: return SECONDS; case 0x01: return MILLISECONDS; case 0x02: return NANOSECONDS; case 0x03: return MICROSECONDS; case 0x04: return MINUTES; case 0x05: return HOURS; case 0x06: return DAYS; case 0x07: return DEFAULT; case 0x08: return INFINITE; default: throw new IllegalArgumentException("Unsupported byte value: " + rightBits); } } public static KeyValuePair decodePair(byte timeUnitValues) { return new KeyValuePair<>(decode((byte) ((timeUnitValues & 0xf0) >> 4)), decode((byte) (timeUnitValues & 0x0f))); } } 1-10 package com.markyang.framework.pojo.rabbit; import com.markyang.framework.pojo.rabbit.message.MessageData; import lombok.AllArgsConstructor; import lombok.Getter; /** * RabbitMQ消息类型 * * @author yangchangliang * @version 1 */ @AllArgsConstructor @Getter public enum RabbitMessageType { /** * 队列相关的类型 * * QueuingDto */ RSV_QUEUING(MessageData.class); /** * 相关联类 */ private final Class clazz; } /** * Copyright 2019 ForgeRock AS. * * 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 com.forgerock.openbanking.common.services.security; import lombok.extern.slf4j.Slf4j; import net.logstash.logback.encoder.org.apache.commons.lang.StringEscapeUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Whitelist; import org.springframework.util.StringUtils; import java.util.Arrays; import java.util.Map; /** * Helper class to wrap the Jsoup implementation. This makes it easier to use a different type of sanitiser library in future by hiding implementation from the rest of the code. */ @Slf4j public class TextSanitiserService { private static final Document.OutputSettings OUTPUT_SETTINGS = new Document.OutputSettings() .prettyPrint(false); public static boolean hasHtmlContent(final Map.Entry formEntry) { if (formEntry == null || formEntry.getValue() == null || formEntry.getValue().length == 0) { return false; } return Arrays.stream(formEntry.getValue()) .anyMatch(TextSanitiserService::hasHtmlContent); } public static boolean hasHtmlContent(final String unsanitised) { if (StringUtils.isEmpty(unsanitised)) { return false; } String sanitised = Jsoup.clean(unsanitised, "", Whitelist.none(), OUTPUT_SETTINGS); // If different then html was removed boolean different = !unsanitised.equals(sanitised) && // This comparison is needed for scenarios when user posts escapable (e.g. &) or escaped (&) values in string. // We do not want to reject these kinds of string data so we compare with escaped and unescaped content and accept either if matching. !unsanitised.equals(StringEscapeUtils.unescapeXml(sanitised)); if (different) { log.debug("Supplied text contains HTML content. Before sanitisation: '{}', after sanitisation '{}'", unsanitised, sanitised); } return different; } } Test_Resolutions/src/main/java/ficha1_SV_13_14/ReflectIterableEager.java package ficha1_SV_13_14; import java.util.ArrayList; import java.util.Iterator; import java.util.function.Predicate; /** * Created by on 25/06/2015. */ public class ReflectIterableEager implements ReflectIterable { Iterable iterableSeq; Predicate pred; public ReflectIterableEager(Iterable iterableSeq){ this.iterableSeq= iterableSeq; } @Override public ReflectIterable filter(String fieldName, Object expected) { ArrayList items = new ArrayList<>(); if(pred == null) pred = new ReflectPredicate<>(fieldName,expected); else{ pred = ReflectPredicate.and(pred,new ReflectPredicate(fieldName,expected)); } for(T t : this){ System.out.println(t); if(pred.test(t)){ items.add(t); } } System.out.println("-----Final Select-----"); return reflectEager(items); } @Override public Iterator iterator() { return (Iterator)iterableSeq.iterator(); } public static ReflectIterable reflectEager(Iterable items){ return new ReflectIterableEager<>(items); } } /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.forscience.whistlepunk.devicemanager; import com.google.android.apps.forscience.whistlepunk.api.scalarinput.InputDeviceSpec; import java.util.List; public interface SensorGroup { /** @return false if this sensor hasn't been seen in this group */ boolean hasSensorKey(String sensorKey); /** Add {@code sensor} with key {@code sensorKey}. */ void addSensor(String sensorKey, ConnectableSensor sensor); /** @return true if the given sensorKey existed and was removed. */ boolean removeSensor(String sensorKey); /** * Replace the sensor (if any) currently at {@code sensorKey} with {@code sensor}. * *

Note that there are situations in which multiple asynchronous processes mean that sensorKey * is already gone before this executes, in which case this method should do the same thing as * addSensor. */ void replaceSensor(String sensorKey, ConnectableSensor sensor); int getSensorCount(); /** * @param providerId a key to the external sensor provider that advertises this service. * @param service * @param startSpinners whether this new service should be shown as "loading" */ void addAvailableService( String providerId, SensorDiscoverer.DiscoveredService service, boolean startSpinners); void onServiceScanComplete(String serviceId); void addAvailableDevice(SensorDiscoverer.DiscoveredDevice device); // TODO: too many methods that only some implementors care about void setMyDevices(List device); /** * Adds an available (not paired) sensor that this group might want to display * * @return true iff this group decides this sensor belongs to it. */ boolean addAvailableSensor(String sensorKey, ConnectableSensor sensor); /** * A sensor was added in another view. It shouldn't be displayed here, but if you need to know * about it, implement this. */ void onSensorAddedElsewhere(String newKey, ConnectableSensor sensor); } antopen/alipay-sdk-java-allsrc/main/java/com/alipay/api/domain/AlipayFinanceQuotationQuotetradeTradedaystateBatchqueryModel.java package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 查询一段日期范围的交易市场状态 * * @author auto create * @since 1.0, 2022-04-29 10:43:04 */ public class AlipayFinanceQuotationQuotetradeTradedaystateBatchqueryModel extends AlipayObject { private static final long serialVersionUID = 1139173719694765489L; /** * 查询的开始日期, 格式为 yyyyMMdd */ @ApiField("begin_date") private String beginDate; /** * 查询的开始日期, 格式为 yyyyMMdd */ @ApiField("end_date") private String endDate; /** * 市场, 查询该市场的交易日 */ @ApiField("market") private String market; public String getBeginDate() { return this.beginDate; } public void setBeginDate(String beginDate) { this.beginDate = beginDate; } public String getEndDate() { return this.endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getMarket() { return this.market; } public void setMarket(String market) { this.market = market; } } package net.liplum.coroutine; public class WaitForNextTick extends WaitForTicks{ public WaitForNextTick() { super(1); } } 0 /* * Copyright 2017 NEERC team * * 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 ru.ifmo.neerc.chat.android; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.util.Log; public class RosterFragment extends Fragment { private RecyclerView userList; private LinearLayoutManager layoutManager; private RosterAdapter adapter; private BroadcastReceiver userReceiver; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.roster, container, false); userList = (RecyclerView) view.findViewById(R.id.user_list); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); layoutManager = new LinearLayoutManager(getActivity()); userList.setLayoutManager(layoutManager); adapter = new RosterAdapter(); userList.setAdapter(adapter); } @Override public void onStart() { super.onStart(); userReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateUsers(); } }; getContext().registerReceiver(userReceiver, new IntentFilter(ChatService.USER)); updateUsers(); } @Override public void onStop() { super.onStop(); getContext().unregisterReceiver(userReceiver); } public void updateUsers() { adapter.update(); } } package com.jakublesko.jwtsecurity.configuration; import com.jakublesko.jwtsecurity.rest.impl.RestServiceExceptionMapper; import java.util.List; import org.apache.cxf.Bus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxrs.spring.JAXRSServerFactoryBeanDefinitionParser.SpringJAXRSServerFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @ComponentScan("org.apache.syncope.core.rest.cxf.service") @Configuration public class RestConfiguration { @Autowired private Bus bus; @Autowired private ApplicationContext ctx; @Bean public RestServiceExceptionMapper restServiceExceptionMapper() { return new RestServiceExceptionMapper(); } @Bean public Server restContainer() { SpringJAXRSServerFactoryBean restContainer = new SpringJAXRSServerFactoryBean(); restContainer.setBus(bus); restContainer.setAddress("/"); restContainer.setStaticSubresourceResolution(true); restContainer.setBasePackages(List.of( "com.jakublesko.jwtsecurity.rest.api", "com.jakublesko.jwtsecurity.rest.impl")); restContainer.setProviders(List.of(restServiceExceptionMapper())); restContainer.setApplicationContext(ctx); return restContainer.create(); } } mjevon/coding package com.design_parttern.headfirst.chap3_Factory; public abstract class AbstractProduct { //扩展属性 ExtendA extendA; abstract void create(); void product(){ } } package com.landtanin.teacherattendancemonitoring.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.landtanin.teacherattendancemonitoring.R; import com.landtanin.teacherattendancemonitoring.dao.StudentAttendanceDao; import io.realm.OrderedRealmCollection; import io.realm.RealmRecyclerViewAdapter; /** * Created by landtanin on 2/15/2017 AD. */ public class StudentListAdapter extends RealmRecyclerViewAdapter{ Context mContext; int redColor, greenColor, greyColor, indegoColor, statusTxtGreenColor, blackColor, orangeColor; public StudentListAdapter(@NonNull Context context, @Nullable OrderedRealmCollection data, boolean autoUpdate) { super(context, data, autoUpdate); mContext = context; } @Override public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { redColor = ContextCompat.getColor(parent.getContext(), R.color.colorPink100); greenColor = ContextCompat.getColor(parent.getContext(), R.color.colorRealGreen100); orangeColor = ContextCompat.getColor(parent.getContext(), R.color.colorOrange100); statusTxtGreenColor = ContextCompat.getColor(parent.getContext(), R.color.colorActiveStatus); greyColor = ContextCompat.getColor(parent.getContext(), R.color.colorGrey500); indegoColor = ContextCompat.getColor(parent.getContext(), R.color.colorIndigo50); blackColor = ContextCompat.getColor(parent.getContext(), android.R.color.black); View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_student, parent, false); return new RecyclerViewHolder(itemView); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (getData().size()!=0) { RecyclerViewHolder itemHolder = (RecyclerViewHolder) holder; // it needs RecyclerViewHolder, not RecyclerView.ViewHolder StudentAttendanceDao studentListItem = getData().get(position); itemHolder.studentNameTxt.setText(studentListItem.getName()); itemHolder.studentIdTxt.setText(studentListItem.getStudentId()); if (studentListItem.getAttendanceStatus().equals("checked")) { itemHolder.itemView.setBackgroundColor(greenColor); } else if (studentListItem.getAttendanceStatus().equals("late")) { itemHolder.itemView.setBackgroundColor(orangeColor); } else if (studentListItem.getAttendanceStatus().equals("end")) { itemHolder.itemView.setBackgroundColor(indegoColor); } } } @Override public int getItemCount() { return getData().size(); } public class RecyclerViewHolder extends RecyclerView.ViewHolder{ TextView studentNameTxt, studentIdTxt; public RecyclerViewHolder(View itemView) { super(itemView); studentNameTxt = (TextView) itemView.findViewById(R.id.studentNameTxt); studentIdTxt = (TextView) itemView.findViewById(R.id.studemtIdTxt); } } } realXuJiang/bigtable-sql package net.sourceforge.squirrel_sql.client.gui.desktopcontainer.docktabdesktop; public class AutoHideManager { } /* * Copyright 2019-2029 geekidea(https://github.com/geekidea) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.geekidea.springbootplus.framework.util; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; /** * 获取文件的内容类型 * mime-type参考:https://svn.apache.org/viewvc/httpd/httpd/trunk/docs/conf/mime.types?revision=1752884&view=co * @author geekidea * @date 2019/08/20 * @since */ @Slf4j public final class ContentTypeUtil { private static String MIME_TYPE_CONFIG_FILE = "config/mime-type.properties"; private static String DEFAULT_MIME_TYPE = "application/octet-stream"; private static Properties properties; static { try { properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(MIME_TYPE_CONFIG_FILE)); } catch (IOException e) { log.error("读取配置文件" + MIME_TYPE_CONFIG_FILE + "异常",e); } log.info(MIME_TYPE_CONFIG_FILE + " = " + properties); } /** * 获取文件内容类型 * @param file * @return */ public static String getContentType(File file){ if (file == null){ return null; } Path path = Paths.get(file.toURI()); if (path == null){ return null; } String contentType = null; try { contentType = Files.probeContentType(path); } catch (IOException e) { log.error("获取文件ContentType异常",e); } if (contentType == null){ // 读取拓展的自定义配置 contentType = getContentTypeByExtension(file); } // 设置默认的内容类型 if (contentType == null){ contentType = DEFAULT_MIME_TYPE; } return contentType; } /** * 根据文件后缀获取自定义配置的文件mime-type * @param file * @return */ private static String getContentTypeByExtension(File file){ if (properties == null){ return null; } String extension = FilenameUtils.getExtension(file.getName()); if (StringUtils.isBlank(extension)){ return null; } String contentType = properties.getProperty(extension); return contentType; } } src/main/java/com/chxd/policeDog/controller/WormImmueController.java package com.chxd.policeDog.controller; import com.chxd.policeDog.dao.IDogBaseInfoDao; import com.chxd.policeDog.dao.IWormImmueDao; import com.chxd.policeDog.vo.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.websocket.server.PathParam; import java.util.List; /** * Created by cheng on 2017/8/31. */ @RestController @RequestMapping("/wormImmue") public class WormImmueController extends BaseController { @Autowired private IDogBaseInfoDao dogBaseInfoDao; @Autowired private IWormImmueDao wormImmueDao; @RequestMapping("/list/worm/{pageSize}/{curPage}") public PageResultVO getWormList(@RequestBody DogWormVO dogWormVO, @PathParam("") PageVO pageVO) { PageResultVO page = new PageResultVO(); PoliceUserVO currentUser = getCurrentUser(); String userRole = currentUser.getUserRole(); if(UserRoleVO.NORMAL_USER.equals(userRole)){ dogWormVO.setPoliceId(currentUser.getId()); } try { List list = wormImmueDao.getWormList(dogWormVO, pageVO); Integer integer = wormImmueDao.getWormCount(dogWormVO); for(int i = 0; i dog = dogBaseInfoDao.selectAll(new DogBaseInfoVO(w.getDogId()), PageVO.getInstance()); if(dog.size() > 0) { w.setDogInfo(dog.get(0)); } } pageVO.setTotalRows(integer); page.setResult(list); page.setPageVO(pageVO); } catch (Exception e) { e.printStackTrace(); } return page; } @RequestMapping("/list/immue/{pageSize}/{curPage}") public PageResultVO getImmueList(@RequestBody DogImmueVO dogImmueVO, @PathParam("") PageVO pageVO) { PageResultVO page = new PageResultVO(); PoliceUserVO currentUser = getCurrentUser(); String userRole = currentUser.getUserRole(); if(UserRoleVO.NORMAL_USER.equals(userRole)){ dogImmueVO.setPoliceId(currentUser.getId()); } try { List list = wormImmueDao.getImmueList(dogImmueVO, pageVO); Integer integer = wormImmueDao.getImmueCount(dogImmueVO); for(int i = 0; i dog = dogBaseInfoDao.selectAll(new DogBaseInfoVO(w.getDogId()), PageVO.getInstance()); if(dog.size() > 0) { w.setDogInfo(dog.get(0)); } } pageVO.setTotalRows(integer); page.setResult(list); page.setPageVO(pageVO); } catch (Exception e) { e.printStackTrace(); } return page; } @RequestMapping("/finishWorm") public ResultVO finishWorm(@RequestBody List list) { ResultVO resultVO = ResultVO.getInstance(); try{ for(int i = 0; i list) { ResultVO resultVO = ResultVO.getInstance(); try{ for(int i = 0; i list) { ResultVO resultVO = ResultVO.getInstance(); try{ for (int i = 0; i < list.size(); i++) { DogWormVO dogWormVO = list.get(i); wormImmueDao.addWorm(dogWormVO); } }catch (Exception e){ e.printStackTrace(); resultVO.fail(e.getMessage()); } return resultVO; } @RequestMapping("/batchAddImmue") public ResultVO batchAddImmue(@RequestBody List list) { ResultVO resultVO = ResultVO.getInstance(); try{ for (int i = 0; i < list.size(); i++) { DogImmueVO dogImmueVO = list.get(i); wormImmueDao.addImmue(dogImmueVO); } }catch (Exception e){ e.printStackTrace(); resultVO.fail(e.getMessage()); } return resultVO; } @RequestMapping("/delWorm") public ResultVO delWorm(@RequestBody List list){ ResultVO resultVO = ResultVO.getInstance(); wormImmueDao.delWorm(list); return resultVO; } @RequestMapping("/delImmue") public ResultVO delImmue(@RequestBody List list){ ResultVO resultVO = ResultVO.getInstance(); wormImmueDao.delImmue(list); return resultVO; } @RequestMapping("/updateImmueState") public ResultVO updateImmueState(@RequestBody DogImmueVO dogImmueVO){ ResultVO resultVO = ResultVO.getInstance(); wormImmueDao.updateImmueState(dogImmueVO); return resultVO; } @RequestMapping("/updateWormState") public ResultVO updateWormState(@RequestBody DogWormVO dogWormVO){ ResultVO resultVO = ResultVO.getInstance(); wormImmueDao.updateWormState(dogWormVO); return resultVO; } } 1-10 package edu.rpi.rocs.client.ui; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.OptionElement; import com.google.gwt.dom.client.SelectElement; import com.google.gwt.user.client.ui.ListBox; public class ListBoxHTML extends ListBox { private static final int INSERT_AT_END = -1; public ListBoxHTML() { super(); } public ListBoxHTML(boolean multiple) { super(multiple); } public void addHTML(String html, String value) { insertHTML(html, value, INSERT_AT_END); } public void addStyleNameOfOption(int index, String name) { SelectElement select = getSelectElement2(); OptionElement option = select.getOptions().getItem(index); String clsname = option.getClassName(); if(clsname.startsWith(name+" ") || clsname.endsWith(" "+name)) return; if(clsname.contains((" "+name+" ").subSequence(0, name.length()+2))) return; clsname += " name"; option.setClassName(clsname); } public void removeStyleNameOfOption(int index, String name) { SelectElement select = getSelectElement2(); OptionElement option = select.getOptions().getItem(index); String clsname = option.getClassName(); if(clsname.startsWith(name+" ")) { clsname.replaceFirst(name+" ", ""); } else if(clsname.endsWith(" "+name)) { clsname.replaceFirst(" "+name+"$", ""); } else if(clsname.contains((" "+name+" ").subSequence(0, name.length()+2))) { clsname.replaceFirst(" "+name+" ", ""); } option.setClassName(clsname); } public void insertHTML(String html, String value, int index) { SelectElement select = getSelectElement2(); OptionElement option = Document.get().createOptionElement(); option.setInnerHTML(html); option.setValue(value); if((index == -1) || (index == select.getLength())) { //select.add(option, null); select.appendChild(option); } else { OptionElement before = select.getOptions().getItem(index); select.insertBefore(option, before); } } protected SelectElement getSelectElement2() { return getElement().cast(); } } /* * 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.kubernetes.operator.utils; import org.apache.flink.kubernetes.operator.TestUtils; import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.Pod; import org.junit.Assert; import org.junit.jupiter.api.Test; import java.util.Arrays; /** FlinkUtilsTest. */ public class FlinkUtilsTest { @Test public void testMergePods() throws Exception { Container container1 = new Container(); container1.setName("container1"); Container container2 = new Container(); container2.setName("container2"); Pod pod1 = TestUtils.getTestPod( "pod1 hostname", "pod1 api version", Arrays.asList(container2)); Pod pod2 = TestUtils.getTestPod( "pod2 hostname", "pod2 api version", Arrays.asList(container1, container2)); Pod mergedPod = FlinkUtils.mergePodTemplates(pod1, pod2); Assert.assertEquals(pod2.getApiVersion(), mergedPod.getApiVersion()); Assert.assertEquals(pod2.getSpec().getContainers(), mergedPod.getSpec().getContainers()); } } package com.team007.appalanche.view; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Switch; import com.team007.appalanche.experiment.BinomialExperiment; import com.team007.appalanche.experiment.CountBasedExperiment; import com.team007.appalanche.R; import com.team007.appalanche.experiment.Experiment; import com.team007.appalanche.experiment.MeasurementExperiment; import com.team007.appalanche.experiment.NonNegativeCountExperiment; import com.team007.appalanche.user.User; /** * This Fragment is created when a user wants to create an experiment. * The user can select attributes such as the minimum number of trials, * the region of the experiment, and the experiment's description. */ public class AddExperimentFragment extends DialogFragment { private OnFragmentInteractionListener listener; public static AddExperimentFragment newInstance(User user) { Bundle args = new Bundle(); args.putSerializable("User", user); AddExperimentFragment fragment = new AddExperimentFragment(); fragment.setArguments(args); return fragment; } @NonNull public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_add_experiment, null); // Get EditTexts EditText experimentDescription = view.findViewById(R.id.expDescription); EditText experimentRegion = view.findViewById(R.id.expRegion); EditText minTrials = view.findViewById(R.id.expTrials); Switch geoRequired = view.findViewById(R.id.geoRequired); // Initialize Dialog AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // Initialize Spinner String[] types = {"COUNT", "BINOMIAL", "NON NEGATIVE COUNT", "MEASUREMENT"}; Spinner spin = (Spinner) view.findViewById(R.id.expType); ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item, types); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spin.setAdapter(adapter); return builder .setView(view) .setTitle("NEW EXPERIMENT") .setNegativeButton("Cancel", null) .setPositiveButton("Post", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { User user = (User) getArguments().getSerializable("User"); // Get the experiment details String description = experimentDescription.getText().toString(); String region = experimentRegion.getText().toString(); int numTrials; try { numTrials = Integer.valueOf(minTrials.getText().toString()); } catch (NumberFormatException e) { numTrials = 0; } // Get the type of the experiment String type = spin.getSelectedItem().toString(); // Get whether geolocation is required boolean geolocation = geoRequired.isChecked(); switch(type) { case "COUNT": Experiment countExp = new CountBasedExperiment(description, region, numTrials, geolocation, true, user.getId()); listener.addExperiment(countExp); break; case "BINOMIAL": Experiment binomialExp = new BinomialExperiment(description, region, numTrials, geolocation, true, user.getId()); listener.addExperiment(binomialExp); break; case "NON NEGATIVE COUNT": Experiment nonNegExp = new NonNegativeCountExperiment(description, region, numTrials, geolocation, true, user.getId()); listener.addExperiment(nonNegExp); break; case "MEASUREMENT": Experiment measurementExp = new MeasurementExperiment(description, region, numTrials, geolocation, true, user.getId()); listener.addExperiment(measurementExp); break; } } }) .create(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_add_experiment, container, false); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener){ listener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } public interface OnFragmentInteractionListener { void addExperiment(Experiment newExp); } }timfel/netbeans /* * 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.netbeans.modules.derby; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.netbeans.modules.derby.ui.DerbyPropertiesPanel; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.filesystems.FileLock; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Mutex; import org.openide.util.NbBundle; /** * * @author */ public class Util { private static final String DERBY_CLIENT = "derbyclient.jar"; // NOI18N private Util() { } public static boolean hasInstallLocation() { return getCheckedLocation() != null; } public static boolean checkInstallLocation() { if (!hasInstallLocation()) { showInformation(NbBundle.getMessage(Util.class, "MSG_DerbyLocationIncorrect")); return false; } return true; } private static File getCheckedLocation() { File location = new File(DerbyOptions.getDefault().getLocation()); if (location.isAbsolute() && location.isDirectory() && location.exists()) { return location; } return null; } public static File getDerbyFile(String relPath) { File location = getCheckedLocation(); if (location != null) { return new File(location, relPath); } return null; } public static boolean ensureSystemHome() { if (DerbyOptions.getDefault().getSystemHome().length() <= 0) { return Mutex.EVENT.writeAccess(new Mutex.Action() { public Boolean run() { return DerbyPropertiesPanel.showDerbyProperties(); } }); } return true; } public static void showInformation(final String msg){ Mutex.EVENT.readAccess(new Runnable() { public void run() { NotifyDescriptor d = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(d); } }); } public static boolean isDerbyInstallLocation(File location) { if (location == null || ! location.exists()) { return false; } File libDir = new File(location, "lib"); // NOI18N if (!libDir.exists()) { return false; } File[] libs = libDir.listFiles(); if (libs == null || libs.length <= 0) { return false; } for (File lib : libs) { if (lib.getName().equals(DERBY_CLIENT)) { return true; } } return false; } public static void extractZip(File source, FileObject target) throws IOException { FileInputStream is = new FileInputStream(source); try { ZipInputStream zis = new ZipInputStream(is); ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { String name = ze.getName(); // if directory, create if (ze.isDirectory()) { FileUtil.createFolder(target, name); continue; } // if file, copy FileObject fd = FileUtil.createData(target, name); FileLock lock = fd.lock(); try { OutputStream os = fd.getOutputStream(lock); try { FileUtil.copy(zis, os); } finally { os.close(); } } finally { lock.releaseLock(); } } } finally { is.close(); } } /** * Check if candiate FileObject is a derby database. * * @param candidate the value of candidate * @return true if candidate is a derby database */ public static boolean isDerbyDatabase(FileObject candidate) { if (candidate.isFolder()) { FileObject sp = candidate.getFileObject("service.properties"); return sp != null && FileUtil.toFile(sp) != null; } else { return false; } } } codacy-badger/opensrp-server-websrc/test/java/org/opensrp/web/controller/it/AuditMessageControllerIntegrationTest.java package org.opensrp.web.controller.it; import org.junit.Ignore; import org.opensrp.common.audit.Auditor; import org.opensrp.web.rest.it.BaseResourceTest; import org.springframework.beans.factory.annotation.Autowired; @Ignore public class AuditMessageControllerIntegrationTest extends BaseResourceTest { @Autowired Auditor auditor; /* @Test public void getAuditMessagesBasedOnPreviousIndex() throws Exception { String url = "/audit/messages"; Auditor.AuditMessageBuilder auditMessageBuilder = new Auditor.AuditMessageBuilder(auditor, AuditMessageType.NORMAL); auditMessageBuilder.done(); auditMessageBuilder = new Auditor.AuditMessageBuilder(auditor, AuditMessageType.SMS); auditMessageBuilder.done(); MvcResult mvcResult = this.mockMvc.perform(get(url + "?previousAuditMessageIndex=1").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(print()).andReturn(); String responseString = mvcResult.getResponse().getContentAsString(); JsonNode actualObj = mapper.readTree(responseString); Client actualClient = mapper.treeToValue(actualObj, Client.class); assertEquals(Auditor.AuditMessageItem.from(auditor.messagesSince(1)), actualClient); }*/ } ajaysagarn/dynamo-repository-servicesrc/main/java/com/ajsa/dyrepo/repository/property/dao/PropertyDAO.java package com.ajsa.dyrepo.repository.property.dao; import com.ajsa.dyrepo.repository.property.model.Property; import com.ajsa.dyrepo.util.RepositoryException; import java.util.Optional; public interface PropertyDAO { public Property createProperty(String nodeIdPath, Property node); public Optional readProperty(String nodeIdPath, String propertyId) throws RepositoryException; public Property updateProperty(String nodeIdPath, Property property); public void deleteProperty(String propertyPath, String propertyId); }Storm/src/main/java/cn/edu/ecnu/example/storm/wordcount/window/WindowWordCountTopology.java package cn.edu.ecnu.example.storm.wordcount.window; import cn.edu.ecnu.example.storm.common.SocketSpout; import cn.edu.ecnu.example.storm.wordcount.SplitBolt; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import org.apache.storm.StormSubmitter; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.tuple.Fields; public class WindowWordCountTopology { public static void main(String[] args) throws Exception { if (args.length < 3) { System.exit(-1); return; } /* 步骤1:构建拓扑 */ TopologyBuilder builder = new TopologyBuilder(); // 设置Spout的名称为"SPOUT",executor数量为1,任务数量为1 builder.setSpout("SPOUT", new SocketSpout(args[1], args[2]), 1); // 设置Bolt的名称为"SPLIT",executor数量为2,任务数量为2,与"SPOUT"之间的流分组策略为随机分组 builder.setBolt("SPLIT", new SplitBolt(), 2).setNumTasks(2).shuffleGrouping("SPOUT"); // 设置Bolt取名"WINDOWCOUNT",executor数量为2,任务数量为2,订阅策略为fieldsGrouping builder.setBolt("WINDOWCOUNT", new WindowBolt(), 2).fieldsGrouping("SPLIT", new Fields("word")); /* 步骤2:设置配置信息 */ Config conf = new Config(); conf.setDebug(false); // 关闭调试模式 conf.setNumWorkers(2); // 设置Worker数量为2 conf.setNumAckers(0); // 设置Acker数量为0 /* 步骤3:指定程序运行的方式 */ if (args[0].equals("cluster")) { // 在集群运行程序,拓扑的名称为WINDOWWORDCOUNT StormSubmitter.submitTopology("WINDOWWORDCOUNT", conf, builder.createTopology()); } else if (args[0].equals("local")) { // 在本地IDE调试程序,拓扑的名称为WINDOWWORDCOUNT LocalCluster cluster = new LocalCluster(); cluster.submitTopology("WINDOWWORDCOUNT", conf, builder.createTopology()); } else { System.exit(-2); } } } uktrade/lite-user-servicesrc/test/java/uk/gov/bis/lite/user/resource/UserDetailsResourceTest.java0 package uk.gov.bis.lite.user.resource; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static uk.gov.bis.lite.user.TestUtils.generateJwtAuthorizationHeader; import static uk.gov.bis.lite.user.spire.user.details.SpireUserDetailsTestUtils.ACCOUNT_STATUS; import static uk.gov.bis.lite.user.spire.user.details.SpireUserDetailsTestUtils.ACCOUNT_TYPE; import static uk.gov.bis.lite.user.spire.user.details.SpireUserDetailsTestUtils.CONTACT_EMAIL_ADDRESS; import static uk.gov.bis.lite.user.spire.user.details.SpireUserDetailsTestUtils.CONTACT_PHONE_NUMBER; import static uk.gov.bis.lite.user.spire.user.details.SpireUserDetailsTestUtils.FIRST_NAME; import static uk.gov.bis.lite.user.spire.user.details.SpireUserDetailsTestUtils.FULL_NAME; import static uk.gov.bis.lite.user.spire.user.details.SpireUserDetailsTestUtils.LAST_NAME; import static uk.gov.bis.lite.user.spire.user.details.SpireUserDetailsTestUtils.TITLE; import io.dropwizard.auth.AuthDynamicFeature; import io.dropwizard.auth.AuthValueFactoryProvider; import io.dropwizard.testing.junit.ResourceTestRule; import org.assertj.core.api.Assertions; import org.junit.Rule; import org.junit.Test; import uk.gov.bis.lite.common.jwt.LiteJwtAuthFilterHelper; import uk.gov.bis.lite.common.jwt.LiteJwtUser; import uk.gov.bis.lite.user.TestUtils; import uk.gov.bis.lite.user.api.view.UserDetailsView; import uk.gov.bis.lite.user.api.view.enums.AccountStatus; import uk.gov.bis.lite.user.service.UserDetailsService; import uk.gov.bis.lite.user.spire.user.details.SpireUserDetails; import java.util.Map; import java.util.Optional; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; public class UserDetailsResourceTest { private static final String ID = "24492"; private static final String USER_DETAILS_TYPE_PATH = "/user-details"; private final UserDetailsService userDetailsService = mock(UserDetailsService.class); @Rule public final ResourceTestRule resources = ResourceTestRule.builder() .addResource(new UserDetailsResource(userDetailsService)) .addProvider(new AuthDynamicFeature(LiteJwtAuthFilterHelper.buildAuthFilter(TestUtils.JWT_SHARED_SECRET))) .addProvider(new AuthValueFactoryProvider.Binder<>(LiteJwtUser.class)) .build(); @Test public void userExistsTest() throws Exception { SpireUserDetails userDetails = new SpireUserDetails() .setTitle(TITLE) .setFirstName(FIRST_NAME) .setLastName(LAST_NAME) .setFullName(FULL_NAME) .setContactEmailAddress(CONTACT_EMAIL_ADDRESS) .setContactPhoneNumber(CONTACT_PHONE_NUMBER) .setAccountType(ACCOUNT_TYPE) .setAccountStatus(ACCOUNT_STATUS); when(userDetailsService.getUserDetails(ID)).thenReturn(Optional.of(userDetails)); Response response = resources.client() .target(USER_DETAILS_TYPE_PATH + "/" + ID) .request() .header(HttpHeaders.AUTHORIZATION, generateJwtAuthorizationHeader(ID, CONTACT_EMAIL_ADDRESS, FULL_NAME)) .get(); assertThat(response.getStatus()).isEqualTo(200); UserDetailsView result = response.readEntity(UserDetailsView.class); assertThat(result.getTitle()).isEqualTo(TITLE); assertThat(result.getFirstName()).isEqualTo(FIRST_NAME); assertThat(result.getLastName()).isEqualTo(LAST_NAME); assertThat(result.getFullName()).isEqualTo(FULL_NAME); assertThat(result.getContactEmailAddress()).isEqualTo(CONTACT_EMAIL_ADDRESS); assertThat(result.getContactPhoneNumber()).isEqualTo(CONTACT_PHONE_NUMBER); assertThat(result.getAccountStatus()).isEqualTo(AccountStatus.ACTIVE); } @Test public void userDoesNotExistTest() throws Exception { when(userDetailsService.getUserDetails(ID)).thenReturn(Optional.empty()); Response response = resources.client() .target(USER_DETAILS_TYPE_PATH + "/" + ID) .request() .header(HttpHeaders.AUTHORIZATION, generateJwtAuthorizationHeader(ID, CONTACT_EMAIL_ADDRESS, FULL_NAME)) .get(); assertThat(response.getStatus()).isEqualTo(404); Map map = TestUtils.getMapFromResponse(response); Assertions.assertThat(map).hasSize(2); Assertions.assertThat(map).containsEntry("code", "404"); Assertions.assertThat(map).containsEntry("message", "User not found"); } @Test public void userIdTokenDoesNotMatchUrlTest() throws Exception { Response response = resources.client() .target(USER_DETAILS_TYPE_PATH + "/" + "1") .request() .header(HttpHeaders.AUTHORIZATION, generateJwtAuthorizationHeader("999", CONTACT_EMAIL_ADDRESS, FULL_NAME)) .get(); assertThat(response.getStatus()).isEqualTo(401); Map map = TestUtils.getMapFromResponse(response); Assertions.assertThat(map).hasSize(2); Assertions.assertThat(map).containsEntry("code", "401"); Assertions.assertThat(map).containsEntry("message", "userId 1 does not match value supplied in token 999"); } @Test public void tokenNotSuppliedTest() throws Exception { Response response = resources.client() .target(USER_DETAILS_TYPE_PATH + "/" + ID) .request() .get(); assertThat(response.getStatus()).isEqualTo(401); } }package fr.inria.spirals.repairnator.states; /** * This enum is used to define if information has been pushed during execution of the pipeline */ public enum PushState { NONE, REPO_INITIALIZED, REPO_NOT_INITIALIZED, REPAIR_INFO_COMMITTED, REPAIR_INFO_NOT_COMMITTED, PATCH_COMMITTED, PATCH_NOT_COMMITTED, PROCESS_END_COMMITTED, PROCESS_END_NOT_COMMITTED, CHANGED_TESTS_COMMITTED, CHANGED_TESTS_NOT_COMMITTED, REPO_PUSHED, REPO_NOT_PUSHED } // [START woosmap_http_zones] OkHttpClient client = new OkHttpClient().newBuilder() .build(); Request request = new Request.Builder() .url("https://api.woosmap.com/zones/ZoneA/?private_key=YOUR_PRIVATE_API_KEY") .method("GET", null) .build(); Response response = client.newCall(request).execute(); // [END woosmap_http_zones]/* * Copyright 2016 ANI Technologies Pvt. Ltd. * * 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.olacabs.fabric.model.event; import lombok.Builder; import lombok.Getter; import lombok.Setter; import lombok.Singular; import java.util.Collections; import java.util.List; import java.util.Map; /** * TODO Add more. */ public final class EventSet { @Getter private final int sourceId; @Getter private final int partitionId; @Getter private final boolean isSourceGenerated; @Getter private final List events; @Getter @Setter private long id; /** * A gobally unique transaction id. This needs to be carried forward from parent. Will be set by system. * This makes sense only for transactional sources like kafka. */ @Getter @Setter private long transactionId; @Getter @Setter private Map meta; @Getter private boolean isAggregate; @Builder(builderMethodName = "eventFromSourceBuilder", builderClassName = "EventFromSourceBuilder") private EventSet(long id, int sourceId, int partitionId, @Singular List events, long transactionId, @Singular("meta") Map meta) { this.id = id; this.sourceId = sourceId; this.partitionId = partitionId; this.events = events; this.meta = meta; this.isSourceGenerated = (-1 != this.sourceId); this.transactionId = transactionId; } @Builder(builderMethodName = "eventFromEventBuilder", builderClassName = "EventFromEventBuilder") private EventSet(int partitionId, @Singular List events, boolean isAggregate) { // Just a dummy id, not really used anywhere this.id = Long.MAX_VALUE; this.partitionId = partitionId; this.isAggregate = isAggregate; this.events = events; this.sourceId = -1; this.isSourceGenerated = false; this.meta = Collections.emptyMap(); } } Team-Fruit/FactorioForge package net.teamfruit.factorioforge.factorioapi.data.modportal; import java.util.List; import net.teamfruit.factorioforge.factorioapi.IResponse; import net.teamfruit.factorioforge.factorioapi.ModListAPI; import net.teamfruit.factorioforge.factorioapi.data.impl.modportal.Result; public interface IModList extends IResponse { /** * Information on ModList page. * @return IPagination */ IPagination getPagination(); /** * A list of mods, matching any filters you specified. * @return List */ List getResults(); boolean hasNext(); ModListAPI next(); } package com.misterpemodder.shulkerboxtooltip.impl.provider; import com.misterpemodder.shulkerboxtooltip.api.provider.BlockEntityPreviewProvider; import net.minecraft.item.ItemStack; public class FurnacePreviewProvider extends BlockEntityPreviewProvider { public FurnacePreviewProvider() { super(3, false); } @Override public boolean isFullPreviewAvailable(ItemStack stack) { return false; } } open-sphere-base/core/src/main/java/io/opensphere/core/geometry/renderproperties/PolygonRenderProperties.java package io.opensphere.core.geometry.renderproperties; /** Render properties specific to polygon geometries. */ public interface PolygonRenderProperties extends PolylineRenderProperties { /** * Clone this set of render properties. * * @return The cloned render properties. */ @Override PolygonRenderProperties clone(); /** * Get the fill color render properties. If the polygon is not filled, this * is {@code null}. * * @return The render properties. */ ColorRenderProperties getFillColorRenderProperties(); } package com.mysiteforme.admin.config; import com.jagregory.shiro.freemarker.ShiroTags; import com.mysiteforme.admin.freemark.*; import freemarker.template.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; import javax.annotation.PostConstruct; /** * Created by huangyl on 2017/11/26. * todo: */ @Component public class FreemarkerConfig { @Autowired private Configuration configuration; @Autowired private SystemDirective systemDirective; @Autowired private ArticleDirective articleDirective; @Autowired private IndexArticleDirective indexArticleDirective; @Autowired private ChannelDirective channelDirective; @Autowired private ParentChannelListDirective parentChannelListDirective; @Autowired private ArticleClickTempletModel articleClickTempletModel; @Autowired private SysUserTempletModel sysUserTempletModel; @Autowired private TagsTempletModel tagsTempletModel; @Autowired private NewCommentArticleTempletModel newCommentArticleTempletModel; @Autowired private LookLikeArticlesTempletModel lookLikeArticlesTempletModel; @Autowired private CommentNumberTempletModel commentNumberTempletModel; @Autowired private FreeMarkerViewResolver resolver; @Autowired private FreeMarkerConfigurer freeMarkerConfigurer; @PostConstruct public void setSharedVariable() { //系统字典标签 configuration.setSharedVariable("my", systemDirective); //文章文章标签 configuration.setSharedVariable("ar", articleDirective); //文章首页文章列表标签 configuration.setSharedVariable("myindex", indexArticleDirective); //文章栏目标签 configuration.setSharedVariable("mychannel", channelDirective); //文章当前栏目所有父目录集合标签 configuration.setSharedVariable("articleChannelList", parentChannelListDirective); //获取文章点击量标签 configuration.setSharedVariable("clickNumber", articleClickTempletModel); //获取文章评论数量 configuration.setSharedVariable("commentNumber", commentNumberTempletModel); //获取系统用户信息 configuration.setSharedVariable("sysuser", sysUserTempletModel); //获取标签集合 configuration.setSharedVariable("tags", tagsTempletModel); //最新评论文章集合 configuration.setSharedVariable("nca", newCommentArticleTempletModel); //当前文章相似的文章 configuration.setSharedVariable("same", lookLikeArticlesTempletModel); // 加上这句后,可以在页面上使用shiro标签 freeMarkerConfigurer.getConfiguration().setSharedVariable("shiro", new ShiroTags()); // 加上这句后,可以在页面上用${context.contextPath}获取contextPath resolver.setRequestContextAttribute("context"); } } 1-10 package com.alibaba.druid.bvt.sql.postgresql.select; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.util.JdbcConstants; import junit.framework.TestCase; import java.util.List; public class PGSelectTest80_json extends TestCase { public void test_0() throws Exception { String sql = "select '[{\"a\":\"foo\"},{\"b\":\"bar\"},{\"c\":\"baz\"}]'::json->2"; final List statements = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL); assertEquals(1, statements.size()); final SQLStatement stmt = statements.get(0); assertEquals("SELECT '[{\"a\":\"foo\"},{\"b\":\"bar\"},{\"c\":\"baz\"}]'::json -> 2", stmt.toString()); assertEquals("select '[{\"a\":\"foo\"},{\"b\":\"bar\"},{\"c\":\"baz\"}]'::json -> 2", stmt.toLowerCaseString()); } public void test_1() throws Exception { String sql = "select '{\"a\": {\"b\":\"foo\"}}'::json->'a'"; final List statements = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL); assertEquals(1, statements.size()); final SQLStatement stmt = statements.get(0); assertEquals("SELECT '{\"a\": {\"b\":\"foo\"}}'::json -> 'a'", stmt.toString()); assertEquals("select '{\"a\": {\"b\":\"foo\"}}'::json -> 'a'", stmt.toLowerCaseString()); } public void test_2() throws Exception { String sql = "select '[1,2,3]'::json->>2"; final List statements = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL); assertEquals(1, statements.size()); final SQLStatement stmt = statements.get(0); assertEquals("SELECT '[1,2,3]'::json ->> 2", stmt.toString()); assertEquals("select '[1,2,3]'::json ->> 2", stmt.toLowerCaseString()); } public void test_3() throws Exception { String sql = "select '{\"a\": {\"b\":{\"c\": \"foo\"}}}'::json#>'{a,b}'"; final List statements = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL); assertEquals(1, statements.size()); final SQLStatement stmt = statements.get(0); assertEquals("SELECT '{\"a\": {\"b\":{\"c\": \"foo\"}}}'::json# > '{a,b}'", stmt.toString()); assertEquals("select '{\"a\": {\"b\":{\"c\": \"foo\"}}}'::json# > '{a,b}'", stmt.toLowerCaseString()); } public void test_4() throws Exception { String sql = "select '{\"a\":1, \"b\":2}'::jsonb @> '{\"b\":2}'::jsonb"; final List statements = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL); assertEquals(1, statements.size()); final SQLStatement stmt = statements.get(0); assertEquals("SELECT '{\"a\":1, \"b\":2}'::jsonb @> '{\"b\":2}'::jsonb", stmt.toString()); assertEquals("select '{\"a\":1, \"b\":2}'::jsonb @> '{\"b\":2}'::jsonb", stmt.toLowerCaseString()); } public void test_5() throws Exception { String sql = "select '{\"a\":1, \"b\":2}'::jsonb <@ '{\"b\":2}'::jsonb"; final List statements = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL); assertEquals(1, statements.size()); final SQLStatement stmt = statements.get(0); assertEquals("SELECT '{\"a\":1, \"b\":2}'::jsonb <@ '{\"b\":2}'::jsonb", stmt.toString()); assertEquals("select '{\"a\":1, \"b\":2}'::jsonb <@ '{\"b\":2}'::jsonb", stmt.toLowerCaseString()); } public void test_6() throws Exception { String sql = "select '{\"a\":1, \"b\":2}'::jsonb ? 'b'"; final List statements = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL); assertEquals(1, statements.size()); final SQLStatement stmt = statements.get(0); assertEquals("SELECT '{\"a\":1, \"b\":2}'::jsonb ? 'b'", stmt.toString()); assertEquals("select '{\"a\":1, \"b\":2}'::jsonb ? 'b'", stmt.toLowerCaseString()); } public void test_7() throws Exception { String sql = "select '{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?| array['b', 'c']"; final List statements = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL); assertEquals(1, statements.size()); final SQLStatement stmt = statements.get(0); assertEquals("SELECT '{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?| array['b', 'c']", stmt.toString()); assertEquals("select '{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?| array['b', 'c']", stmt.toLowerCaseString()); } public void test_8() throws Exception { String sql = "select '{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?& array['b', 'c']"; final List statements = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL); assertEquals(1, statements.size()); final SQLStatement stmt = statements.get(0); assertEquals("SELECT '{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?& array['b', 'c']", stmt.toString()); assertEquals("select '{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?& array['b', 'c']", stmt.toLowerCaseString()); } } 1-10 package dcraft.db.fileindex; import dcraft.db.DatabaseException; import dcraft.db.IRequestContext; import dcraft.db.util.ByteUtil; import dcraft.db.util.DocumentIndexBuilder; import dcraft.filestore.CommonPath; import dcraft.filevault.Vault; import dcraft.hub.app.ApplicationHub; import dcraft.hub.op.IVariableAware; import dcraft.hub.op.OperatingContextException; import dcraft.locale.IndexInfo; import dcraft.locale.LocaleUtil; import dcraft.log.Logger; import dcraft.struct.ListStruct; import dcraft.struct.RecordStruct; import dcraft.struct.Struct; import dcraft.tenant.Site; import dcraft.util.StringUtil; import dcraft.util.TimeUtil; import java.math.BigDecimal; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; public class FileIndexAdapter { static public FileIndexAdapter of(IRequestContext request) { FileIndexAdapter adapter = new FileIndexAdapter(); adapter.request = request; return adapter; } static public List pathToIndex(Vault vault, CommonPath path) { List indexkeys = new ArrayList<>(); Site site = vault.getSite(); indexkeys.add(site.getTenant().getAlias()); indexkeys.add("dcFileIndex"); indexkeys.add(site.getAlias()); indexkeys.add(vault.getName()); if (path != null) { for (String part : path.getParts()) indexkeys.add(part); } return indexkeys; } protected IRequestContext request = null; // don't call for general code... protected FileIndexAdapter() { } public IRequestContext getRequest() { return this.request; } // -1 means recursive, 1 = just this level, > 1 means just this many levels public void traverseIndex(Vault vault, CommonPath path, int depth, IVariableAware scope, IFilter filter) throws OperatingContextException { try { RecordStruct frec = this.fileInfo(vault, path, scope); if ((frec != null) && ! frec.getFieldAsBooleanOrFalse("IsFolder")) { //System.out.println("Found: " + path + " - " + state + " - " + title); if (! filter.check(this, scope, vault, path, frec).resume) return; } else if (depth != 0) { List indexkeys = FileIndexAdapter.pathToIndex(vault, path); // start at top indexkeys.add(null); byte[] pkey = this.request.getInterface().nextPeerKey(indexkeys.toArray()); while (pkey != null) { Object pval = ByteUtil.extractValue(pkey); if (pval instanceof String) { this.traverseIndex(vault, path.resolve((String) pval), depth - 1, scope, filter); } indexkeys.remove(indexkeys.size() - 1); indexkeys.add(pval); pkey = this.request.getInterface().nextPeerKey(indexkeys.toArray()); } } } catch (DatabaseException x) { Logger.error("Unable to delete index file " + path + " in db: " + x); } } //TODO support files too - look at EncryptedFileStore getInfo - also fix the code above to ignore folders public RecordStruct fileInfo(Vault vault, CommonPath path, IVariableAware scope) throws OperatingContextException { try { List entrykeys = FileIndexAdapter.pathToIndex(vault, path); Object marker = this.request.getInterface().get(entrykeys.toArray()); if ("Folder".equals(Struct.objectToString(marker))) { RecordStruct frec = RecordStruct.record(); frec.with("State", "Present"); frec.with("IsFolder", true); return frec; } else if ("XFolder".equals(Struct.objectToString(marker))) { return null; } else if (marker != null) { // Either is true or "File" // state entrykeys.add("State"); entrykeys.add(null); byte[] pkey = this.request.getInterface().nextPeerKey(entrykeys.toArray()); if (pkey == null) return null; Object pval = ByteUtil.extractValue(pkey); entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("State"); entrykeys.add(pval); RecordStruct frec = RecordStruct.record(); frec.with("State", Struct.objectToString(this.request.getInterface().get(entrykeys.toArray()))); /* entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("History"); entrykeys.add(pval); frec.with("History", this.request.getInterface().get(entrykeys.toArray())); */ BigDecimal stamp = Struct.objectToDecimal(pval); if (stamp == null) stamp = BigDecimal.ZERO; frec.with("Modified", stamp.negate()); // public entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("Public"); frec.with("Public", Struct.objectToBoolean(this.request.getInterface().get(entrykeys.toArray()), true)); // title entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("eng"); // TODO current locale entrykeys.add("Title"); frec.with("Title", Struct.objectToString(this.request.getInterface().get(entrykeys.toArray()))); // summary entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("eng"); // TODO current locale entrykeys.add("Summary"); frec.with("Summary", Struct.objectToString(this.request.getInterface().get(entrykeys.toArray()))); /* // search indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add("eng"); // TODO current locale indexkeys.add("Search"); frec.with("Search", Struct.objectToString(this.request.getInterface().get(indexkeys.toArray()))); */ // sort hint entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("eng"); // TODO current locale entrykeys.add("SortHint"); frec.with("SortHint", Struct.objectToString(this.request.getInterface().get(entrykeys.toArray()))); // badges entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("Badges"); frec.with("Badges", Struct.objectToList(this.request.getInterface().get(entrykeys.toArray()))); return frec; } else { entrykeys.add(null); byte[] ekey = this.request.getInterface().nextPeerKey(entrykeys.toArray()); if (ekey != null) { // the folder is implied by path RecordStruct frec = RecordStruct.record(); frec.with("State", "Present"); frec.with("Implied", true); frec.with("IsFolder", true); return frec; } } } catch (DatabaseException x) { Logger.error("Unable to get index file info " + path + " in db: " + x); } return null; } public RecordStruct fileDeposit(Vault vault, CommonPath path, IVariableAware scope) throws OperatingContextException { try { List entrykeys = FileIndexAdapter.pathToIndex(vault, path); Object marker = this.request.getInterface().get(entrykeys.toArray()); if ("Folder".equals(Struct.objectToString(marker))) { return null; } else if ("XFolder".equals(Struct.objectToString(marker))) { return null; } else if (marker != null) { // Either is true or "File" // state entrykeys.add("State"); entrykeys.add(null); byte[] pkey = this.request.getInterface().nextPeerKey(entrykeys.toArray()); while (pkey != null) { Object pval = ByteUtil.extractValue(pkey); entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("State"); entrykeys.add(pval); String state = Struct.objectToString(this.request.getInterface().get(entrykeys.toArray())); if (! "Present".equals(state)) return null; entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("History"); entrykeys.add(pval); RecordStruct hist = Struct.objectToRecord(this.request.getInterface().get(entrykeys.toArray())); if ("Deposit".equals(hist.getFieldAsString("Source"))) return hist; // go to next State entrykeys = FileIndexAdapter.pathToIndex(vault, path); entrykeys.add("State"); entrykeys.add(pval); pkey = this.request.getInterface().nextPeerKey(entrykeys.toArray()); } } } catch (DatabaseException x) { Logger.error("Unable to get index file deposit " + path + " in db: " + x); } return null; } public void clearSiteIndex(Site site) { try { List indexkeys = new ArrayList<>(); indexkeys.add(site.getTenant().getAlias()); indexkeys.add("dcFileIndex"); indexkeys.add(site.getAlias()); this.request.getInterface().kill(indexkeys.toArray()); } catch (DatabaseException x) { Logger.error("Unable to clea file index in site db: " + x); } } public void clearVaultIndex(Vault vault) { try { List indexkeys = FileIndexAdapter.pathToIndex(vault, null); this.request.getInterface().kill(indexkeys.toArray()); } catch (DatabaseException x) { Logger.error("Unable to clea file index in db: " + x); } } public void indexFile(Vault vault, CommonPath path, ZonedDateTime time, RecordStruct history) throws OperatingContextException { try { // set entry marker List indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add("File"); this.request.getInterface().set(indexkeys.toArray()); // add state indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add("State"); indexkeys.add((time != null) ? ByteUtil.dateTimeToReverse(time) : BigDecimal.ZERO); indexkeys.add("Present"); // don't use ByteUtil.dateTimeToReverse(file.getModificationAsTime()) - using zero is better for eventual consistency across nodes this.request.getInterface().set(indexkeys.toArray()); // add history indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add("History"); indexkeys.add((time != null) ? ByteUtil.dateTimeToReverse(time) : BigDecimal.ZERO); indexkeys.add(history); // don't use ByteUtil.dateTimeToReverse(file.getModificationAsTime()) - using zero is better for eventual consistency across nodes this.request.getInterface().set(indexkeys.toArray()); this.indexFolderEnsure(vault, path.getParent()); } catch (DatabaseException x) { Logger.error("Unable to index file " + path + " in db: " + x); } } public void indexFileEnsure(Vault vault, CommonPath path) throws OperatingContextException { try { // set public marker List indexkeys = FileIndexAdapter.pathToIndex(vault, path); ZonedDateTime now = TimeUtil.now(); boolean needbase = false; if (! this.request.getInterface().isSet(indexkeys.toArray())) { needbase = true; } else { // state indexkeys.add("State"); indexkeys.add(null); byte[] pkey = this.request.getInterface().nextPeerKey(indexkeys.toArray()); if (pkey != null) { Object pval = ByteUtil.extractValue(pkey); indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add("State"); indexkeys.add(pval); String state = Struct.objectToString(this.request.getInterface().get(indexkeys.toArray())); if (! "Present".equals(state)) { needbase = true; } } } if (needbase) { this.indexFile(vault, path, now, RecordStruct.record() .with("Source", "Scan") .with("Op", "Write") .with("TimeStamp", now) // TODO prefer file mod .with("Node", ApplicationHub.getNodeId()) ); } else { this.indexFolderEnsure(vault, path.getParent()); } } catch (DatabaseException x) { Logger.error("Unable to ensure index file " + path + " in db: " + x); } } public void indexFolderEnsure(Vault vault, CommonPath path) throws OperatingContextException { if (path.isRoot()) return; try { // set public marker List indexkeys = FileIndexAdapter.pathToIndex(vault, path); ZonedDateTime now = TimeUtil.now(); Object fmarker = this.request.getInterface().get(indexkeys.toArray()); //boolean isfile = Struct.objectToBooleanOrFalse(fmarker) || "File".equals(Struct.objectToString(fmarker)); if (fmarker == null) { // check for implied folder indexkeys.add(null); byte[] pkey = this.request.getInterface().nextPeerKey(indexkeys.toArray()); // if none implied then force if (pkey == null) { indexkeys.remove(indexkeys.size() - 1); indexkeys.add("Folder"); this.request.getInterface().set(indexkeys.toArray()); } } else if ("XFolder".equals(Struct.objectToString(fmarker))) { indexkeys.add("Folder"); this.request.getInterface().set(indexkeys.toArray()); } this.indexFolderEnsure(vault, path.getParent()); } catch (DatabaseException x) { Logger.error("Unable to ensure index folder " + path + " in db: " + x); } } public void indexSearch(Vault vault, CommonPath path, DocumentIndexBuilder indexer) throws OperatingContextException { /* System.out.println("ib title: " + indexer.getTitle()); System.out.println("summ: " + indexer.getSummary()); System.out.println("hint: " + indexer.getSortHint()); System.out.println("deny: " + indexer.isDenyIndex()); System.out.println("badges: " + indexer.getBadges()); for (StringBuilder sb : indexer.getSections()) { System.out.println(); System.out.println(sb); } // TODO System.out.println(" ----- "); */ try { this.indexFileEnsure(vault, path); // set public marker List indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add("Public"); indexkeys.add(! indexer.isDenyIndex()); this.request.getInterface().set(indexkeys.toArray()); CharSequence title = indexer.getTitle(); // set title if (StringUtil.isNotEmpty(title)) { indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add(indexer.getLang()); indexkeys.add("Title"); indexkeys.add(title); this.request.getInterface().set(indexkeys.toArray()); } CharSequence summary = indexer.getSummary(); // set summary if (StringUtil.isNotEmpty(summary)) { indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add(indexer.getLang()); indexkeys.add("Summary"); indexkeys.add(summary); this.request.getInterface().set(indexkeys.toArray()); } CharSequence hint = indexer.getSortHint(); // set hint if (StringUtil.isNotEmpty(hint)) { indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add(indexer.getLang()); indexkeys.add("SortHint"); indexkeys.add(hint); this.request.getInterface().set(indexkeys.toArray()); } ListStruct badges = indexer.getBadges(); // set badges if (badges != null) { indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add("Badges"); indexkeys.add(badges); this.request.getInterface().set(indexkeys.toArray()); } List index = indexer.getIndex(); // set search if ((index != null) && (index.size() > 0)) { indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add(indexer.getLang()); indexkeys.add("Search"); indexkeys.add(LocaleUtil.toSearch(index)); this.request.getInterface().set(indexkeys.toArray()); } } catch (DatabaseException x) { Logger.error("Unable to search index file " + path + " in db: " + x); } } public void deleteFile(Vault vault, CommonPath path, ZonedDateTime time, RecordStruct history) { try { List indexkeys = FileIndexAdapter.pathToIndex(vault, path); Object fmarker = this.request.getInterface().get(indexkeys.toArray()); boolean isfile = Struct.objectToBooleanOrFalse(fmarker) || "File".equals(Struct.objectToString(fmarker)); if (isfile) { // state indexkeys.add("State"); indexkeys.add((time != null) ? ByteUtil.dateTimeToReverse(time) : BigDecimal.ZERO); indexkeys.add("Deleted"); this.request.getInterface().set(indexkeys.toArray()); // history indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add("History"); indexkeys.add((time != null) ? ByteUtil.dateTimeToReverse(time) : BigDecimal.ZERO); indexkeys.add(history); this.request.getInterface().set(indexkeys.toArray()); } else if ("Folder".equals(Struct.objectToString(fmarker))) { indexkeys.add("XFolder"); this.request.getInterface().set(indexkeys.toArray()); } else if (fmarker == null) { // check if this is an implied folder indexkeys.add(null); byte[] pkey = this.request.getInterface().nextPeerKey(indexkeys.toArray()); if (pkey != null) { indexkeys.remove(indexkeys.size() - 1); indexkeys.add("XFolder"); this.request.getInterface().set(indexkeys.toArray()); } /* // start at top indexkeys.add(null); byte[] pkey = this.request.getInterface().nextPeerKey(indexkeys.toArray()); while (pkey != null) { Object pval = ByteUtil.extractValue(pkey); if (pval instanceof String) { this.deleteFile(vault, path.resolve((String) pval), time, history); } indexkeys.remove(indexkeys.size() - 1); indexkeys.add(pval); pkey = this.request.getInterface().nextPeerKey(indexkeys.toArray()); } */ } } catch (DatabaseException x) { Logger.error("Unable to delete index file " + path + " in db: " + x); } } public void hideFolder(Vault vault, CommonPath path, ZonedDateTime time, RecordStruct history) { try { List indexkeys = FileIndexAdapter.pathToIndex(vault, path); indexkeys.add("XFolder"); this.request.getInterface().set(indexkeys.toArray()); } catch (DatabaseException x) { Logger.error("Unable to delete index file " + path + " in db: " + x); } } } src/main/java/org/springTest/Service/InfomationService.java package org.springTest.Service; import org.springTest.Dto.*; import org.springTest.Entity.*; import org.springTest.Service.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @Component public interface InfomationService { //public TestResultDto execute(Infomation entity); Page findAll(Pageable pageable); ListgetAllEntity(); } efluid-datagate-app/src/main/java/fr/uem/efluid/services/types/DiffSummaryForOneTable.java package fr.uem.efluid.services.types; import fr.uem.efluid.model.entities.IndexAction; import java.util.Collection; /** * Details from a diff for a specified table, with count of identified changes. * For display in diff, merge, revert and details screens * * @author elecomte * @version 1 * @since v3.1.17 */ public class DiffSummaryForOneTable extends DiffSummary { private final DictionaryEntrySummary dict; private DiffSummaryForOneTable( DictionaryEntrySummary dict, IndexAction.IndexActionCount counts) { super(); this.dict = dict; setCounts(counts); } public int getTotal() { return this.getCounts().total(); } public DictionaryEntrySummary getDict() { return this.dict; } public static DiffSummaryForOneTable forCount(DictionaryEntrySummary dict, IndexAction.IndexActionCount count) { return new DiffSummaryForOneTable(dict, count); } } xml/src/java/org/apache/hivemind/impl/XmlImplMessages.java // Copyright 2004, 2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.hivemind.impl; import org.apache.hivemind.ClassResolver; import org.apache.hivemind.Element; import org.apache.hivemind.HiveMind; import org.apache.hivemind.Location; import org.apache.hivemind.Resource; import org.apache.hivemind.definition.Occurances; import org.apache.hivemind.schema.SchemaProcessor; /** * Used to format messages used in errors and log output for classes within the impl package. * * @author */ class XmlImplMessages { private static final MessageFormatter _formatter = new MessageFormatter(XmlImplMessages.class, "XmlImplStrings"); static String unableToResolveSchema(String schemaId) { return _formatter.format("unable-to-resolve-schema", schemaId); } static String schemaNotVisible(String schemaId, String moduleId) { return _formatter.format("schema-not-visible", schemaId, moduleId); } static String wrongNumberOfParameters(String factoryServiceId, int actualCount, Occurances expectation) { return _formatter.format( "wrong-number-of-parameters", factoryServiceId, contributionCount(actualCount), occurances(expectation)); } static String occurances(Occurances occurances) { return _formatter.getMessage("occurances." + occurances.getName()); } static String contributionCount(int count) { return _formatter.format("contribution-count", new Integer(count)); } static String uniqueAttributeConstraintBroken(String name, String value, Location priorLocation) { return _formatter.format("unique-attribute-constraint-broken", name, value, priorLocation); } static String unknownAttribute(String name) { return _formatter.format("unknown-attribute", name); } static String schemaStackViolation(SchemaProcessor processor) { return _formatter.format("schema-stack-violation", processor.getElementPath()); } static String missingAttribute(String name) { return _formatter.format("missing-attribute", name); } static String elementErrors(SchemaProcessor processor, Element element) { return _formatter.format("element-errors", processor.getElementPath(), element .getLocation()); } static String unknownElement(SchemaProcessor processor, Element element) { return _formatter.format("unknown-element", processor.getElementPath()); } static String translatorInstantiationFailure(Class translatorClass, Throwable cause) { return _formatter.format( "translator-instantiation-failure", translatorClass.getName(), cause); } static String unknownTranslatorName(String name, String configurationId) { return _formatter.format("unknown-translator-name", name, configurationId); } static String duplicateTranslatorName(String name, Location oldLocation) { return _formatter.format("duplicate-translator-name", name, HiveMind .getLocationString(oldLocation)); } static String incompleteTranslator(TranslatorContribution c) { return _formatter.format("incomplete-translator", c.getName()); } static String subModuleDoesNotExist(Resource subModuleDescriptor) { return _formatter.format("sub-module-does-not-exist", subModuleDescriptor); } static String unableToFindModulesError(ClassResolver resolver, Throwable cause) { return _formatter.format("unable-to-find-modules", resolver, cause); } static String unableToFindModuleResource(Resource resource) { return _formatter.format("unable-to-find-module-resource", resource); } static String noSuchSymbol(String name) { return _formatter.format("no-such-symbol", name); } static String symbolSourceContribution() { return _formatter.getMessage("symbol-source-contribution"); } static String unknownConfigurationPointOfSchemaAssignment(String configurationId, SchemaAssignment schemaAssignment) { return _formatter.format("unknown-configurationpoint-in-schema-assignment", configurationId, schemaAssignment.getLocation()); } }/* * 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.jclouds.rackspace.autoscale.v1.domain; import static com.google.common.base.Preconditions.checkNotNull; import java.beans.ConstructorProperties; import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects.ToStringHelper; import com.google.common.base.Objects; /** * Autoscale Personality. Part of the launch configuration. * * @see LaunchConfiguration#getPersonalities() */ public class Personality { private final String path; private final String contents; @ConstructorProperties({ "path", "contents" }) protected Personality(String path, String contents) { this.path = checkNotNull(path, "path should not be null"); this.contents = checkNotNull(contents, "contents should not be null"); } /** * @return the path of this Personality. * @see Personality.Builder#path(String) */ public String getPath() { return this.path; } /** * @return the contents for this Personality. * @see Personality.Builder#contents(String) */ public String getContents() { return this.contents; } @Override public int hashCode() { return Objects.hashCode(path, contents); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Personality that = Personality.class.cast(obj); return Objects.equal(this.path, that.path) && Objects.equal(this.contents, that.contents); } protected ToStringHelper string() { return MoreObjects.toStringHelper(this).add("path", path).add("contents", contents); } @Override public String toString() { return string().toString(); } public static Builder builder() { return new Builder(); } public Builder toBuilder() { return new Builder().fromPersonality(this); } public static class Builder { protected String path; protected String contents; /** * @param path The path of this Personality. * @return The builder object. * @see Personality#getPath() */ public Builder path(String path) { this.path = path; return this; } /** * @param contents The contents of this Personality. * @return The builder object. * @see Personality#getContents() */ public Builder contents(String contents) { this.contents = contents; return this; } /** * @return A new Personality object. */ public Personality build() { return new Personality(path, contents); } public Builder fromPersonality(Personality in) { return this.path(in.getPath()).contents(in.getContents()); } } } package de.tum.in.ase.parser.exception; public class UnsupportedToolException extends RuntimeException { public UnsupportedToolException(String message) { super(message); } } src/edu/washington/escience/myria/api/encoding/AbstractProducerEncoding.java package edu.washington.escience.myria.api.encoding; import java.util.List; import java.util.Set; import edu.washington.escience.myria.operator.network.Producer; import edu.washington.escience.myria.parallel.ExchangePairID; public abstract class AbstractProducerEncoding

extends UnaryOperatorEncoding

implements ExchangeEncoding { private Set realWorkerIds; private List realOperatorIds; @Override public final Set getRealWorkerIds() { return realWorkerIds; } @Override public final void setRealWorkerIds(Set w) { realWorkerIds = w; } @Override public final List getRealOperatorIds() { return realOperatorIds; } @Override public final void setRealOperatorIds(List operatorIds) { realOperatorIds = operatorIds; } }sabot/kernel/src/test/java/com/dremio/exec/planner/physical/visitor/TestSplitCountChecker.java /* * Copyright (C) 2017-2019 Dremio 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. */ package com.dremio.exec.planner.physical.visitor; import static java.util.Arrays.asList; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.List; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.plan.volcano.VolcanoPlanner; import org.apache.calcite.rel.core.JoinRelType; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.rex.RexNode; import org.apache.calcite.sql.type.SqlTypeName; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; import com.dremio.common.expression.SchemaPath; import com.dremio.exec.ExecConstants; import com.dremio.exec.catalog.StoragePluginId; import com.dremio.exec.planner.physical.HashJoinPrel; import com.dremio.exec.planner.physical.PlannerSettings; import com.dremio.exec.planner.physical.Prel; import com.dremio.exec.planner.physical.ScreenPrel; import com.dremio.exec.planner.types.JavaTypeFactoryImpl; import com.dremio.exec.proto.UserBitShared; import com.dremio.exec.store.TableMetadata; import com.dremio.exec.store.sys.SystemPluginConf; import com.dremio.exec.store.sys.SystemScanPrel; import com.dremio.exec.store.sys.SystemTable; import com.dremio.options.OptionList; import com.dremio.options.OptionManager; import com.dremio.options.OptionValidatorListing; import com.dremio.resource.ClusterResourceInformation; import com.dremio.sabot.op.join.JoinUtils; import com.dremio.service.namespace.NamespaceKey; import com.dremio.service.namespace.capabilities.SourceCapabilities; import com.dremio.service.namespace.source.proto.SourceConfig; import com.dremio.test.DremioTest; import com.dremio.test.UserExceptionMatcher; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; /** * Unit test for SplitCountChecker */ public class TestSplitCountChecker { private static final RelTraitSet traits = RelTraitSet.createEmpty().plus(Prel.PHYSICAL); private static final RelDataTypeFactory typeFactory = JavaTypeFactoryImpl.INSTANCE; private static final RexBuilder rexBuilder = new RexBuilder(typeFactory); private RelOptCluster cluster; @Rule public final ExpectedException thrownException = ExpectedException.none(); @Before public void setup() throws Exception { OptionList optionList = new OptionList(); optionList.add(ExecConstants.SLICE_TARGET_OPTION.getDefault()); optionList.add(PlannerSettings.ENABLE_LEAF_LIMITS.getDefault()); optionList.add(PlannerSettings.ENABLE_TRIVIAL_SINGULAR.getDefault()); final OptionManager optionManager = mock(OptionManager.class); when(optionManager.getOptionValidatorListing()).thenReturn(mock(OptionValidatorListing.class)); when(optionManager.getOption(eq(PlannerSettings.FULL_NESTED_SCHEMA_SUPPORT.getOptionName()))) .thenReturn(PlannerSettings.FULL_NESTED_SCHEMA_SUPPORT.getDefault()); when(optionManager.getNonDefaultOptions()).thenReturn(optionList); ClusterResourceInformation info = mock(ClusterResourceInformation.class); when(info.getExecutorNodeCount()).thenReturn(1); final PlannerSettings plannerSettings = new PlannerSettings(DremioTest.DEFAULT_SABOT_CONFIG, optionManager, () -> info); cluster = RelOptCluster.create(new VolcanoPlanner(plannerSettings), rexBuilder); } private void verifySplits(Prel root, int querySplitLimit, int datasetSplitLimit, boolean expectedResult) { if (!expectedResult) { // Expect an exception thrownException.expect(new UserExceptionMatcher(UserBitShared.DremioPBError.ErrorType.UNSUPPORTED_OPERATION, "Number of splits")); } SplitCountChecker.checkNumSplits(root, querySplitLimit, datasetSplitLimit); assertTrue("Expected verification failure. Instead, verification succeeded", expectedResult); } // Single scan, large limit. Expect success @Test public void simpleScan() throws Exception { Prel input = newScreen( newScan(rowType(), 500, 5) ); verifySplits(input, 100, 100, true); } // Single scan, small dataset limit. Expect failure @Test public void singleScanDatasetLimit() throws Exception { Prel input = newScreen( newScan(rowType(), 500, 5) ); verifySplits(input, 100, 3, false); } // Single scan, small query limit. Expect failure @Test public void singleScanQueryLimit() throws Exception { Prel input = newScreen( newScan(rowType(), 500, 5) ); verifySplits(input, 3, 100, false); } // Two scans, large limit. Expect success @Test public void twoTablesLargeLimit() throws Exception { Prel input = newScreen( newJoin( newScan(rowType(), 500, 5), newScan(rowType(), 700, 10), rexBuilder.makeLiteral(true) ) ); verifySplits(input, 100, 100, true); } // Two scans, small query limit. Each dataset can squeeze through the dataset limit. Query can // squeeze through the query limit (but not the dataset limit). Expect success @Test public void twoTablesSmallLimit() throws Exception { Prel input = newScreen( newJoin( newScan(rowType(), 500, 10), newScan(rowType(), 700, 10), rexBuilder.makeLiteral(true) ) ); verifySplits(input, 25, 15, true); } // Two scans, small query limit. Expect failure @Test public void twoTablesQueryLimit() throws Exception { Prel input = newScreen( newJoin( newScan(rowType(), 500, 10), newScan(rowType(), 700, 10), rexBuilder.makeLiteral(true) ) ); verifySplits(input, 15, 15, false); } // Two scans, small dataset limit. Expect failure @Test public void twoTablesDatasetLimit() throws Exception { Prel input = newScreen( newJoin( newScan(rowType(), 500, 3), newScan(rowType(), 700, 10), rexBuilder.makeLiteral(true) ) ); verifySplits(input, 20, 5, false); } private Prel newScreen(Prel child) { return new ScreenPrel(cluster, traits, child); } private Prel newJoin(Prel left, Prel right, RexNode joinExpr) { return HashJoinPrel.create(cluster, traits, left, right, joinExpr, JoinRelType.INNER, JoinUtils.projectAll(left.getRowType().getFieldCount()+right.getRowType().getFieldCount())); } private Prel newScan(RelDataType rowType, double rowCount, int splitCount) throws Exception { TableMetadata metadata = Mockito.mock(TableMetadata.class); when(metadata.getName()).thenReturn(new NamespaceKey(ImmutableList.of("sys", "version"))); when(metadata.getSchema()).thenReturn(SystemTable.VERSION.getRecordSchema()); when(metadata.getSplitRatio()).thenReturn(0.75); when(metadata.getSplitCount()).thenReturn(splitCount); StoragePluginId pluginId = new StoragePluginId(new SourceConfig().setConfig(new SystemPluginConf().toBytesString()), new SystemPluginConf(), SourceCapabilities.NONE); when(metadata.getStoragePluginId()).thenReturn(pluginId); List columns = FluentIterable.from(SystemTable.VERSION.getRecordSchema()).transform(input -> SchemaPath.getSimplePath(input.getName())).toList(); final RelOptTable relOptTable = Mockito.mock(RelOptTable.class); when(relOptTable.getRowCount()).thenReturn(rowCount); when(relOptTable.getQualifiedName()).thenReturn(ImmutableList.of("sys", "version")); return new SystemScanPrel(cluster, traits, relOptTable, metadata, columns, 1.0d, rowType); } private RelDataType rowType() { return typeFactory.createStructType( asList(typeFactory.createSqlType(SqlTypeName.INTEGER), typeFactory.createSqlType(SqlTypeName.DOUBLE)), asList("intCol", "doubleCol") ); } } siko1056/searchbooster package de.mround.searchbooster.api.xml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.List; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import de.mround.searchbooster.api.xml.RequestSearchBuilder.Content; import de.mround.searchbooster.api.xml.SearchBoosterXML.StatusCodeID; public class RequestSearchParserTest { private static XMLGregorianCalendar modificationdatebegin1 = null; private static XMLGregorianCalendar modificationdatebegin2 = null; private static XMLGregorianCalendar modificationdateend1 = null; private static XMLGregorianCalendar modificationdateend2 = null; private static Content contentDocument = null; private static Content contentMusic = null; private static Content contentPicture = null; private static Content contentVideo = null; private static Document simpleSearchRequest = null; private static Document advancedSearchRequest = null; private static Document abortRequest = null; private static Document indexChangeRequest = null; private static Document indexInfoRequest = null; private static Document metaSearchResultResponse = null; private static Document indexContentResponse = null; @BeforeClass public static void setUpBeforeClass() throws Exception { try { modificationdatebegin1 = DatatypeFactory.newInstance() .newXMLGregorianCalendar("2001-01-01T01:01:01"); modificationdatebegin2 = DatatypeFactory.newInstance() .newXMLGregorianCalendar("2002-02-02T02:02:02"); modificationdateend1 = DatatypeFactory.newInstance() .newXMLGregorianCalendar("2010-10-10T10:10:10"); modificationdateend2 = DatatypeFactory.newInstance() .newXMLGregorianCalendar("2020-12-20T20:20:20"); } catch (DatatypeConfigurationException e) { System.err.println(e.getMessage()); } contentDocument = RequestSearchBuilder.Content .newDocumentContent("Doc Test"); contentMusic = RequestSearchBuilder.Content.newMusicContent( "Metallica", "Master of Puppets"); contentPicture = RequestSearchBuilder.Content.newPictureContent(); contentVideo = RequestSearchBuilder.Content.newVideoContent(); simpleSearchRequest = RequestSearchBuilder.create(); advancedSearchRequest = RequestSearchBuilder.create(); RequestSearchBuilder.appendPath(advancedSearchRequest, "/test/url/2", -1); RequestSearchBuilder.appendParameter(advancedSearchRequest, "*", modificationdatebegin1, modificationdateend1, contentDocument); RequestSearchBuilder.appendPath(advancedSearchRequest, "/test/url/3", -1); // should not be visible RequestSearchBuilder.appendParameter(advancedSearchRequest, null, null, null, null); RequestSearchBuilder.appendParameter(advancedSearchRequest, "BlaBla", modificationdatebegin2, modificationdateend2, contentMusic); RequestSearchBuilder.appendParameter(advancedSearchRequest, "*", null, null, null); RequestSearchBuilder.appendParameter(advancedSearchRequest, null, null, null, contentVideo); RequestSearchBuilder.appendParameter(advancedSearchRequest, null, null, null, contentPicture); abortRequest = RequestAbortBuilder.create("Test"); indexChangeRequest = RequestIndexChangeBuilder.create(true); indexInfoRequest = RequestIndexInfoBuilder.create("Test"); metaSearchResultResponse = ResponseSearchBuilder.create( StatusCodeID.SUCCESSFUL, "Test"); indexContentResponse = ResponseIndexContentBuilder.create( StatusCodeID.SUCCESSFUL, "Test"); } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testIsSearchRequest() { assertTrue(RequestSearchParser.isSearchRequest(simpleSearchRequest)); assertTrue(RequestSearchParser.isSearchRequest(advancedSearchRequest)); assertFalse(RequestSearchParser.isSearchRequest(abortRequest)); assertFalse(RequestSearchParser.isSearchRequest(indexChangeRequest)); assertFalse(RequestSearchParser.isSearchRequest(indexInfoRequest)); assertFalse(RequestSearchParser .isSearchRequest(metaSearchResultResponse)); assertFalse(RequestSearchParser.isSearchRequest(indexContentResponse)); } @Test public void testGetPathList() { assertEquals(0, RequestSearchParser.getPathList(simpleSearchRequest) .size()); assertEquals(2, RequestSearchParser.getPathList(advancedSearchRequest) .size()); } @Test public void testGetPathURL() { List nodeList = RequestSearchParser .getPathList(advancedSearchRequest); assertEquals("/test/url/3", RequestSearchParser.getPathURL(nodeList.get(1))); } @Test public void testGetPathRecursionDepth() { List nodeList = RequestSearchParser .getPathList(advancedSearchRequest); assertEquals(-1, RequestSearchParser.getPathRecursionDepth(nodeList.get(1))); } @Test public void testGetParameterList() { assertEquals(0, RequestSearchParser.getParameterList(simpleSearchRequest) .size()); assertEquals(5, RequestSearchParser.getParameterList(advancedSearchRequest) .size()); } @Test public void testHasParameterFileName() { List nodeList = RequestSearchParser .getParameterList(advancedSearchRequest); assertTrue(RequestSearchParser.hasParameterFileName(nodeList.get(0))); assertFalse(RequestSearchParser.hasParameterFileName(nodeList.get(3))); } @Test public void testHasParameterModificationDateBegin() { List nodeList = RequestSearchParser .getParameterList(advancedSearchRequest); assertTrue(RequestSearchParser .hasParameterModificationDateBegin(nodeList.get(0))); assertFalse(RequestSearchParser .hasParameterModificationDateBegin(nodeList.get(2))); } @Test public void testHasParameterModificationDateEnd() { List nodeList = RequestSearchParser .getParameterList(advancedSearchRequest); assertTrue(RequestSearchParser.hasParameterModificationDateEnd(nodeList .get(0))); assertFalse(RequestSearchParser .hasParameterModificationDateEnd(nodeList.get(2))); } @Test public void testHasParameterContentDocument() { List nodeList = RequestSearchParser .getParameterList(advancedSearchRequest); RequestSearchParser.hasParameterContentDocument(nodeList.get(0)); assertTrue(RequestSearchParser.hasParameterContentDocument(nodeList .get(0))); assertFalse(RequestSearchParser.hasParameterContentDocument(nodeList .get(1))); } } 1-10 package org.eddy; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.system.ApplicationPidFileWriter; @SpringBootApplication public class TaskApplicationStart { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(TaskApplicationStart.class); springApplication.addListeners(new ApplicationPidFileWriter("task.pid")); springApplication.run(args); } }package com.example.picoclient.testclient; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; // Might change this to a fragment in the future public class LogActivity extends Activity { SharedPreferences prefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log); prefs = PreferenceManager.getDefaultSharedPreferences(this); } @Override protected void onResume() { super.onResume(); Log.i("Log", "onResume"); try { StringBuilder log=new StringBuilder(); String line = ""; Map allPref = prefs.getAll(); for (Map.Entry e :allPref.entrySet()){ log.append(e.getKey()); log.append(": "); log.append(e.getValue().toString()); log.append("\n"); } TextView tv = (TextView)findViewById(R.id.textView1); tv.setText(log.toString()); } catch (Exception e) { Log.e("Log",e.getLocalizedMessage()); e.printStackTrace(); } } } src/main/java/net/imglib2/python/ArrayImgWithUnsafeStoreFactory.java0 /*- * #%L * Utility and helper methods to facilitate python imglib2 interaction with shared memory. * %% * Copyright (C) 2017 - 2021 Medical Institute. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. * #L% */ package net.imglib2.python; import net.imglib2.exception.IncompatibleTypeException; import net.imglib2.img.Img; import net.imglib2.img.ImgFactory; import net.imglib2.img.array.ArrayImg; import net.imglib2.img.basictypelongaccess.unsafe.owning.OwningByteUnsafe; import net.imglib2.img.basictypelongaccess.unsafe.owning.OwningDoubleUnsafe; import net.imglib2.img.basictypelongaccess.unsafe.owning.OwningFloatUnsafe; import net.imglib2.img.basictypelongaccess.unsafe.owning.OwningIntUnsafe; import net.imglib2.img.basictypelongaccess.unsafe.owning.OwningLongUnsafe; import net.imglib2.img.basictypelongaccess.unsafe.owning.OwningShortUnsafe; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.ARGBType; import net.imglib2.type.numeric.complex.ComplexDoubleType; import net.imglib2.type.numeric.complex.ComplexFloatType; import net.imglib2.type.numeric.integer.ByteType; import net.imglib2.type.numeric.integer.IntType; import net.imglib2.type.numeric.integer.LongType; import net.imglib2.type.numeric.integer.ShortType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.type.numeric.integer.UnsignedIntType; import net.imglib2.type.numeric.integer.UnsignedLongType; import net.imglib2.type.numeric.integer.UnsignedShortType; import net.imglib2.type.numeric.real.DoubleType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.util.Fraction; import net.imglib2.util.Intervals; public class ArrayImgWithUnsafeStoreFactory< T extends NativeType< T > > extends ImgFactory< T > { @Deprecated public ArrayImgWithUnsafeStoreFactory() { this( null ); } public ArrayImgWithUnsafeStoreFactory( final T t ) { super( t ); } @SuppressWarnings( "unchecked" ) @Override public Img< T > create( final long[] dim, final T type ) { final long numEntities = Intervals.numElements( dim ); if ( type instanceof ARGBType ) { final ArrayImg< ARGBType, OwningIntUnsafe > img = new ArrayImg<>( new OwningIntUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new ARGBType( img ) ); return ( Img< T > ) img; } if ( type instanceof ComplexDoubleType ) { final ArrayImg< ComplexDoubleType, OwningDoubleUnsafe > img = new ArrayImg<>( new OwningDoubleUnsafe( numEntities ), dim, new Fraction( 2, 1 ) ); img.setLinkedType( new ComplexDoubleType( img ) ); return ( Img< T > ) img; } if ( type instanceof ComplexFloatType ) { final ArrayImg< ComplexFloatType, OwningFloatUnsafe > img = new ArrayImg<>( new OwningFloatUnsafe( numEntities ), dim, new Fraction( 2, 1 ) ); img.setLinkedType( new ComplexFloatType( img ) ); return ( Img< T > ) img; } if ( type instanceof DoubleType ) { final ArrayImg< DoubleType, OwningDoubleUnsafe > img = new ArrayImg<>( new OwningDoubleUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new DoubleType( img ) ); return ( Img< T > ) img; } if ( type instanceof FloatType ) { final ArrayImg< FloatType, OwningFloatUnsafe > img = new ArrayImg<>( new OwningFloatUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new FloatType( img ) ); return ( Img< T > ) img; } if ( type instanceof ByteType ) { final ArrayImg< ByteType, OwningByteUnsafe > img = new ArrayImg<>( new OwningByteUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new ByteType( img ) ); return ( Img< T > ) img; } if ( type instanceof UnsignedByteType ) { final ArrayImg< UnsignedByteType, OwningByteUnsafe > img = new ArrayImg<>( new OwningByteUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new UnsignedByteType( img ) ); return ( Img< T > ) img; } if ( type instanceof IntType ) { final ArrayImg< IntType, OwningIntUnsafe > img = new ArrayImg<>( new OwningIntUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new IntType( img ) ); return ( Img< T > ) img; } if ( type instanceof UnsignedIntType ) { final ArrayImg< UnsignedIntType, OwningIntUnsafe > img = new ArrayImg<>( new OwningIntUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new UnsignedIntType( img ) ); return ( Img< T > ) img; } if ( type instanceof LongType ) { final ArrayImg< LongType, OwningLongUnsafe > img = new ArrayImg<>( new OwningLongUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new LongType( img ) ); return ( Img< T > ) img; } if ( type instanceof UnsignedLongType ) { final ArrayImg< UnsignedLongType, OwningLongUnsafe > img = new ArrayImg<>( new OwningLongUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new UnsignedLongType( img ) ); return ( Img< T > ) img; } if ( type instanceof ShortType ) { final ArrayImg< ShortType, OwningShortUnsafe > img = new ArrayImg<>( new OwningShortUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new ShortType( img ) ); return ( Img< T > ) img; } if ( type instanceof UnsignedShortType ) { final ArrayImg< UnsignedShortType, OwningShortUnsafe > img = new ArrayImg<>( new OwningShortUnsafe( numEntities ), dim, new Fraction() ); img.setLinkedType( new UnsignedShortType( img ) ); return ( Img< T > ) img; } return null; } @SuppressWarnings( { "rawtypes", "unchecked" } ) @Override public < S > ImgFactory< S > imgFactory( final S type ) throws IncompatibleTypeException { if ( type instanceof NativeType ) { return new ArrayImgWithUnsafeStoreFactory( ( NativeType< ? > ) type ); } throw new IncompatibleTypeException( type, "Does not implement NativeType!" ); } @Override public Img< T > create( final long... dimensions ) { return create( dimensions, type() ); } } package com.odde.doughnut.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") class HealthCheckController { @Autowired private Environment environment; @GetMapping("/healthcheck") public String ping() { return "OK. Active Profile: " + String.join(", ", environment.getActiveProfiles()); } } 1000+ /* * Copyright (c) 2008-2016 Haulmont. * * 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.haulmont.cuba.security; import com.haulmont.cuba.core.EntityManager; import com.haulmont.cuba.core.Transaction; import com.haulmont.cuba.core.global.AppBeans; import com.haulmont.cuba.core.global.PasswordEncryption; import com.haulmont.cuba.core.global.UserSessionSource; import com.haulmont.cuba.security.auth.AuthenticationManager; import com.haulmont.cuba.security.auth.Credentials; import com.haulmont.cuba.security.auth.LoginPasswordCredentials; import com.haulmont.cuba.security.entity.Group; import com.haulmont.cuba.security.entity.User; import com.haulmont.cuba.security.entity.UserSubstitution; import com.haulmont.cuba.security.global.UserSession; import com.haulmont.cuba.testsupport.TestContainer; import com.haulmont.cuba.testsupport.TestUserSessionSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.Test; import java.util.Locale; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; public class LoginTest { @RegisterExtension public static TestContainer cont = TestContainer.Common.INSTANCE; private AuthenticationManager authenticationManager; private UUID user1Id; private UUID user2Id; private UUID substitutionId; private TestUserSessionSource userSessionSource; private UserSession standardTestUserSession; @BeforeEach public void setUp() throws Exception { PasswordEncryption passwordEncryption = AppBeans.get(PasswordEncryption.NAME); authenticationManager = AppBeans.get(AuthenticationManager.NAME); userSessionSource = AppBeans.get(UserSessionSource.NAME); standardTestUserSession = userSessionSource.getUserSession(); Transaction tx = cont.persistence().createTransaction(); try { EntityManager em = cont.persistence().getEntityManager(); Group group = em.getReference(Group.class, UUID.fromString("0fa2b1a5-1d68-4d69-9fbd-dff348347f93")); User user1 = new User(); user1Id = user1.getId(); user1.setGroup(group); user1.setLogin("user1"); user1.setPassword(passwordEncryption.getPasswordHash(user1.getId(), "1")); em.persist(user1); User user2 = new User(); user2Id = user2.getId(); user2.setGroup(group); user2.setLogin("user2"); user2.setPassword(passwordEncryption.getPasswordHash(user2.getId(), "2")); em.persist(user2); tx.commit(); } finally { tx.end(); } } @AfterEach public void tearDown() throws Exception { cont.deleteRecord("SEC_USER_SUBSTITUTION", substitutionId); cont.deleteRecord("SEC_USER", user1Id); cont.deleteRecord("SEC_USER", user2Id); userSessionSource.setUserSession(standardTestUserSession); } private User loadUser(final UUID userId) { return cont.persistence().createTransaction().execute(new Transaction.Callable() { @Override public User call(EntityManager em) { return em.find(User.class, userId); } }); } @Test public void testUserSubstitution() throws Exception { // Log in Credentials credentials = new LoginPasswordCredentials("", "1", Locale.ENGLISH); UserSession session1 = authenticationManager.login(credentials).getSession(); userSessionSource.setUserSession(session1); // Substitute a user that is not in our substitutions list - fail User user2 = loadUser(user2Id); try { authenticationManager.substituteUser(user2); fail(); } catch (Exception e) { // ok } // Create a substitution cont.persistence().createTransaction().execute(new Transaction.Runnable() { @Override public void run(EntityManager em) { UserSubstitution substitution = new UserSubstitution(); substitutionId = substitution.getId(); substitution.setUser(em.getReference(User.class, user1Id)); substitution.setSubstitutedUser(em.getReference(User.class, user2Id)); em.persist(substitution); } }); // Try again - succeed UserSession session2 = authenticationManager.substituteUser(user2); userSessionSource.setUserSession(session2); assertEquals(session1.getId(), session2.getId()); assertEquals(user1Id, session2.getUser().getId()); assertEquals(user2Id, session2.getSubstitutedUser().getId()); // Switch back to the logged in user User user1 = loadUser(user1Id); UserSession session3 = authenticationManager.substituteUser(user1); assertEquals(session1.getId(), session3.getId()); assertEquals(user1Id, session3.getUser().getId()); assertNull(session3.getSubstitutedUser()); } @Test public void testUserSubstitutionSoftDelete() { // Create a substitution cont.persistence().createTransaction().execute(em -> { UserSubstitution substitution = new UserSubstitution(); substitutionId = substitution.getId(); substitution.setUser(em.getReference(User.class, user1Id)); substitution.setSubstitutedUser(em.getReference(User.class, user2Id)); em.persist(substitution); }); // Soft delete it cont.persistence().createTransaction().execute(em -> { UserSubstitution substitution = em.getReference(UserSubstitution.class, substitutionId); em.remove(substitution); }); // Log in Credentials credentials = new LoginPasswordCredentials("user1", "1", Locale.ENGLISH); UserSession session1 = authenticationManager.login(credentials).getSession(); userSessionSource.setUserSession(session1); // Try to substitute - fail User user2 = loadUser(user2Id); try { authenticationManager.substituteUser(user2); fail(); } catch (Exception e) { // ok } } }10-100 /** * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * This file is part of the LDP4j Project: * http://www.ldp4j.org/ * * Center for Open Middleware * http://www.centeropenmiddleware.com/ * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Copyright (C) 2014-2016 Center for Open Middleware. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * 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. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Artifact : org.ldp4j.framework:ldp4j-application-api:0.2.2 * Bundle : ldp4j-application-api-0.2.2.jar * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ package org.ldp4j.application.vocabulary; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import java.net.URI; import javax.xml.namespace.QName; import org.junit.Test; import org.ldp4j.commons.testing.Utils; public class RDFTest extends AbstractVocabularyTest { @Override protected RDF vocabulary() { return RDF.getInstance(); } @Override protected String namespace() { return RDF.NAMESPACE; } @Override protected String preferredPrefix() { return RDF.NS_PREFIX; } @Override protected URI unknownURITerm() { return URI.create("urn:unknown"); } @Override protected QName unknownQNameTerm() { return new QName("urn:","unknown","urn"); } @Test public void verifyIsUtilityClass() { assertThat(Utils.isUtilityClass(RDF.class),equalTo(true)); } } package yacx; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.junit.jupiter.api.Test; public class TestUtils { final String saxpy = "extern \"C\" __global__\n" + "void saxpy(float a, float *x, float *y, float *out, size_t n) {\n" + " size_t tid = blockIdx.x * blockDim.x + threadIdx.x;\n" + " if (tid < n) {\n" + " out[tid] = a * x[tid] + y[tid];\n" + " }\n" + "}\n" + ""; @Test void loadFile() throws IOException { assertEquals(saxpy, Utils.loadFile("kernels/saxpy.cu")); } } /* * The MIT License (MIT) * * Copyright © 2015 () * * 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. */ package com.motionizr.percenseo.commons; import com.google.common.base.MoreObjects; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * Enumerates all the possible Twilio call status. *

* Used to store the call status in the database in a more efficient manner. Strings are ugly. * * @author () * @version 1.0.0 */ public enum CallStatus { /** * All new calls are created with a status of queued, indicating Twilio has received your request to create the call. */ QUEUED ("queued", 0), /** * Twilio has dialed the call. */ INITIATED ("initiated", 1), /** * The destination number has started ringing. */ RINGING ("ringing", 2), /** * The call has been answered and is current in progress. */ IN_PROGRESS ("in-progress", 3), /** * The call was canceled using the REST API. */ CANCELED ("canceled", 4), /** * After an answered call ends it has a completed status. Since the call is over the Status will always remain in this state. */ COMPLETED ("completed", 5), /** * Twilio dialed the number and received a busy signal. */ BUSY ("busy", 6), /** * Twilio’s carriers could not connect the call, most likely because the phone number was entered incorrectly or was disconnected. */ FAILED ("failed", 7), /** * Twilio dialed the number but no one answered before the Timeout value elapsed. */ NO_ANSWER ("no-answer", 8), /** * Used whenever Twilio replies with an unknown state. */ UNKNOWN ("unknown", -1); /** * Map containing the {@link CallStatus call status} instances by its desc. */ private static final Map FROM_DESC = Arrays.stream(CallStatus.values()) .collect(Collectors.toMap(CallStatus::getDesc, Function.identity())); /** * Map containing the {@link CallStatus call status} instances by its internal code. */ private static final Map FROM_INTERNAL_CODE = Arrays.stream(CallStatus.values()) .collect(Collectors.toMap(CallStatus::getInternalCode, Function.identity())); /** * The status description used by the Twilio API. */ private String desc; /** * The internal code used to represent the instance in an efficient manner. */ private int internalCode; /** * Creates a new instance of {@link CallStatus}. * * @param desc The status description used by the Twilio API. * @param internalCode The internal code used to represent the instance in an efficient manner. */ private CallStatus(String desc, int internalCode) { this.desc = desc; this.internalCode = internalCode; } /** * Gets the status description used by the Twilio API. * * @return The status description used by the Twilio API. */ public String getDesc() { return desc; } /** * Gets the internal code used to represent the instance in an efficient manner. * * @return The internal code used to represent the instance in an efficient manner. */ public int getInternalCode() { return internalCode; } /** * Gets the {@link CallStatus call status} instance from its public desc. * * @param desc The public description of the {@link CallStatus call status}. * @return The {@link CallStatus call status} instance. */ public static CallStatus fromDesc(String desc) { return FROM_DESC.getOrDefault(desc, UNKNOWN); } /** * Gets the {@link CallStatus call status} instance from its internal code. * * @param internalCode The internal code of the {@link CallStatus call status}. * @return The {@link CallStatus call status} instance. */ @SuppressWarnings("UnusedDeclaration") public static CallStatus fromInternalCode(Integer internalCode) { return FROM_INTERNAL_CODE.getOrDefault(internalCode, UNKNOWN); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("desc", desc) .add("internalCode", internalCode) .toString(); } } package com.ebradshaw.insight.agent.events; public class ServletRequestErrorEvent extends InstrumentedEvent { public ServletRequestErrorEvent(long threadId) { super(threadId); } } src/main/java/todo/models/User.java package todo.models; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * * @author dagothar */ @Entity public class User implements Serializable { @Id @GeneratedValue @Column(name = "id", nullable = false, updatable = false) private Long id; @Column(name = "username", nullable = false, unique = true) private String username; @Column(name = "password_hash", nullable = false) private String passwordHash; @Enumerated(EnumType.STRING) private Role role; public User() { } public User(Long id, String login, String passwordHash, Role role) { this.id = id; this.username = login; this.passwordHash = passwordHash; this.role = role; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPasswordHash() { return passwordHash; } public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } @Override public String toString() { return String.format("%d %s %s", id, username, passwordHash); } } /** * 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.io.retry; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.retry.RetryPolicies.MultipleLinearRandomRetry; import org.apache.hadoop.ipc.RemoteException; import com.google.protobuf.ServiceException; import org.apache.hadoop.ipc.RetriableException; public class RetryUtils { public static final Log LOG = LogFactory.getLog(RetryUtils.class); /** * Return the default retry policy set in conf. * * If the value retryPolicyEnabledKey is set to false in conf, * use TRY_ONCE_THEN_FAIL. * * Otherwise, get the MultipleLinearRandomRetry policy specified in the conf * and then * (1) use multipleLinearRandomRetry for * - remoteExceptionToRetry, or * - IOException other than RemoteException, or * - ServiceException; and * (2) use TRY_ONCE_THEN_FAIL for * - non-remoteExceptionToRetry RemoteException, or * - non-IOException. * * * @param conf * @param retryPolicyEnabledKey conf property key for enabling retry * @param defaultRetryPolicyEnabled default retryPolicyEnabledKey conf value * @param retryPolicySpecKey conf property key for retry policy spec * @param defaultRetryPolicySpec default retryPolicySpecKey conf value * @param remoteExceptionToRetry The particular RemoteException to retry * @return the default retry policy. */ public static RetryPolicy getDefaultRetryPolicy( Configuration conf, String retryPolicyEnabledKey, boolean defaultRetryPolicyEnabled, String retryPolicySpecKey, String defaultRetryPolicySpec, final Class remoteExceptionToRetry) { final RetryPolicy multipleLinearRandomRetry = getMultipleLinearRandomRetry( conf, retryPolicyEnabledKey, defaultRetryPolicyEnabled, retryPolicySpecKey, defaultRetryPolicySpec ); if (LOG.isDebugEnabled()) { LOG.debug("multipleLinearRandomRetry = " + multipleLinearRandomRetry); } if (multipleLinearRandomRetry == null) { //no retry return RetryPolicies.TRY_ONCE_THEN_FAIL; } else { return new WrapperRetryPolicy( (MultipleLinearRandomRetry) multipleLinearRandomRetry, remoteExceptionToRetry); } } private static final class WrapperRetryPolicy implements RetryPolicy { private MultipleLinearRandomRetry multipleLinearRandomRetry; private final Class remoteExceptionToRetry; private WrapperRetryPolicy( final MultipleLinearRandomRetry multipleLinearRandomRetry, final Class remoteExceptionToRetry) { this.multipleLinearRandomRetry = multipleLinearRandomRetry; this.remoteExceptionToRetry = remoteExceptionToRetry; } @Override public RetryAction shouldRetry(Exception e, int retries, int failovers, boolean isMethodIdempotent) throws Exception { if (e instanceof ServiceException) { //unwrap ServiceException final Throwable cause = e.getCause(); if (cause != null && cause instanceof Exception) { e = (Exception)cause; } } //see (1) and (2) in the javadoc of this method. final RetryPolicy p; if (e instanceof RetriableException || RetryPolicies.getWrappedRetriableException(e) != null) { // RetriableException or RetriableException wrapped p = multipleLinearRandomRetry; } else if (e instanceof RemoteException) { final RemoteException re = (RemoteException)e; p = remoteExceptionToRetry != null && re.getClassName().equals(remoteExceptionToRetry.getName()) ? multipleLinearRandomRetry : RetryPolicies.TRY_ONCE_THEN_FAIL; } else if (e instanceof IOException || e instanceof ServiceException) { p = multipleLinearRandomRetry; } else { //non-IOException p = RetryPolicies.TRY_ONCE_THEN_FAIL; } if (LOG.isDebugEnabled()) { LOG.debug("RETRY " + retries + ") policy=" + p.getClass().getSimpleName() + ", exception=" + e); } return p.shouldRetry(e, retries, failovers, isMethodIdempotent); } /** * remoteExceptionToRetry is ignored as part of equals since it does not * affect connection failure handling. */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } else { return (obj instanceof WrapperRetryPolicy) && this.multipleLinearRandomRetry .equals(((WrapperRetryPolicy) obj).multipleLinearRandomRetry); } } /** * Similarly, remoteExceptionToRetry is ignored as part of hashCode since it * does not affect connection failure handling. */ @Override public int hashCode() { return multipleLinearRandomRetry.hashCode(); } @Override public String toString() { return "RetryPolicy[" + multipleLinearRandomRetry + ", " + RetryPolicies.TRY_ONCE_THEN_FAIL.getClass().getSimpleName() + "]"; } } /** * Return the MultipleLinearRandomRetry policy specified in the conf, * or null if the feature is disabled. * If the policy is specified in the conf but the policy cannot be parsed, * the default policy is returned. * * Retry policy spec: * N pairs of sleep-time and number-of-retries "s1,n1,s2,n2,..." * * @param conf * @param retryPolicyEnabledKey conf property key for enabling retry * @param defaultRetryPolicyEnabled default retryPolicyEnabledKey conf value * @param retryPolicySpecKey conf property key for retry policy spec * @param defaultRetryPolicySpec default retryPolicySpecKey conf value * @return the MultipleLinearRandomRetry policy specified in the conf, * or null if the feature is disabled. */ public static RetryPolicy getMultipleLinearRandomRetry( Configuration conf, String retryPolicyEnabledKey, boolean defaultRetryPolicyEnabled, String retryPolicySpecKey, String defaultRetryPolicySpec ) { final boolean enabled = conf.getBoolean(retryPolicyEnabledKey, defaultRetryPolicyEnabled); if (!enabled) { return null; } final String policy = conf.get(retryPolicySpecKey, defaultRetryPolicySpec); final RetryPolicy r = RetryPolicies.MultipleLinearRandomRetry.parseCommaSeparatedString( policy); return (r != null) ? r : RetryPolicies.MultipleLinearRandomRetry.parseCommaSeparatedString( defaultRetryPolicySpec); } } src/test/java/com/google/devtools/build/lib/skyframe/serialization/MutableListCodecTest.java // Copyright 2022 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skyframe.serialization; import com.google.devtools.build.lib.skyframe.serialization.testutils.SerializationTester; import net.starlark.java.eval.StarlarkList; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link MutableListCodec}. */ @RunWith(JUnit4.class) public class MutableListCodecTest { @Test public void testCodec() throws Exception { StarlarkList aliasedInnerList = StarlarkList.immutableOf("1", "2"); new SerializationTester( StarlarkList.empty(), StarlarkList.immutableOf("1", "2", StarlarkList.immutableOf("3", "4"), "5"), StarlarkList.immutableOf(aliasedInnerList, aliasedInnerList)) .makeMemoizing() // Note that verification uses an equals() test, which ensures not just correct order, but // also that we got back the right kind of value (list versus tuple). .runTests(); } } lib/common/src/main/java/dk/alexandra/fresco/lib/common/math/integer/division/SecretSharedDivisor.java package dk.alexandra.fresco.lib.common.math.integer.division; import dk.alexandra.fresco.framework.DRes; import dk.alexandra.fresco.framework.builder.Computation; import dk.alexandra.fresco.framework.builder.numeric.Numeric; import dk.alexandra.fresco.framework.builder.numeric.ProtocolBuilderNumeric; import dk.alexandra.fresco.framework.util.Pair; import dk.alexandra.fresco.framework.value.SInt; import dk.alexandra.fresco.lib.common.compare.Comparison; import dk.alexandra.fresco.lib.common.math.AdvancedNumeric; import dk.alexandra.fresco.lib.field.integer.BasicNumericContext; import java.math.BigInteger; /** *

This protocol implements integer division where both numerator and denominator are secret * shared. If the denominator is a known number {@link KnownDivisor} should be used instead.

* *

The protocol uses Goldschmidt Division (aka. the 'IBM Method').

* *

Its results approximate regular integer division with n bits, where n is equal to {@link * BasicNumericContext#getMaxBitLength()} / 4. Just like * regular integer division, this division will always truncate the result instead of rounding.

*/ public class SecretSharedDivisor implements Computation { private DRes numerator; private DRes denominator; public SecretSharedDivisor( DRes numerator, DRes denominator) { this.numerator = numerator; this.denominator = denominator; } @Override public DRes buildComputation(ProtocolBuilderNumeric builder) { BasicNumericContext basicNumericContext = builder.getBasicNumericContext(); // Calculate maximum number of bits we can represent without overflows. // We lose half of the precision because we need to multiply two numbers without overflow. // And we lose half again because we need to be able to shift the numerator left, // depending on the bit length of the denominator int maximumBitLength = basicNumericContext.getMaxBitLength() / 4; // Calculate amount of iterations that are needed to get a precise answer in all decimal bits int amountOfIterations = log2(maximumBitLength); // Convert 2 to fixed point notation with 'maximumBitLength' decimals. BigInteger two = BigInteger.valueOf(2).shiftLeft(maximumBitLength); return builder.seq(seq -> Pair.lazy(numerator, denominator) ).pairInPar((seq, pair) -> { // Determine sign of numerator and ensure positive DRes numerator = pair.getFirst(); Comparison comparison = Comparison.using(seq); DRes sign = comparison.sign(numerator); return Pair.lazy(sign, seq.numeric().mult(sign, numerator)); }, (seq, pair) -> { // Determine sign of denominator and ensure positive DRes denominator = pair.getSecond(); Comparison comparison = Comparison.using(seq); DRes sign = comparison.sign(denominator); return Pair.lazy(sign, seq.numeric().mult(sign, denominator)); }).seq((seq, pair) -> { DRes denominator = pair.getSecond().getSecond(); // Determine the actual number of bits in the denominator. DRes denominatorBitLength = getBitLength(seq, denominator, maximumBitLength); // Determine the maximum number of bits we can shift the denominator // left in order to gain more precision. BigInteger maxBitLength = BigInteger.valueOf(maximumBitLength); DRes leftShift = seq.numeric().sub(maxBitLength, denominatorBitLength); DRes leftShiftFactor = exp2(seq, leftShift, log2(maximumBitLength)); return Pair.lazy(leftShiftFactor, pair); // Left shift numerator and denominator for greater precision. // We're allowed to do this because shifting numerator and denominator // by the same amount doesn't change the outcome of the division. }).pairInPar((seq, pair) -> { DRes numeratorSign = pair.getSecond().getFirst().getFirst(); DRes numerator = pair.getSecond().getFirst().getSecond(); DRes shiftNumerator = seq.numeric().mult(pair.getFirst(), numerator); return Pair.lazy(numeratorSign, shiftNumerator); }, (seq, pair) -> { DRes denomintator = pair.getSecond().getSecond().getSecond(); DRes denomintatorSign = pair.getSecond().getSecond().getFirst(); DRes shiftedDenominator = seq.numeric().mult(pair.getFirst(), denomintator); return Pair.lazy(denomintatorSign, shiftedDenominator); } ).seq((seq, pair) -> { DRes> iterationPair = Pair .lazy(pair.getFirst().getSecond().out(), pair.getSecond().getSecond().out()); // Goldschmidt iteration for (int i = 0; i < amountOfIterations; i++) { DRes> finalPair = iterationPair; iterationPair = seq.seq((innerSeq) -> { Pair iteration = finalPair.out(); DRes d = iteration::getSecond; DRes f = innerSeq.numeric().sub(two, d); return Pair.lazy(f, iteration); }).pairInPar((innerSeq, innerPair) -> { Numeric innerNumeric = innerSeq.numeric(); DRes n = () -> innerPair.getSecond().getFirst(); DRes f = innerPair.getFirst(); return shiftRight(innerSeq, innerNumeric.mult(f, n), maximumBitLength); }, (innerSeq, innerPair) -> { Numeric innerNumeric = innerSeq.numeric(); DRes d = () -> innerPair.getSecond().getSecond(); DRes f = innerPair.getFirst(); return shiftRight(innerSeq, innerNumeric.mult(f, d), maximumBitLength); }); } DRes> iterationResult = iterationPair; return () -> new Pair<>( iterationResult.out().getFirst(), new Pair<>(pair.getFirst().getFirst(), pair.getSecond().getFirst())); }).seq((seq, pair) -> { DRes n = pair::getFirst; Pair, DRes> signs = pair.getSecond(); Numeric numeric = seq.numeric(); // Right shift to remove decimals, rounding last decimal up. n = numeric.add(BigInteger.ONE, n); n = shiftRight(seq, n, maximumBitLength); // Ensure that result has the correct sign n = numeric.mult(n, signs.getFirst()); n = numeric.mult(n, signs.getSecond()); return n; }); } private int log2(int number) { return (int) Math.ceil(Math.log(number) / Math.log(2)); } private DRes getBitLength(ProtocolBuilderNumeric builder, DRes input, int maximumBitLength) { return AdvancedNumeric.using(builder) .bitLength(input, maximumBitLength); } private DRes exp2(ProtocolBuilderNumeric builder, DRes exponent, int maxExponentLength) { return AdvancedNumeric.using(builder).exp( BigInteger.valueOf(2), exponent, maxExponentLength ); } private DRes shiftRight(ProtocolBuilderNumeric builder, DRes input, int numberOfPositions) { return AdvancedNumeric.using(builder) .rightShift(input, numberOfPositions); } } mvplibrary/src/main/java/com/se/mvplibrary/model/db/DbHelper.java package com.se.mvplibrary.model.db; import android.util.Log; /** * Created by Administrator on 2018/5/8. */ public class DbHelper implements AppDbHelper{ @Override public void testDb() { Log.d("print", "数据库操作"); } } src/main/java/cool/scx/ext/crud/CRUDApiType.java1-10 package cool.scx.ext.crud; /** *

CRUDApiType class.

* * @author scx567888 * @version 1.10.8 */ public enum CRUDApiType { /** * a */ LIST, /** * a */ INFO, /** * a */ ADD, /** * a */ UPDATE, /** * a */ DELETE, /** * a */ BATCH_DELETE, /** * a */ REVOKE_DELETE, /** * a */ CHECK_UNIQUE } /* * Copyright (C) 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 com.landawn.abacus.parser; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import com.landawn.abacus.annotation.JsonXmlField; import com.landawn.abacus.exception.UncheckedIOException; /** * Design principles:
  • 1, Simple (is beautiful)
  • 2, Fast (is powerful)
  • 3, Concepts (must be integral * and consistent)

  • * These principles can't be broken by any change or reason. And basically programmable is > configurable. There is no * extra support by configuration file or annotation. * * All the implementation should be multi-thread safety. * * @author * @param * @param * @see JsonXmlField * @since 0.8 */ public interface Parser, DC extends DeserializationConfig> { /** * * @param obj * @return */ String serialize(Object obj); /** * * @param obj * @param config * @return */ String serialize(Object obj, SC config); /** * * @param output * @param obj * @throws UncheckedIOException the unchecked IO exception */ void serialize(File output, Object obj) throws UncheckedIOException; /** * * @param output * @param obj * @param config * @throws UncheckedIOException the unchecked IO exception */ void serialize(File output, Object obj, SC config) throws UncheckedIOException; /** * * @param output * @param obj * @throws UncheckedIOException the unchecked IO exception */ void serialize(OutputStream output, Object obj) throws UncheckedIOException; /** * * @param output * @param obj * @param config * @throws UncheckedIOException the unchecked IO exception */ void serialize(OutputStream output, Object obj, SC config) throws UncheckedIOException; /** * * @param output * @param obj * @throws UncheckedIOException the unchecked IO exception */ void serialize(Writer output, Object obj) throws UncheckedIOException; /** * * @param output * @param obj * @param config * @throws UncheckedIOException the unchecked IO exception */ void serialize(Writer output, Object obj, SC config) throws UncheckedIOException; /** * * @param * @param targetClass * @param source * @return */ T deserialize(Class targetClass, String source); /** * * @param * @param targetClass * @param source * @param config * @return */ T deserialize(Class targetClass, String source, DC config); /** * * @param * @param targetClass * @param source * @return * @throws UncheckedIOException the unchecked IO exception */ T deserialize(Class targetClass, File source) throws UncheckedIOException; /** * * @param * @param targetClass * @param source * @param config * @return * @throws UncheckedIOException the unchecked IO exception */ T deserialize(Class targetClass, File source, DC config) throws UncheckedIOException; /** * * @param * @param targetClass * @param source * @return * @throws UncheckedIOException the unchecked IO exception */ T deserialize(Class targetClass, InputStream source) throws UncheckedIOException; /** * * @param * @param targetClass * @param source * @param config * @return * @throws UncheckedIOException the unchecked IO exception */ T deserialize(Class targetClass, InputStream source, DC config) throws UncheckedIOException; /** * * @param * @param targetClass * @param source * @return * @throws UncheckedIOException the unchecked IO exception */ T deserialize(Class targetClass, Reader source) throws UncheckedIOException; /** * * @param * @param targetClass * @param source * @param config * @return * @throws UncheckedIOException the unchecked IO exception */ T deserialize(Class targetClass, Reader source, DC config) throws UncheckedIOException; } package testing; /** * The point of this is to test the getPrice method from Ticket * @author * last updated: 4/30/2020 */ import java.util.ArrayList; import models.Menu; import models.MenuItem; import models.ModelConstants; import models.Ticket; public class TestTicketGetPrice { public static void main(String[] args) { //Some variables for testing data and to measure success ArrayList testData = assembleFakeData(); double[] expectedValues = {0, -20, 0, 8, 16}; Ticket testTicket = new Ticket(); boolean successFlag = true; String[] passMessages = {"Passed the Error case.", "We can add two negative numbers.", "We can add a negative and a positive number.", "We can add positive numbers.", "We can add positive numbers again.", }; String failMessage = "Wow we suck at life."; String successMessage = "The function passed all tests."; for(int x = 0; x < testData.size(); x++) { if(successFlag) { testTicket = new Ticket(); testTicket.addMenuItems(testData.get(x).getItems()); successFlag = checkPrice(expectedValues[x], testTicket); System.out.println(successFlag ? passMessages[x] : failMessage); } } System.out.println(successFlag ? successMessage : failMessage); } public static boolean checkPrice(double _expectedPrice, Ticket _currTicket) { return (_expectedPrice == _currTicket.getPrice()); } public static ArrayList assembleFakeData() { ArrayList retVal = new ArrayList(); MenuItem pepPizza = new MenuItem(1, "Pepperoni Pizza", 10.00, 0, 0); MenuItem chePizza = new MenuItem(1, "Cheese Pizza", -10.00, 0, 0); MenuItem cokeDrink = new MenuItem(2, "Coke", 4, 0, 0); MenuItem[] aMenuList = { chePizza, chePizza }; MenuItem[] bMenuList = { pepPizza, chePizza }; MenuItem[] cMenuList = { cokeDrink, cokeDrink}; MenuItem[] dMenuList = { cokeDrink, cokeDrink, cokeDrink, cokeDrink}; Menu nullMenu = new Menu("Pizza", ModelConstants.MENU_TYPE_PIZZAS); Menu aMenu = new Menu("Pizza", ModelConstants.MENU_TYPE_PIZZAS); Menu bMenu = new Menu("Pizza", ModelConstants.MENU_TYPE_PIZZAS); Menu cMenu = new Menu("Pizza", ModelConstants.MENU_TYPE_PIZZAS); Menu dMenu = new Menu("Pizza", ModelConstants.MENU_TYPE_PIZZAS); aMenu.setItems(aMenuList); bMenu.setItems(bMenuList); cMenu.setItems(cMenuList); dMenu.setItems(dMenuList); retVal.add(nullMenu); retVal.add(aMenu); retVal.add(bMenu); retVal.add(cMenu); retVal.add(dMenu); return retVal; } }package com.qaprosoft.carina.myfp.android; import com.qaprosoft.carina.core.foundation.utils.factory.DeviceType; import com.qaprosoft.carina.core.foundation.utils.mobile.IMobileUtils; import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement; import com.qaprosoft.carina.core.gui.AbstractPage; import com.qaprosoft.carina.myfp.common.CreateAccountPageBase; import com.qaprosoft.carina.myfp.common.WeeklyGoalPageBase; import com.qaprosoft.carina.myfp.utils.constants.TextConstants; import com.qaprosoft.carina.myfp.utils.constants.TimeConstants; import com.qaprosoft.carina.myfp.utils.enums.YouPage; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.FindBy; @DeviceType(pageType = DeviceType.Type.ANDROID_PHONE, parentClass = WeeklyGoalPageBase.class) public class WeeklyGoalPage extends WeeklyGoalPageBase implements TimeConstants, IMobileUtils, TextConstants { public WeeklyGoalPage(WebDriver driver) { super(driver); } @FindBy(id = "com.myfitnesspal.android:id/units") private ExtendedWebElement unitsDropdown; @FindBy(xpath = "//android.widget.CheckedTextView[@text='%s']") private ExtendedWebElement itemByText; @FindBy(xpath = "//android.widget.TextView[@text='%s']") private ExtendedWebElement getItemByChosenText; @FindBy(id = "com.myfitnesspal.android:id/goal_weight") private ExtendedWebElement goaLWeightDropdown; @FindBy(id = "com.myfitnesspal.android:id/entry_one") private ExtendedWebElement inputWeight; @FindBy(id = "android:id/button1") private ExtendedWebElement setButton; @FindBy(xpath = "//android.widget.RadioButton[@text='%s']") private ExtendedWebElement radioButtonByText; @FindBy(id = "com.myfitnesspal.android:id/nextButton") private ExtendedWebElement nextButton; @FindBy(id = "com.myfitnesspal.android:id/container") private ExtendedWebElement container; @Override public void typeWeight(String value) { goaLWeightDropdown.click(); inputWeight.type(String.valueOf(value)); } @Override public AbstractPage selectWeightUnitFromDropdown(YouPage weight) { unitsDropdown.click(); itemByText.format(weight.getName()).click(THREE_SECONDS); return initPage(getDriver(), weight.getPageClass()); } @Override public boolean isWeightUnitSelected(String unit) { return getItemByChosenText.format(unit).isElementPresent(THREE_SECONDS); } @Override public void clickOnSetButton() { setButton.click(); hideKeyboard(); } @Override public AbstractPage switchToWeeklyGoal(YouPage weeklyGoal) { radioButtonByText.format(weeklyGoal.getName()).click(THREE_SECONDS); return initPage(getDriver(), weeklyGoal.getPageClass()); } @Override public boolean isWeeklyGoalSelected(String weeklyGoal) { return radioButtonByText.format(weeklyGoal).isElementPresent(THREE_SECONDS); } @Override public void typeWeightAgain(String weight) { inputWeight.type(String.valueOf(weight)); } @Override public void clickToOpenDropdownWeight() { goaLWeightDropdown.click(); } @Override public CreateAccountPageBase followToCreateAccountPage() { swipe(nextButton, container, 5); nextButton.click(THREE_SECONDS); return initPage(getDriver(), CreateAccountPageBase.class); } @Override public String isInputWeightPresent() { return inputWeight.getText(); } }patrickbussmann/app-VZD-Client /* * Copyright (c) 2020 gematik GmbH * * 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. */ /* * I_Directory_Administration * REST Schnittstelle zur Pflege der Verzeichniseinträge. Über diese Schnittstelle können Verzeichniseinträge inklusive Zertifikaten erzeugt, aktualisiert und gelöscht werden. Die Administration von Fachdaten erfolgt über Schnittstelle I_Directory_Application_Maintenance und wird durch die Fachanwendungen durchgeführt. Lesender Zugriff auf die Fachdaten ist mit Operation getDirectoryEntries in vorliegender Schnittstelle möglich. * * The version of the OpenAPI document: 1.1.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package de.gematik.ti.epa.vzd.client.model; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModelProperty; import java.util.List; import java.util.Objects; /** * FAD1 */ public class FAD1 { public static final String SERIALIZED_NAME_DN = "dn"; @SerializedName(SERIALIZED_NAME_DN) private DistinguishedName dn; public static final String SERIALIZED_NAME_MAIL = "mail"; @SerializedName(SERIALIZED_NAME_MAIL) private List mail = null; public FAD1 dn(DistinguishedName dn) { this.dn = dn; return this; } /** * Get dn * * @return dn **/ @ApiModelProperty(required = true, value = "") public DistinguishedName getDn() { return dn; } public void setDn(DistinguishedName dn) { this.dn = dn; } /** * Get mail * * @return mail **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public List getMail() { return mail; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FAD1 FAD1 = (FAD1) o; return Objects.equals(this.dn, FAD1.dn) && Objects.equals(this.mail, FAD1.mail); } @Override public int hashCode() { return Objects.hash(dn, mail); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class FAD1 {\n"); sb.append(" dn: ").append(toIndentedString(dn)).append("\n"); sb.append(" mail: ").append(toIndentedString(mail)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } imlige/demo-websocket package com.cmdizj.websocket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoWebsocketApplication { public static void main(String[] args) { SpringApplication.run(DemoWebsocketApplication.class, args); } } /* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.rpc.client.impl; import com.google.gwt.rpc.client.ast.CommandSink; import com.google.gwt.rpc.client.ast.ValueCommand; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * Contains base methods for implementing a SerializationStreamWriter. */ public abstract class CommandSerializationStreamWriterBase implements SerializationStreamWriter { private final CommandSink commandSink; protected CommandSerializationStreamWriterBase(CommandSink sink) { this.commandSink = sink; } public void writeBoolean(boolean value) throws SerializationException { commandSink.accept(makeValue(boolean.class, value)); } public void writeByte(byte value) throws SerializationException { commandSink.accept(makeValue(byte.class, value)); } public void writeChar(char value) throws SerializationException { commandSink.accept(makeValue(char.class, value)); } public void writeDouble(double value) throws SerializationException { commandSink.accept(makeValue(double.class, value)); } public void writeFloat(float value) throws SerializationException { commandSink.accept(makeValue(float.class, value)); } public void writeInt(int value) throws SerializationException { commandSink.accept(makeValue(int.class, value)); } public void writeLong(long value) throws SerializationException { commandSink.accept(makeValue(long.class, value)); } public void writeObject(Object instance) throws SerializationException { commandSink.accept(makeValue(instance != null ? instance.getClass() : void.class, instance)); } public void writeShort(short value) throws SerializationException { commandSink.accept(makeValue(short.class, value)); } public void writeString(String value) throws SerializationException { commandSink.accept(makeValue(String.class, value)); } protected final CommandSink getCommandSink() { return commandSink; } protected abstract ValueCommand makeValue(Class type, Object value) throws SerializationException; }sonecabr/konker-platformkonker.registry.services.core/src/main/java/com/konkerlabs/platform/registry/business/services/DeviceConfigSetupServiceImpl.java package com.konkerlabs.platform.registry.business.services; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.konkerlabs.platform.registry.business.model.Application; import com.konkerlabs.platform.registry.business.model.DeviceConfig; import com.konkerlabs.platform.registry.business.model.DeviceConfigSetup; import com.konkerlabs.platform.registry.business.model.DeviceModel; import com.konkerlabs.platform.registry.business.model.Location; import com.konkerlabs.platform.registry.business.model.Tenant; import com.konkerlabs.platform.registry.business.model.validation.CommonValidations; import com.konkerlabs.platform.registry.business.repositories.DeviceConfigSetupRepository; import com.konkerlabs.platform.registry.business.services.api.ApplicationService; import com.konkerlabs.platform.registry.business.services.api.DeviceConfigSetupService; import com.konkerlabs.platform.registry.business.services.api.DeviceModelService; import com.konkerlabs.platform.registry.business.services.api.LocationSearchService; import com.konkerlabs.platform.registry.business.services.api.LocationService; import com.konkerlabs.platform.registry.business.services.api.ServiceResponse; import com.konkerlabs.platform.registry.business.services.api.ServiceResponseBuilder; import com.mongodb.util.JSON; import com.mongodb.util.JSONParseException; @Service @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class DeviceConfigSetupServiceImpl implements DeviceConfigSetupService { @Autowired private DeviceConfigSetupRepository deviceConfigSetupRepository; @Autowired private LocationSearchService locationSearchService; @Override public ServiceResponse> findAll(Tenant tenant, Application application) { if (!Optional.ofNullable(tenant).isPresent()) { return ServiceResponseBuilder.>error() .withMessage(CommonValidations.TENANT_NULL.getCode()).build(); } if (!Optional.ofNullable(application).isPresent()) { return ServiceResponseBuilder.>error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()).build(); } return ServiceResponseBuilder.>ok() .withResult(getDeviceConfigs(tenant, application)) .build(); } @Override public ServiceResponse save(Tenant tenant, Application application, DeviceModel deviceModel, Location location, String json) { ServiceResponse validationsResponse = validate(tenant, application, deviceModel, location); if (validationsResponse != null && !validationsResponse.isOk()) { return validationsResponse; } if (isInvalidJson(json)) { return ServiceResponseBuilder.error() .withMessage(Validations.DEVICE_INVALID_JSON.getCode()).build(); } DeviceConfigSetup deviceConfigSetupDB = getCurrentConfigSetup(tenant, application); List configs = deviceConfigSetupDB.getConfigs(); DeviceConfig deviceConfig = findDeviceConfig(configs, deviceModel, location); if (deviceConfig == null) { deviceConfig = DeviceConfig.builder() .deviceModel(deviceModel.getName()) .deviceModelGuid(deviceModel.getGuid()) .locationName(location.getName()) .locationGuid(location.getGuid()) .json(json) .build(); configs.add(deviceConfig); } else { deviceConfig.setJson(json); } DeviceConfigSetup deviceConfigSetupNew = getNewApplication(tenant, application, deviceConfigSetupDB.getVersion() + 1); deviceConfigSetupNew.setConfigs(configs); deviceConfigSetupRepository.save(deviceConfigSetupNew); return ServiceResponseBuilder.ok().withResult(deviceConfig).build(); } private boolean isInvalidJson(String json) { if (StringUtils.isBlank(json)) { return true; } try { JSON.parse(json); } catch (JSONParseException e) { return true; } return false; } @Override public ServiceResponse update(Tenant tenant, Application application, DeviceModel deviceModel, Location location, String json) { ServiceResponse validationsResponse = validate(tenant, application, deviceModel, location); if (validationsResponse != null && !validationsResponse.isOk()) { return validationsResponse; } if (isInvalidJson(json)) { return ServiceResponseBuilder.error() .withMessage(Validations.DEVICE_INVALID_JSON.getCode()).build(); } DeviceConfigSetup deviceConfigSetupDB = getCurrentConfigSetup(tenant, application); List configs = deviceConfigSetupDB.getConfigs(); DeviceConfig deviceConfig = findDeviceConfig(configs, deviceModel, location); if (deviceConfig == null) { return ServiceResponseBuilder.error() .withMessage(Validations.DEVICE_CONFIG_NOT_FOUND.getCode()) .build(); } else { deviceConfig.setJson(json); } DeviceConfigSetup deviceConfigSetupNew = getNewApplication(tenant, application, deviceConfigSetupDB.getVersion() + 1); deviceConfigSetupNew.setConfigs(configs); deviceConfigSetupRepository.save(deviceConfigSetupNew); return ServiceResponseBuilder.ok().withResult(deviceConfig).build(); } @Override public ServiceResponse remove(Tenant tenant, Application application, DeviceModel deviceModel, Location location) { ServiceResponse validationsResponse = validate(tenant, application, deviceModel, location); if (validationsResponse != null && !validationsResponse.isOk()) { return validationsResponse; } DeviceConfigSetup deviceConfigSetupDB = getCurrentConfigSetup(tenant, application); List configs = deviceConfigSetupDB.getConfigs(); configs.remove(DeviceConfig.builder().deviceModelGuid(deviceModel.getGuid()).locationGuid(location.getGuid()).build()); DeviceConfigSetup deviceConfigSetupNew = getNewApplication(tenant, application, deviceConfigSetupDB.getVersion() + 1); deviceConfigSetupNew.setConfigs(configs); deviceConfigSetupRepository.save(deviceConfigSetupNew); return ServiceResponseBuilder.ok() .withResult(deviceConfigSetupNew) .withMessage(Messages.DEVICE_CONFIG_REMOVED_SUCCESSFULLY.getCode()) .build(); } @Override public ServiceResponse findByModelAndLocation(Tenant tenant, Application application, DeviceModel deviceModel, Location location) { ServiceResponse validationsResponse = validate(tenant, application, deviceModel, location); if (validationsResponse != null && !validationsResponse.isOk()) { return validationsResponse; } DeviceConfigSetup deviceConfigSetupDB = getCurrentConfigSetup(tenant, application); List configs = deviceConfigSetupDB.getConfigs(); ServiceResponse locationResponse = locationSearchService.findByName(tenant, application, location.getName(), true); if (!locationResponse.isOk()) { return ServiceResponseBuilder.error() .withMessages(locationResponse.getResponseMessages()) .build(); } Location locationNode = locationResponse.getResult(); DeviceConfig config = null; // search for config in location and above locations while (locationNode != null) { if (config == null) { config = findDeviceConfig(configs, deviceModel, locationNode); } locationNode = locationNode.getParent(); } if (config != null) { return ServiceResponseBuilder.ok().withResult(config.getJson()).build(); } else { return ServiceResponseBuilder.error() .withMessage(Validations.DEVICE_CONFIG_NOT_FOUND.getCode()) .build(); } } private DeviceConfig findDeviceConfig(List configs, DeviceModel model, Location location) { for (DeviceConfig deviceConfig : configs) { if (deviceConfig.getDeviceModelGuid().equals(model.getGuid()) && deviceConfig.getLocationGuid().equals(location.getGuid())) { return deviceConfig; } } return null; } private List getDeviceConfigs(Tenant tenant, Application application) { DeviceConfigSetup deviceConfigSetup = getCurrentConfigSetup(tenant, application); return deviceConfigSetup.getConfigs(); } private DeviceConfigSetup getCurrentConfigSetup(Tenant tenant, Application application) { List configSetups = deviceConfigSetupRepository.findAllByTenantIdAndApplicationName(tenant.getId(), application.getName()); if (configSetups.isEmpty()) { DeviceConfigSetup configSetup = getNewApplication(tenant, application, 0); deviceConfigSetupRepository.save(configSetup); return configSetup; } Collections.sort(configSetups); return configSetups.get(0); } private DeviceConfigSetup getNewApplication(Tenant tenant, Application application, int version) { return DeviceConfigSetup.builder() .tenant(tenant) .application(application) .configs(new ArrayList<>()) .version(version) .date(Instant.now()) .build(); } private ServiceResponse validate(Tenant tenant, Application application, DeviceModel deviceModel, Location location) { if (!Optional.ofNullable(tenant).isPresent()) { return ServiceResponseBuilder.error() .withMessage(CommonValidations.TENANT_NULL.getCode()).build(); } if (!Optional.ofNullable(application).isPresent()) { return ServiceResponseBuilder.error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()).build(); } if (!Optional.ofNullable(deviceModel).isPresent() || !Optional.ofNullable(deviceModel.getGuid()).isPresent()) { return ServiceResponseBuilder.error() .withMessage(DeviceModelService.Validations.DEVICE_MODEL_NULL.getCode()).build(); } if (!Optional.ofNullable(location).isPresent() || !Optional.ofNullable(location.getGuid()).isPresent()) { return ServiceResponseBuilder.error() .withMessage(LocationService.Validations.LOCATION_GUID_NULL.getCode()).build(); } return null; } @Override public ServiceResponse> findAllByDeviceModel(Tenant tenant, Application application, DeviceModel deviceModel) { if (!Optional.ofNullable(tenant).isPresent()) { return ServiceResponseBuilder.>error() .withMessage(CommonValidations.TENANT_NULL.getCode()).build(); } if (!Optional.ofNullable(application).isPresent()) { return ServiceResponseBuilder.>error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()).build(); } if (!Optional.ofNullable(deviceModel).isPresent() || !Optional.ofNullable(deviceModel.getGuid()).isPresent()) { return ServiceResponseBuilder.>error() .withMessage(DeviceModelService.Validations.DEVICE_MODEL_NULL.getCode()).build(); } return ServiceResponseBuilder.>ok() .withResult(getDeviceConfigs(tenant, application) .stream() .filter(p -> p.getDeviceModelGuid().equals(deviceModel.getGuid())) .collect(Collectors.toList())) .build(); } @Override public ServiceResponse> findAllByLocation(Tenant tenant, Application application, Location location) { if (!Optional.ofNullable(tenant).isPresent()) { return ServiceResponseBuilder.>error() .withMessage(CommonValidations.TENANT_NULL.getCode()).build(); } if (!Optional.ofNullable(application).isPresent()) { return ServiceResponseBuilder.>error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()).build(); } if (!Optional.ofNullable(location).isPresent() || !Optional.ofNullable(location.getGuid()).isPresent()) { return ServiceResponseBuilder.>error() .withMessage(LocationService.Validations.LOCATION_GUID_NULL.getCode()).build(); } return ServiceResponseBuilder.>ok() .withResult(getDeviceConfigs(tenant, application) .stream() .filter(p -> p.getLocationGuid().equals(location.getGuid())) .collect(Collectors.toList())) .build(); } } package edu.dlut.catmall.order.service; import com.baomidou.mybatisplus.extension.service.IService; import edu.dlut.catmall.order.vo.*; import edu.dlut.common.to.mq.SeckillOrderTO; import edu.dlut.common.utils.PageUtils; import edu.dlut.catmall.order.entity.OrderEntity; import java.util.Map; import java.util.concurrent.ExecutionException; /** * 订单 * * @author raymond * @email * @date 2020-04-30 09:50:58 */ public interface OrderService extends IService { PageUtils queryPage(Map params); OrderConfirmVO confirmOrder() throws ExecutionException, InterruptedException; SubmitOrderResponseVO submitOrder(OrderSubmitVO submitVO); OrderEntity getOrderByOrderSn(String orderSn); void closeOrder(OrderEntity entity); PayVo getOrderPay(String orderSn); PageUtils queryPageWithItems(Map params); String handlePayResult(PayAsyncVo vo); void createSeckillOrder(SeckillOrderTO seckillOrder); } src/main/java/com/fun/uncle/watcher/SendSuccessMessageObserver.java0 package com.fun.uncle.watcher; /** * @Description: 发送成功的信息观察者 * @Author: Summer * @DateTime: 2021/11/4 2:55 下午 * @Version: 0.0.1-SNAPSHOT */ public class SendSuccessMessageObserver implements Observer{ @Override public void update(String message) { // 处理业务逻辑 System.out.println("注册成功"); } public static void main(String[] args) { // 假设用户注册成功直接通知观察者,改干自己的事情了 ConcreteSubject subject = buildSubject(); subject.notifyObservers(""); } private static ConcreteSubject buildSubject() { ConcreteSubject subject = new ConcreteSubject(); subject.attach(new SendSuccessMessageObserver()); subject.attach(new SendNewPersonCouponObserver()); return subject; } } 1-10 package blog.controller; import blog.dao.BlogSonDao; import blog.dao.BlogSonDaoImpl; import blog.model.BlogSon; 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; import static java.lang.System.out; @WebServlet(name = "ShowUpdateSonServlet", value = "/ShowUpdateSonServlet") public class ShowUpdateSonServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idStr = request.getParameter("user_id"); if (idStr!=null&&!idStr.equals("")){ int id = Integer.parseInt(idStr); BlogSonDao dao = new BlogSonDaoImpl(); List blogSonList = dao.selectByID(id); if (blogSonList == null){ out.println("null"); } else { request.setAttribute("blogSonList",blogSonList); request.getRequestDispatcher("/update_son.jsp").forward(request,response); } } } } /* * Copyright 2015 the original author or hunter. * 未经正式书面同意,其他任何个人、团体不得使用、复制、修改或发布本软件. */ package com.hunter.common.base.security; import java.util.Collection; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.util.CollectionUtils; import com.hunter.common.base.dao.SysUserDao; import com.hunter.common.base.model.SysUserVO; /** * 用户认证 * * @Description 根据帐号加载用户权限信息 * @author linyong * @since 2015年5月17日 下午5:23:28 */ public class DefaultUserDetailsService implements UserDetailsService { private final Logger logger = LoggerFactory.getLogger(getClass()); @Resource private SysUserDao sysUserDao; /** * 默认的登录验证DaoAuthenticationProvider中已经注入了缓存,这里就不再使用了, * @see 注意AbstractUserDetailsAuthenticationProvider的148行, * 如果当前用户状态异常,且是从缓存中获取的,就重新调用本对象的loadUserByUsername方法获取最新用户状态, * 这样在修改用户状态后能实时更新过来. */ /*@Resource private UserCache userCache;*/ /** * 根据帐号查询用户权限信息 * * @param username * @return * @throws UsernameNotFoundException * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) */ public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException { SysUserVO user = this.sysUserDao.getUserByAccount(account); if (user == null) throw new UsernameNotFoundException("User not exists",null); // 得到用户的权限 Collection auths = this.sysUserDao.loadUserAuthorities(account); if (CollectionUtils.isEmpty(auths)) { // 按照Spring的标准如果没有任何权限也是要抛出这个异常的,在这里就不做判断了 logger.info("该用户【" + account + "】没有配置任何权限!"); } // 将权限设置到用户对象中 user.setAuthorities(auths); logger.info("============" + account + "登录系统了,拥有的权限集合:"+auths+"============"); return user; } } /* * 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.harmony.test.func.api.java.awt.KeyboardFocusManager; import java.awt.AWTEvent; import java.awt.AWTException; import java.awt.AWTKeyStroke; import java.awt.Button; import java.awt.Component; import java.awt.Container; import java.awt.DefaultKeyboardFocusManager; import java.awt.Dimension; import java.awt.FocusTraversalPolicy; import java.awt.Frame; import java.awt.KeyboardFocusManager; import java.awt.Panel; import java.awt.Point; import java.awt.Robot; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.io.File; import java.util.Iterator; import java.util.Set; import org.apache.harmony.test.func.api.share.AutonomousTest; import org.apache.harmony.share.Result; public class KeyboardFocusManagerTest extends AutonomousTest { static File testDir; protected Frame frm; Button btnClose; Button btnDoNothing; protected final int WIN_WIDTH = 320; protected final int WIN_HEIGHT = 240; protected final int WIN_X = 150; protected final int WIN_Y = 150; protected Dimension winDimension = new Dimension(WIN_WIDTH, WIN_HEIGHT); protected Dimension smallWinDimension = new Dimension(WIN_WIDTH / 4, WIN_HEIGHT / 4); protected Point winLocation = new Point(WIN_X, WIN_Y); protected boolean actionPerformed = false; protected boolean componentEventFocusLost = false; /** * MyKeyboardFocusManager class serves as a custom focus manager that can be * modified upon the necessity of a particular Test */ class MyKeyboardFocusManager extends KeyboardFocusManager { protected boolean postProcessKeyEventCalled = false; protected boolean myProperty = false; public boolean getMyProperty() { return myProperty; } public Window getGlobalActiveWindow() throws SecurityException { return super.getGlobalActiveWindow(); } public void setGlobalActiveWindow(Window activeWindow) { super.setGlobalActiveWindow(activeWindow); } public Window getGlobalFocusedWindow() { return super.getGlobalFocusedWindow(); } public void setGlobalFocusedWindow(Window window) { super.setGlobalFocusedWindow(window); } public boolean dispatchEvent(AWTEvent arg0) { return false; } public void setGlobalFocusOwner(Component focusOwner) { super.setGlobalFocusOwner(focusOwner); } public Component getGlobalFocusOwner() { return super.getGlobalFocusOwner(); } public Component getGlobalPermanentFocusOwner() { return super.getGlobalPermanentFocusOwner(); } public void setGlobalPermanentFocusOwner(Component focusOwner) { super.setGlobalPermanentFocusOwner(focusOwner); } protected void dequeueKeyEvents(long arg0, Component arg1) { } protected void enqueueKeyEvents(long arg0, Component arg1) { } protected void discardKeyEvents(Component arg0) { } public void focusNextComponent(Component arg0) { } public void focusPreviousComponent(Component arg0) { } public void upFocusCycle(Component arg0) { } public void downFocusCycle(Container arg0) { } public boolean dispatchKeyEvent(KeyEvent arg0) { return false; } public boolean postProcessKeyEvent(KeyEvent arg0) { postProcessKeyEventCalled = true; return false; } public void processKeyEvent(Component arg0, KeyEvent arg1) { } public void myFirePropertyChange(String propertyName, Object oldValue, Object newValue) { super.firePropertyChange(propertyName, oldValue, newValue); } public void myFireVetoablePropertyChange(String propertyName, Object oldValue, Object newValue) throws PropertyVetoException { super.fireVetoableChange(propertyName, oldValue, newValue); } } /** * * MyPropChangeListener class has an embedded counter, that is incremented * each tiem the bound property is changed */ public class MyPropChangeListener implements PropertyChangeListener { private int propChangedTimes = 0; public int getPropChangedTimes() { return propChangedTimes; } public void propertyChange(PropertyChangeEvent arg0) { ++propChangedTimes; } } public class MyVetoChangeListener implements VetoableChangeListener { private int propChangedTimes = 0; public int getPropChangedTimes() { return propChangedTimes; } public void vetoableChange(PropertyChangeEvent arg0) throws PropertyVetoException { ++propChangedTimes; } } public KeyEvent provideKeyEvent(int modifiers, int keyCode, char keyChar) { return new KeyEvent(frm, KeyEvent.KEY_PRESSED, System .currentTimeMillis(), modifiers, keyCode, keyChar); } protected void setUp() { frm = new Frame("My Frame"); btnClose = new Button("MyClose"); btnDoNothing = new Button("MyLoafer"); /* WM_DESTROY is posted when button is clicked */ ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent ae) { actionPerformed = true; String action = ae.getActionCommand(); if (action.equals("MyClose")) { frm.dispose(); } else { System.out.println(action); } } }; btnClose.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { componentEventFocusLost = true; } }); btnClose.addActionListener(al); btnClose.setBounds(10, 10, 80, 22); btnDoNothing.setBounds(70, 20, 100, 22); Panel panel = new Panel(); panel.setLayout(null); panel.setSize(winDimension); panel.add(btnClose); panel.add(btnDoNothing); frm.add(panel); /* Handler for WM_DESTROY message */ frm.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frm.dispose(); } }); frm.setSize(winDimension); } protected void tearDown() { frm.dispose(); } public void setTestDir(File dir) { testDir = dir; } public static void main(String[] args) { // File f = new File("C:\\temp\\toDelete"); // KeyboardFocusManagerTest kfmTest = new KeyboardFocusManagerTest(); // kfmTest.setUp(); // kfmTest.setTestDir(f); // kfmTest.test(args); // kfmTest.tearDown(); // System.exit(0); System.exit(new KeyboardFocusManagerTest().test(args)); } public Result testKeyboardFocusManager_addKeyEventPostProcessor() { MyKeyboardFocusManager keyEvPostProcessor = new MyKeyboardFocusManager(); DefaultKeyboardFocusManager dkfm = new DefaultKeyboardFocusManager(); dkfm.addKeyEventPostProcessor(keyEvPostProcessor); /* Implicit call of MyKeyboardFocusManager#postProcessKeyEvent */ dkfm.dispatchKeyEvent(provideKeyEvent(0, KeyEvent.VK_SPACE, ' ')); if (keyEvPostProcessor.postProcessKeyEventCalled == false) { return failed("\nMyKeyboardFocusManager#postProcessKeyEvent has " + "not been called"); } return passed(); } public Result testKeyboardFocusManager_clearGlobalFocusOwner() { frm.setVisible(true); /* Get instance of btnClose button */ Button btn = (Button) ((Container) frm.getComponents()[0]) .getComponents()[0]; btn.requestFocus(); MyKeyboardFocusManager keyEvPostProcessor = new MyKeyboardFocusManager(); DefaultKeyboardFocusManager dkfm = new DefaultKeyboardFocusManager(); dkfm.addKeyEventPostProcessor(keyEvPostProcessor); Robot robo = null; try { robo = new Robot(); } catch (AWTException e) { e.printStackTrace(); } /* Move mouse to the btn (btnClose) */ robo.mouseMove(btn.getX() - 5, btn.getY() - 5); componentEventFocusLost = false; /* * This sleep is required because drawing of the GUI components on Linux * PCs can be very slow */ sleep(getPaintTimeout()); waitEventQueueToClear(); /* FOCUS_LOST event must be sent to btn (btnClose) */ dkfm.clearGlobalFocusOwner(); waitEventQueueToClear(); sleep(getPaintTimeout()); if (componentEventFocusLost == false) { return failed("\nThe component failed to recieve a FOCUS_LOST event"); } /* reset the actionPerformed flag */ actionPerformed = false; /* * Click button, the button must not be clicked and "actionPerformed" * flag should not be set */ robo.keyPress(KeyEvent.VK_ENTER); robo.keyRelease(KeyEvent.VK_ENTER); waitEventQueueToClear(); // System.out.println("actionPerformed: " + componentEventFocusLost); // System.out.println("componentEventFocusLost: " // + componentEventFocusLost); if (actionPerformed) { return failed("\nAfter calling clearGlobalFocusOwner() \"the native " + "windowing system will discard all user-generated " + "KeyEvents\" in our keyPress and keyRelease occured on " + "a button"); } return passed(); } public Result testKeyboardFocusManager_propertyChange() { MyKeyboardFocusManager myKFM = new MyKeyboardFocusManager(); MyPropChangeListener myPropChangeListener = new MyPropChangeListener(); MyVetoChangeListener myVetoChangeListener = new MyVetoChangeListener(); // DefaultKeyboardFocusManager dkfm = new DefaultKeyboardFocusManager(); /* Get instance of btnClose button */ Button btnOldFocusOwner = (Button) ((Container) frm.getComponents()[0]) .getComponents()[0]; /* Get instance of btnDoNothing button */ Button btnNewFocusOwner = (Button) ((Container) frm.getComponents()[0]) .getComponents()[1]; frm.setVisible(true); btnOldFocusOwner.requestFocus(); sleep(getPaintTimeout()); myKFM.addPropertyChangeListener(myPropChangeListener); myKFM.addVetoableChangeListener("myProperty", myVetoChangeListener); waitEventQueueToClear(); /* try to change the property */ myKFM.myFirePropertyChange("focusOwner", btnOldFocusOwner, btnNewFocusOwner); waitEventQueueToClear(); if (myPropChangeListener.getPropChangedTimes() != 1) { return failed("\nfirePropertyChange has failed to change " + "focusOwner property"); } /* * try again to change the property, according to spec No event will be * delivered if oldValue and newValue are the same. */ myKFM.myFirePropertyChange("focusOwner", btnNewFocusOwner, btnNewFocusOwner); waitEventQueueToClear(); if (myPropChangeListener.getPropChangedTimes() != 1) { return failed("\nNo event must be delivered when " + "oldValue and newValue are the same.\nAs a result the " + "property has changed wrong number of times.\nThe " + "expected number of times is 1, the retrieved number is " + myPropChangeListener.getPropChangedTimes()); } btnOldFocusOwner.requestFocus(); sleep(getPaintTimeout()); /* try to change the vetoable property */ boolean propertyVetoExceptionThrown = false; try { myKFM.myFireVetoablePropertyChange("myProperty", new Boolean(false), new Boolean(true)); } catch (PropertyVetoException e) { propertyVetoExceptionThrown = true; } if (propertyVetoExceptionThrown == true) { return failed("\nPropertyVetoException must not be thrown"); } waitEventQueueToClear(); if (myVetoChangeListener.getPropChangedTimes() != 1) { return failed("\nfirePropertyChange has failed to change " + "myProperty property"); } /* * try again to change the property, according to spec No event will be * delivered if oldValue and newValue are the same. */ try { myKFM.myFireVetoablePropertyChange("myProperty", new Boolean(false), new Boolean(false)); } catch (PropertyVetoException e) { propertyVetoExceptionThrown = true; } waitEventQueueToClear(); if (myVetoChangeListener.getPropChangedTimes() != 1) { return failed("\nNo event must be delivered when VetoableProperty " + "oldValue and newValue are the same.\nAs a result the " + "property has changed wrong number of times.\nThe " + "expected number of times is 1, the retrieved number is " + myVetoChangeListener.getPropChangedTimes()); } frm.setVisible(false); return passed(); } public Result testKeyboardFocusManager_getProperties() { MyKeyboardFocusManager myKFM = new MyKeyboardFocusManager(); frm.setVisible(true); sleep(getPaintTimeout()); try { KeyboardFocusManager.setCurrentKeyboardFocusManager(myKFM); } catch (SecurityException e) { return failed("\nFor some reason it is not allowed to call " + "KeyboardFocusManager.setCurrentKeyboardFocusManager()"); } if (!(KeyboardFocusManager.getCurrentKeyboardFocusManager() instanceof MyKeyboardFocusManager)) { return failed("\n getCurrentKeyboardFocusManager() failed"); } myKFM.clearGlobalFocusOwner(); frm.setVisible(true); /* Wait for a frame to become painted */ sleep(getPaintTimeout()); Window activeWindow = myKFM.getActiveWindow(); if (activeWindow == null) { return failed("\nKeyboardFocusManager#getActiveWindow() " + "returned null"); } myKFM.setGlobalActiveWindow(frm); Frame globalActiveWindow = (Frame) myKFM.getGlobalActiveWindow(); if (globalActiveWindow == null || globalActiveWindow.getTitle().equals("My Frame") == false) { return failed("\nKeyboardFocusManager#getGlobalActiveWindow() " + "returned:" + globalActiveWindow); } myKFM.setGlobalFocusedWindow(frm); Frame globalFocusedWindow = (Frame) myKFM.getGlobalFocusedWindow(); if (myKFM.getGlobalFocusedWindow() == null || !(myKFM.getGlobalFocusedWindow() instanceof Frame)) { return failed("\nKeyboardFocusManager#getGlobalFocusedWindow() " + "returned: " + globalFocusedWindow); } /* Get instance of btnClose button */ Button btn1 = (Button) ((Container) frm.getComponents()[0]) .getComponents()[1]; myKFM.setGlobalFocusOwner(btn1); Button globalFocusOwner = (Button) myKFM.getGlobalFocusOwner(); if (globalFocusOwner == null || globalFocusOwner.getLabel().equals("MyLoafer") == false) { return failed("\nKeyboardFocusManager#getGlobalFocusOwner() " + "returned the wrong value:" + globalFocusOwner); } myKFM.setGlobalPermanentFocusOwner(btn1); Button globalPermanentFocusOwner = (Button) myKFM .getGlobalPermanentFocusOwner(); if (globalPermanentFocusOwner == null || globalPermanentFocusOwner.getLabel().equals("MyLoafer") == false) { return failed("\nKeyboardFocusManager#globalPermanentFocusOwner() " + "returned the wrong value:" + globalPermanentFocusOwner); } sleep(getPaintTimeout()); Frame focusedWindow = (Frame) myKFM.getFocusedWindow(); if (focusedWindow == null || focusedWindow.getTitle().equals("My Frame") == false) { return failed("\nKeyboardFocusManager#getFocusedWindow() " + "returned the wrong value:" + focusedWindow); } // TODO why does requestFocusInWindow does not help retrieving correct // object using getFocusOwner? // btn0.requestFocusInWindow(); waitEventQueueToClear(); sleep(getPaintTimeout()); Button focusOwner = (Button) myKFM.getFocusOwner(); if (focusOwner == null || focusOwner.getLabel().equals("MyLoafer") == false) { return failed("\nKeyboardFocusManager#getFocusOwner() " + "returned the wrong value:" + focusOwner); } myKFM.clearGlobalFocusOwner(); myKFM.setGlobalCurrentFocusCycleRoot(frm); Frame currentFocusCycleRoot = (Frame) myKFM.getCurrentFocusCycleRoot(); if (currentFocusCycleRoot == null || currentFocusCycleRoot.getTitle().equals("My Frame") == false) { return failed("\nKeyboardFocusManager#getGlobalActiveWindow() " + "returned null"); } return passed(); } public Result testKeyboardFocusManager_getKeyProperties() { DefaultKeyboardFocusManager myKFM = new DefaultKeyboardFocusManager(); /* Install tested DefaultKeyboardFocusManager */ try { KeyboardFocusManager.setCurrentKeyboardFocusManager(myKFM); } catch (SecurityException e) { return failed("\nFor some reason it is not allowed to call " + "KeyboardFocusManager.setCurrentKeyboardFocusManager()"); } frm.setVisible(true); Button btn = (Button) ((Container) frm.getComponents()[0]) .getComponents()[0]; btn.requestFocus(); if (btn.getFocusTraversalKeysEnabled()) { String firstLabel = btn.getLabel(); String secondLabel = ""; Button mostRecentFocusOwner = null; /* Get keys (if any) that can travese focus forward */ Set backwardTravKeys = myKFM .getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); boolean exceptionFired = false; try { myKFM.setDefaultFocusTraversalKeys( KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, backwardTravKeys); } catch (IllegalArgumentException e) { exceptionFired = true; } if (exceptionFired == false) { return failed("\nNo IllegalArgumentException exception fired " + "when focus traversal keys are unique for a Component"); } Set travKeys = myKFM .getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); /* In case there are key that can traverse focus forward */ Iterator it = travKeys.iterator(); if (it.hasNext()) { /* get 1st supported key that can traverse focus forward */ AWTKeyStroke travKey = (AWTKeyStroke) it.next(); /* * send that key to the component, we assume that this should be * btnDoNothing, because we were able to get forward traversal * keys on btnClose */ myKFM.redispatchEvent(btn, provideKeyEvent(travKey .getModifiers(), travKey.getKeyCode(), travKey .getKeyChar())); /* Wait until the window gets painted, etc. */ waitEventQueueToClear(); sleep(getPaintTimeout()); /* * There are only two buttons in the frame, this is why we * assume that focus could only move from button that was added * first, to the button that wass added second. See setUp() for * details */ mostRecentFocusOwner = (Button) frm.getMostRecentFocusOwner(); secondLabel = mostRecentFocusOwner.getLabel(); if (firstLabel.equals(secondLabel) == true) { return failed("\nKeyboardFocusManager#redispatchEvent " + "failed to move focus to the next component"); } } } return passed(); } public Result testKeyboardFocusManager_focusTraversalPolicy() { MyKeyboardFocusManager myKFM = new MyKeyboardFocusManager(); boolean exceptionFired = false; try { myKFM.setDefaultFocusTraversalPolicy(null); } catch (IllegalArgumentException e) { exceptionFired = true; } if (exceptionFired == false) { return failed("\nNo IllegalArgumentException exception fired " + "when setDefaultFocusTraversalPolicy gets null"); } FocusTraversalPolicy focTravPol = myKFM .getDefaultFocusTraversalPolicy(); if (((Frame) focTravPol.getInitialComponent(frm)).getTitle().equals( "My Frame") == false) { return failed("\nKeyboardFocusManager#getDefaultFocusTraversalPolicy()" + "has wrong initial component"); } // TODO perhaps getFirstComponent(frm) should not return null return passed(); } }src/main/java/com/food/order/model/entity/BaseEntity.java package com.food.order.model.entity; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import javax.persistence.*; import java.io.Serializable; import java.util.Date; @Data @MappedSuperclass public class BaseEntity implements Serializable { protected Long saasStoreId = 1l;//预留saas服务,当前默认为1 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) protected Long id; @JsonIgnore protected boolean isDelete = false; @Temporal(value = TemporalType.TIMESTAMP) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") protected Date updateTime = new Date(); @Temporal(value = TemporalType.TIMESTAMP) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") protected Date createTime = new Date(); }lgcy/common/src/main/java/org/tron/common/utils/JsonUtil.java package org.tron.common.utils; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.util.StringUtils; public class JsonUtil { public static final T json2Obj(String jsonString, Class clazz) { if (!StringUtils.isEmpty(jsonString) && clazz != null) { try { ObjectMapper om = new ObjectMapper(); return om.readValue(jsonString, clazz); } catch (Exception var3) { throw new RuntimeException(var3); } } else { return null; } } public static final String obj2Json(Object obj) { if (obj == null) { return null; } else { ObjectMapper om = new ObjectMapper(); try { return om.writeValueAsString(obj); } catch (Exception var3) { throw new RuntimeException(var3); } } } } package test; import nodes.LightNode; import nodes.MinerNode; import nodes.Node; import nodes.NormalNode; import org.apache.commons.io.FileUtils; import structures.Block; import test.utils.TestUtilities; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; public class ResultTestModule{ public static void main(String[] args) { int[] blockSizes = new int[]{500,1000,1500,2000,2500}; int[] thresholds = new int[]{1,2,3}; int[] thresholdsWeight = new int[]{1,2,3,4,5}; String resultsFolder = "results/"; //content of config file String configContent = "max_cache_size 100\n" + "time_restraint 90000\n" + "network_topology 0 7000 7019 2\n" + "miner_node localhost 7020\n" + "full_node localhost 7021\n" + "storage 0"; //delete directory try{ FileUtils.deleteDirectory(new File(resultsFolder)); } catch (IOException ex){ ex.printStackTrace(); } String[] categories = new String[]{"marketplace"}; String[] topLevelFolders = new String[]{ "interest_based_IB", "threshold_based_TB", "threshold_weight_based_WTB", "interest_based_block_size_IBBS", "threshold_based_block_size_TBBS", "threshold_based_recency_TBR", "pyramid_scheme_interest_based_IBPS" }; String[] distributions = new String[]{ "exponential_distribution", "poisson_distribution", "normal_distribution", "uniform_distribution", "zipfian_distribution" }; //Folders that indicate whether miner groups transactions or not String[] groupFolders = new String[]{ "transaction_group", "no_transaction_group" }; //names for folders that indicate block size String[] blockSizeFolders = new String[blockSizes.length-1]; String prefix = "block_size_min"; String middle = "_max"; for(int i = 0; i < blockSizes.length - 1; i++){ blockSizeFolders[i] = prefix + blockSizes[i] + middle + blockSizes[i+1]; } //folders for thresholds String[] thresholdFolders = new String[thresholds.length]; String[] thresholdWeightFolders = new String[thresholdsWeight.length]; prefix = "threshold_"; for(int i = 0; i < thresholds.length;i++){ thresholdFolders[i] = prefix + (i+1); } prefix = "threshold_weight_"; for(int i = 0; i < thresholdsWeight.length;i++){ thresholdWeightFolders[i] = prefix + (i+1); } /*Now that everything is setup create folder structure*/ for(String s0 : categories){ new File(resultsFolder + s0); for(String s1 : topLevelFolders){ System.out.println("IN CONFIGURATION " + s1); new File(resultsFolder + s0 + "/" + s1).mkdirs(); for(String s2 : blockSizeFolders){ new File(resultsFolder + s0 + "/" + s1 + "/" + s2).mkdirs(); for(String s3 : groupFolders){ new File(resultsFolder + s0 + "/" + s1 + "/" + s2 + "/" + s3).mkdirs(); if(s1.contains("threshold_weight")){ for(String s4 : thresholdWeightFolders){ String dest = resultsFolder + s0 + "/" + s1 + "/" + s2 + "/" + s3 + "/" + s4; new File(dest).mkdirs(); createConfigFile(configContent,s2,s3,s1,s4); testLocal( dest + "/", s0,distributions); } } else if(s1.contains("threshold")){ for(String s4 : thresholdFolders){ String dest = resultsFolder + s0 + "/" + s1 + "/" + s2 + "/" + s3 + "/" + s4; new File(dest).mkdirs(); createConfigFile(configContent,s2,s3,s1,s4); testLocal(dest + "/", s0,distributions); } } else{ String dest = resultsFolder + s0 + "/" + s1 + "/" + s2 + "/" + s3 + "/"; createConfigFile(configContent,s2,s3,s1,"dummy_1"); testLocal(dest,s0,distributions); } } } } } } public static void testLocal(String destPath,String category, String[] distributions){ TestUtilities testUtilities = new TestUtilities(category,false); /*create normal and light nodes. The nodes are now setup*/ testUtilities.initLocalOldFiles(10, 10, new int[]{70, 20, 10}, new int[]{70, 20, 10}); /*create miner node*/ MinerNode minerNode = testUtilities.createMiner(); for(String distribution : distributions) { /*How many blocks to create?*/ Block block; HashMap transaction; Node[] nodes = testUtilities.nodes; for(Node n : nodes){ if (n instanceof NormalNode) { ((NormalNode) n).cacheManager.clearAll(); } else if (n instanceof LightNode) { ((LightNode) n).cacheManager.clearAll(); } } long blockChainSize = 0; for (int i = 0; i < 10; i++) { while (true) { /*Add transactions until enough for block*/ transaction = getTransaction(testUtilities,distribution); block = minerNode.addTransactionLocal(transaction); if (block != null) { blockChainSize += block.blockSize; break; } } /*Now add block to each node*/ for (Node n : nodes) { if (n instanceof NormalNode) { ((NormalNode) n).checkBlock(block); } else if (n instanceof LightNode) { ((LightNode) n).checkBlock(block); } } } File blockResults = new File(destPath + distribution + "_blocks.txt"); File sizeResultsNormal = new File(destPath + distribution + "_size_normal.txt"); File sizeResultsLight = new File(destPath + distribution + "_size_light.txt"); File overallSize = new File(destPath + distribution + "full_block_chain_size.txt"); try{ PrintWriter writerBlocks = new PrintWriter(blockResults); PrintWriter writerSizeNormal = new PrintWriter(sizeResultsNormal); PrintWriter writerSizeLight = new PrintWriter(sizeResultsLight); PrintWriter allSizeWriter = new PrintWriter(overallSize); allSizeWriter.println(blockChainSize); for (Node n : nodes) { if (n instanceof NormalNode) { writerBlocks.println(((NormalNode) n).cacheManager.getBlocksInCache().size()); writerSizeNormal.println(((NormalNode) n).cacheManager.getSizeOfCachedBlocks()); } else if (n instanceof LightNode) { writerBlocks.println(((LightNode) n).cacheManager.getBlocksInCache().size()); writerSizeLight.println(((LightNode) n).cacheManager.getSizeOfCachedBlocks()); } } writerBlocks.flush(); writerSizeNormal.flush(); writerSizeLight.flush(); writerBlocks.close(); writerSizeNormal.close(); writerSizeLight.close(); allSizeWriter.flush(); allSizeWriter.close(); } catch (IOException ex){ ex.printStackTrace(); } } } public static HashMap getTransaction(TestUtilities t, String distribution){ HashMap transaction; switch (distribution){ case "exponential_distribution": transaction = t.getTransactionExponential(); break; case "poisson_distribution": transaction = t.getTransactionPoisson(); break; case "normal_distribution": transaction = t.getTransactionNormal(); break; case "uniform_distribution": transaction = t.getTransactionUniform(); break; case "zipfian_distribution": transaction = t.getTransactionZipfian(); break; default: transaction = null; } return transaction; } public static void createConfigFile(String configContent,String sizes, String group,String cacheConfig, String thresholdString){ String config = "cache_configuration\t"; int threshold = Integer.parseInt(thresholdString.substring(thresholdString.length()-1)); switch (cacheConfig){ case "interest_based_IB": config += "1\t1"; break; case "threshold_based_TB": config += "6\t" + threshold; break; case "threshold_weight_based_WTB": config += "2\t" + threshold; break; case "interest_based_block_size_IBBS": config += "3\t1"; break; case "threshold_based_block_size_TBBS": config += "4\t" + threshold; break; case "threshold_based_recency_TBR": config += "5\t" + threshold; break; case "pyramid_scheme_interest_based_IBPS": config+= "7\t1"; } boolean groupTransactions = false; if(group.equals("transaction_group")){ groupTransactions = true; } else if(group.equals("no_transaction_group")){ groupTransactions = false; } int min = Integer.parseInt(sizes.substring(sizes.indexOf("min")+3,sizes.indexOf("max")-1)); int max = Integer.parseInt(sizes.substring(sizes.indexOf("max")+3)); /*have to create config file*/ File configFile = new File("src/test/resources/node_config.txt"); try{ PrintWriter writer = new PrintWriter(configFile); writer.println(configContent); writer.println("min_block_size\t" + min); writer.println("max_block_size\t" + max); writer.println("group_content\t" + groupTransactions + "\t0"); writer.println(config); writer.flush(); writer.close(); } catch (IOException ex){ ex.printStackTrace(); } } } /** * This program reads numbers from a file. It computes the sum and * the average of the numbers that it reads. The file should contain * nothing but numbers of type double; if this is not the case, the * output will be the sum and average of however many numbers were * successfully read from the file. The name of the file will be * input by the user. */ public class AverageNumbersFromFile { public static void main(String[] args) { while (true) { String fileName; // The name of the file, to be input by the user. System.out.print("Enter the name of the file: "); fileName = TextIO.getln(); try { TextIO.readFile( fileName ); // Try to open the file for input. break; // If that succeeds, break out of the loop. } catch ( IllegalArgumentException e ) { System.out.println("Can't read from the file \"" + fileName + "\"."); System.out.println("Please try again.\n"); } } /* At this point, TextIO is reading from the file. */ double number; // A number read from the data file. double sum; // The sum of all the numbers read so far. int count; // The number of numbers that were read. sum = 0; count = 0; try { while (true) { // Loop ends when an exception occurs. number = TextIO.getDouble(); count++; // This is skipped when the exception occurs sum += number; } } catch ( IllegalArgumentException e ) { // We expect this to occur when the end-of-file is encountered. // We don't consider this to be an error, so there is nothing to do // in this catch clause. Just proceed with the rest of the program. } // At this point, we've read the entire file. System.out.println(); System.out.println("Number of data values read: " + count); System.out.println("The sum of the data values: " + sum); if ( count == 0 ) System.out.println("Can't compute an average of 0 values."); else System.out.println("The average of the values: " + (sum/count)); } }1-10 package org.kuali.ole.sip2.service; import org.kuali.ole.deliver.bo.FeeType; import org.kuali.ole.deliver.bo.OleItemLevelBillPayment; import org.kuali.ole.deliver.bo.OlePaymentStatus; import org.kuali.ole.ncip.bo.OLEItemFine; import org.kuali.rice.core.api.util.type.KualiDecimal; import java.math.BigDecimal; import java.util.List; /** * Created by sheiksalahudeenm on 12/30/14. */ public interface OLESIP2HelperService { public OLENettyServer doActionForSocketServer(String action, StringBuffer responseString, OLENettyServer olesip2Server); public OLENettyServer startOLESip2Server(StringBuffer responseString, OLENettyServer olesip2Server); public void stopOLESip2Server(StringBuffer responseString, OLENettyServer olesip2Server); public void startOLESip2Server(); public void stopOLESip2Server(); public OlePaymentStatus getPaymentStatus(String paymentStatus); public KualiDecimal itemWiseFeePaid(List feeTypes, KualiDecimal paymentAmount, String paymentMethod, String fullyPaidStatus, String partiallyPaidStatus, String forgiveErrorNote, String transactionNumber, String transactionNote, String paidByUser, List currentSessionTransactions); public String feePaid(String patronBarcode, String feeTypeCode, String feeTypeId, String paymentMethod, KualiDecimal paymentAmount, String transactionNumber, String paidByUser); public BigDecimal calculateTotalFineBalance(List oleItemFineList); } package edu.fiuba.algo3.modelo.Juego; import edu.fiuba.algo3.modelo.Ciudad.Ciudad; import edu.fiuba.algo3.modelo.Ciudad.Mapa; import edu.fiuba.algo3.modelo.Item.Item; import edu.fiuba.algo3.modelo.Ladron.Ladron; import edu.fiuba.algo3.modelo.Lector.*; import edu.fiuba.algo3.modelo.Policia.Policia; import java.util.ArrayList; import java.util.Map; public class DatosJuego { LectorLadron lectorLadron = new LectorLadron(); LectorItem lectorItem = new LectorItem(); LectorCiudad lectorCiudad = new LectorCiudad(); Map ciudades = null; LectorPolicia lectorPolicia = new LectorPolicia(); LectorMapa lectorMapa = new LectorMapa(); public DatosJuego() { } public ArrayList leerLadrones() throws LectorException { return lectorLadron.leerLadrones(); } public ArrayList leerItems() throws LectorException { return lectorItem.leerItems(); } public Map leerCiudades() throws LectorException { if(null != ciudades) { return ciudades; } return ciudades = lectorCiudad.leerCiudades(); } public Mapa leerMapa(Map ciudades) throws LectorException { return lectorMapa.leerMapa(new Mapa(leerCiudades())); } public ArrayList leerPolicias() throws LectorException { return lectorPolicia.leerPolicias(); } } mch166/houdaexam package com.eliteams.quick4j.test.service; import java.util.Date; import javax.annotation.Resource; import com.eliteams.quick4j.core.util.ApplicationUtils; import org.junit.Test; import com.eliteams.quick4j.core.feature.test.TestSupport; import com.eliteams.quick4j.web.model.User; import com.eliteams.quick4j.web.service.UserService; public class UserServiceTest extends TestSupport { @Resource private UserService userService; @Test public void test_insert() { User model = new User(); model.setUsername("admin"); model.setPassword(ApplicationUtils.sha("")); model.setCreateTime("2018-06-26"); model.setType(1); userService.insert(model); } //@Test public void test_10insert() { for (int i = 0; i < 10; i++) { User model = new User(); model.setUsername("starzou" + i); model.setPassword(ApplicationUtils.("")); model.setCreateTime("2018-06-26"); userService.insert(model); } } } import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; 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.common.serialization.LongDeserializer; import org.apache.kafka.common.serialization.StringDeserializer; import java.util.Collections; import java.util.Properties; public class KafkaConsumerCassandraWriter { private final static String TOPIC = "github-stream-output"; private final static String BOOTSTRAP_SERVERS = "localhost:9092"; private static Consumer createConsumer() { final Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS); props.put(ConsumerConfig.GROUP_ID_CONFIG, "KafkaConsumerTest"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); // Create the consumer using props. final Consumer consumer = new KafkaConsumer<>(props); // Subscribe to the topic. consumer.subscribe(Collections.singletonList(TOPIC)); return consumer; } private static void runConsumer() throws InterruptedException { System.out.println("runConsumer()"); final Consumer consumer = createConsumer(); Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(9042).build(); Session session = cluster.connect("giteventskeyspace"); final int giveUp = 100; int noRecordsCount = 0; while (true) { System.out.println("dentro while"); final ConsumerRecords consumerRecords = consumer.poll(1000); if(consumerRecords.count() == 0) { noRecordsCount++; if(noRecordsCount > giveUp) break; else continue; } noRecordsCount = 0; PreparedStatement preparedInsertStatement = session.prepare( "INSERT INTO events JSON :json" ); BoundStatement insertStatement = preparedInsertStatement .bind(); consumerRecords.forEach(record -> { String json = record.value(); System.out.println(json); insertStatement.setString("json", json); session.execute(insertStatement); System.out.println("Inserted"); }); consumer.commitAsync(); } session.close(); consumer.close(); System.out.println("DONE"); } public static void main(String... args) throws Exception { runConsumer(); } } package daos; import models.ApiKey; public class ApiKeyDAO extends EbeanBaseDAO { public ApiKey getByUserId(Integer userId) { return super.findUniqueByProperty("user.id", userId); } public ApiKey getByToken(String token) { return super.findUniqueByProperty("token", token); } } package ir.unitycorn.app.activities; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Bundle; import androidx.core.content.res.ResourcesCompat; import com.chyrta.onboarder.OnboarderActivity; import com.chyrta.onboarder.OnboarderPage; import java.util.ArrayList; import java.util.List; import es.dmoral.toasty.Toasty; import io.github.inflationx.viewpump.ViewPumpContextWrapper; import ir.unitycorn.app.R; public class IntroActivity extends OnboarderActivity { SharedPreferences settingsPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); settingsPrefs = getSharedPreferences("settings", Context.MODE_PRIVATE); //Initialize Toasty Typeface iranSans = ResourcesCompat.getFont(getApplicationContext(), R.font.iransans); Toasty.Config.getInstance() .setToastTypeface(iranSans) .allowQueue(false) .apply(); List onboarderPages = new ArrayList<>(); //Page I OnboarderPage onboarderPage1 = new OnboarderPage(R.string.intro_title_1, R.string.intro_description_1, R.drawable.intro_pic_1); onboarderPage1.setTitleColor(settingsPrefs.getBoolean("dark_mode", false) ? android.R.color.white : android.R.color.black); onboarderPage1.setDescriptionColor(settingsPrefs.getBoolean("dark_mode", false) ? android.R.color.white : android.R.color.black); onboarderPage1.setBackgroundColor(settingsPrefs.getBoolean("dark_mode", false) ? R.color.colorPrimaryDark : R.color.colorAccent); onboarderPages.add(onboarderPage1); //Page II OnboarderPage onboarderPage2 = new OnboarderPage(R.string.intro_title_2, R.string.intro_description_2, R.drawable.intro_pic_2); onboarderPage2.setTitleColor(settingsPrefs.getBoolean("dark_mode", false) ? android.R.color.white : android.R.color.black); onboarderPage2.setDescriptionColor(settingsPrefs.getBoolean("dark_mode", false) ? android.R.color.white : android.R.color.black); onboarderPage2.setBackgroundColor(settingsPrefs.getBoolean("dark_mode", false) ? R.color.colorPrimaryDark : R.color.colorAccent); onboarderPages.add(onboarderPage2); //Page III OnboarderPage onboarderPage3 = new OnboarderPage(R.string.intro_title_3, R.string.intro_description_3, R.drawable.intro_pic_3); onboarderPage3.setTitleColor(settingsPrefs.getBoolean("dark_mode", false) ? android.R.color.white : android.R.color.black); onboarderPage3.setDescriptionColor(settingsPrefs.getBoolean("dark_mode", false) ? android.R.color.white : android.R.color.black); onboarderPage3.setBackgroundColor(settingsPrefs.getBoolean("dark_mode", false) ? R.color.colorPrimaryDark : R.color.colorAccent); onboarderPages.add(onboarderPage3); setSkipButtonHidden(); setFinishButtonTitle(settingsPrefs.getBoolean("intro_viewed", false) ? R.string.intro_button_after_intro_viewed : R.string.intro_button_before_intro_viewed); setOnboardPagesReady(onboarderPages); } @Override public void onFinishButtonPressed() { exitTheIntro(); } @Override public void onBackPressed() { super.onBackPressed(); exitTheIntro(); } private void exitTheIntro(){ if(settingsPrefs.getBoolean("intro_viewed", false)){ //This Means The Intro Has Opened From About Activity finish(); }else{ settingsPrefs.edit().putBoolean("intro_viewed", true).apply(); Toasty.custom(this, getResources().getString(R.string.intro_toast_message), null, getResources().getColor(R.color.colorPrimary), getResources().getColor(android.R.color.white), Toasty.LENGTH_LONG, false, true).show(); Intent mainActivityIntent = new Intent(IntroActivity.this, MainActivity.class); IntroActivity.this.startActivity(mainActivityIntent); IntroActivity.this.finish(); } } //Change Default Font To Iran Sans @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase)); } } ZhangPeng1990/crm package uk.co.quidos.gdsap.evaluation.persistence.object; import uk.co.quidos.dal.object.AbstractDO; /** * @author peng.shi * */ public class GdsapEvalImprovement extends AbstractDO { private static final long serialVersionUID = 2237407262003051443L; private Long id; private Integer improvementCategory; private String improvementType; private Float typicalSaving; private Float energyPerformanceRating; private Float environmentalImpactRating; private Integer recommendationCode; private String indicativeCost; private Integer greenDealCategory; private Integer scope; private Long reportId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getImprovementCategory() { return improvementCategory; } public void setImprovementCategory(Integer improvementCategory) { this.improvementCategory = improvementCategory; } public String getImprovementType() { return improvementType; } public void setImprovementType(String improvementType) { this.improvementType = improvementType; } public Float getTypicalSaving() { return typicalSaving; } public void setTypicalSaving(Float typicalSaving) { this.typicalSaving = typicalSaving; } public Float getEnergyPerformanceRating() { return energyPerformanceRating; } public void setEnergyPerformanceRating(Float energyPerformanceRating) { this.energyPerformanceRating = energyPerformanceRating; } public Float getEnvironmentalImpactRating() { return environmentalImpactRating; } public void setEnvironmentalImpactRating(Float environmentalImpactRating) { this.environmentalImpactRating = environmentalImpactRating; } public Integer getRecommendationCode() { return recommendationCode; } public void setRecommendationCode(Integer recommendationCode) { this.recommendationCode = recommendationCode; } public String getIndicativeCost() { return indicativeCost; } public void setIndicativeCost(String indicativeCost) { this.indicativeCost = indicativeCost; } public Integer getGreenDealCategory() { return greenDealCategory; } public void setGreenDealCategory(Integer greenDealCategory) { this.greenDealCategory = greenDealCategory; } public Integer getScope() { return scope; } public void setScope(Integer scope) { this.scope = scope; } public Long getReportId() { return reportId; } public void setReportId(Long reportId) { this.reportId = reportId; } }lcj325/lilac0 package com.snail.lilac.model.security; import java.io.Serializable; /** * @author Andy * @since 2013-5-15 */ public class ShiroUser implements Serializable { /** * */ private static final long serialVersionUID = -3801134735205895939L; public UserInfo user; public String url; /** * @param user */ public ShiroUser(UserInfo user){ super(); this.user = user; } /** * @return the user */ public UserInfo getUser() { return user; } /** * @param user the user to set */ public void setUser(UserInfo user) { this.user = user; } /** * @return the url */ public String getUrl() { return url; } /** * @param url the url to set */ public void setUrl(String url) { this.url = url; } } src/com/frostvoid/trekwar/client/gui/BottomMenu/EmptyPanel.java /* * Copyright 2012 FrostVoid Software * * 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.frostvoid.trekwar.client.gui.BottomMenu; import com.frostvoid.trekwar.client.Client; import com.frostvoid.trekwar.client.FontFactory; import com.frostvoid.trekwar.client.ImageManager; import com.frostvoid.trekwar.common.StarSystem; import javax.swing.*; import java.awt.*; /** * Empty space system info for bottom menu * * @author * @author FrostVoid Software * @author http://www.frostvoid.com */ public class EmptyPanel extends JPanel implements Runnable { private Image backgroundImage; private int backgroundX = 0; private long frameCount = 0; private Graphics buffer; private Image offscreen; Thread animThread; private boolean doAnim; private JLabel textLabel, sectorLabel; private SensorPanel sensorPanel; public EmptyPanel() { setBounds(5, 5, 770, 165); setLayout(null); backgroundImage = ImageManager.getInstance().getImage("graphics/empty_background.jpg").getImage(); animThread = new Thread(this); doAnim = true; animThread.start(); textLabel = new JLabel(Client.getLanguage().get("empty_space")); textLabel.setFont(FontFactory.getInstance().getHeading1()); textLabel.setBounds(15, 10, 300, 50); add(textLabel); sectorLabel = new JLabel(Client.getLanguage().get("sector")); sectorLabel.setFont(FontFactory.getInstance().getHeading3()); sectorLabel.setBounds(25, 35, 200, 50); add(sectorLabel); sensorPanel = new SensorPanel(); sensorPanel.setLocation(340, 20); add(sensorPanel); } public void setSystem(StarSystem s) { sectorLabel.setText(Client.getLanguage().get("sector") + ": " + s.getX() + ":" + s.getY()); sensorPanel.setSystem(s); } @Override public void run() { while (true) { try { Thread.sleep(1000 / 60); } catch (InterruptedException e) { } if (doAnim) { frameCount++; if (frameCount % 2 == 0) { backgroundX -= 1; } if (backgroundX <= -2200) { backgroundX = 0; } repaint(); } } } @Override public void paint(Graphics g) { if (offscreen == null) { offscreen = createImage(this.getSize().width, this.getSize().height); buffer = offscreen.getGraphics(); } buffer.clearRect(0, 0, 780, 175); buffer.drawImage(backgroundImage, backgroundX, 0, this); g.drawImage(offscreen, 0, 0, this); paintComponents(g); } @Override public void update(Graphics g) { paint(g); } public void animStart() { doAnim = true; backgroundX = 0; } public void animPause() { doAnim = false; } }/** * * Copyright 2010, . * * This 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 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * * User: * Date: Mar 26, 2010 * */ package play.modules.excel; import org.apache.commons.codec.net.URLCodec; import play.PlayPlugin; import play.exceptions.UnexpectedException; import play.mvc.Http.Header; import play.mvc.Http.Request; import play.mvc.Http.Response; import play.mvc.Scope; import play.mvc.Scope.RenderArgs; import play.mvc.Scope.Session; import play.mvc.results.Result; import play.templates.Template; import play.vfs.VirtualFile; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; public class Plugin extends PlayPlugin { public static PlayPlugin templateLoader; private static final Pattern p_ = Pattern.compile(".*\\.(xls|xlsx)"); @Override public Optional